blob: 1a7db26f56d661190aa69428387589399e40b286 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +090027#define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
28#define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
François Gaffief4ad6e52015-11-19 16:59:57 +010029
Eric Laurentd4692962014-05-05 18:13:44 -070030#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070031#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070032
François Gaffie2110e042015-03-24 08:41:51 +010033#include <AudioPolicyManagerInterface.h>
34#include <AudioPolicyEngineInstance.h>
Mathias Agopian05d19b02017-02-28 16:28:19 -080035#include <cutils/atomic.h>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070037#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070041#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070042#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010045#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010047#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010048#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010049#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010050#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070051
Eric Laurent3b73df72014-03-11 09:06:29 -070052namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070053
Eric Laurentdc462862016-07-19 12:29:53 -070054//FIXME: workaround for truncated touch sounds
55// to be removed when the problem is handled by system UI
56#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070057// ----------------------------------------------------------------------------
58// AudioPolicyInterface implementation
59// ----------------------------------------------------------------------------
60
Eric Laurente0720872014-03-11 09:30:41 -070061status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080062 audio_policy_dev_state_t state,
63 const char *device_address,
64 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070065{
Paul McLeane743a472015-01-28 11:07:31 -080066 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080067}
68
François Gaffie44481e72016-04-20 07:49:57 +020069void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
70 audio_policy_dev_state_t state,
71 const String8 &device_address)
72{
73 AudioParameter param(device_address);
74 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070075 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020076 param.addInt(key, device);
77 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
78}
79
Eric Laurentc73ca6e2014-12-12 14:34:22 -080080status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080081 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080082 const char *device_address,
83 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080084{
Paul McLeane743a472015-01-28 11:07:31 -080085 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
86- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070087
88 // connect/disconnect only 1 device at a time
89 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
90
François Gaffie53615e22015-03-19 09:24:12 +010091 sp<DeviceDescriptor> devDesc =
92 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080093
Eric Laurente552edb2014-03-10 17:42:56 -070094 // handle output devices
95 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070096 SortedVector <audio_io_handle_t> outputs;
97
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
99
Eric Laurente552edb2014-03-10 17:42:56 -0700100 // save a copy of the opened output descriptors before any output is opened or closed
101 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
102 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700103 switch (state)
104 {
105 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800106 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700107 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700108 ALOGW("setDeviceConnectionState() device already connected: %x", device);
109 return INVALID_OPERATION;
110 }
111 ALOGV("setDeviceConnectionState() connecting device %x", device);
112
Eric Laurente552edb2014-03-10 17:42:56 -0700113 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114 index = mAvailableOutputDevices.add(devDesc);
115 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100116 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700117 if (module == 0) {
118 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
119 device);
120 mAvailableOutputDevices.remove(devDesc);
121 return INVALID_OPERATION;
122 }
Paul McLeane743a472015-01-28 11:07:31 -0800123 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124 } else {
125 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700126 }
127
François Gaffie44481e72016-04-20 07:49:57 +0200128 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
129 // parameters on newly connected devices (instead of opening the outputs...)
130 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
131
Eric Laurenta1d525f2015-01-29 13:36:45 -0800132 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700133 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200134
135 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
136 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700137 return INVALID_OPERATION;
138 }
François Gaffie2110e042015-03-24 08:41:51 +0100139 // Propagate device availability to Engine
140 mEngine->setDeviceConnectionState(devDesc, state);
141
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700142 // outputs should never be empty here
143 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
144 "checkOutputsForDevice() returned no outputs but status OK");
145 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
146 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800147
Eric Laurent3ae5f312015-02-03 17:12:08 -0800148 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700149 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700150 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700151 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700152 ALOGW("setDeviceConnectionState() device not connected: %x", device);
153 return INVALID_OPERATION;
154 }
155
Paul McLean5c477aa2014-08-20 16:47:57 -0700156 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
157
Paul McLeane743a472015-01-28 11:07:31 -0800158 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200159 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700160
Eric Laurente552edb2014-03-10 17:42:56 -0700161 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700163
Eric Laurenta1d525f2015-01-29 13:36:45 -0800164 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100165
166 // Propagate device availability to Engine
167 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700168 } break;
169
170 default:
171 ALOGE("setDeviceConnectionState() invalid state: %x", state);
172 return BAD_VALUE;
173 }
174
Eric Laurent3a4311c2014-03-17 12:00:47 -0700175 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
176 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700177 checkA2dpSuspend();
178 checkOutputForAllStrategies();
179 // outputs must be closed after checkOutputForAllStrategies() is executed
180 if (!outputs.isEmpty()) {
181 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700182 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700183 // close unused outputs after device disconnection or direct outputs that have been
184 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700185 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700186 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
187 (desc->mDirectOpenCount == 0))) {
188 closeOutput(outputs[i]);
189 }
190 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 // check again after closing A2DP output to reset mA2dpSuspended if needed
192 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700193 }
194
195 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700196 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700197 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
198 updateCallRouting(newDevice);
199 }
Eric Laurente552edb2014-03-10 17:42:56 -0700200 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
202 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
203 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700204 // do not force device change on duplicated output because if device is 0, it will
205 // also force a device 0 for the two outputs it is duplicated to which may override
206 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700207 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100208 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700209 // always force when disconnecting (a non-duplicated device)
210 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700211 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700212 }
Eric Laurente552edb2014-03-10 17:42:56 -0700213 }
214
Eric Laurentd60560a2015-04-10 11:31:20 -0700215 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
216 cleanUpForDevice(devDesc);
217 }
218
Eric Laurent72aa32f2014-05-30 18:51:48 -0700219 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700220 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700221 } // end if is output device
222
Eric Laurente552edb2014-03-10 17:42:56 -0700223 // handle input devices
224 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700225 SortedVector <audio_io_handle_t> inputs;
226
Eric Laurent3a4311c2014-03-17 12:00:47 -0700227 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700228 switch (state)
229 {
230 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700231 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700233 ALOGW("setDeviceConnectionState() device already connected: %d", device);
234 return INVALID_OPERATION;
235 }
François Gaffie53615e22015-03-19 09:24:12 +0100236 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700237 if (module == NULL) {
238 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
239 device);
240 return INVALID_OPERATION;
241 }
François Gaffie44481e72016-04-20 07:49:57 +0200242
243 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
244 // parameters on newly connected devices (instead of opening the inputs...)
245 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
246
Paul McLean9080a4c2015-06-18 08:24:02 -0700247 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200248 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
249 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700250 return INVALID_OPERATION;
251 }
252
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 index = mAvailableInputDevices.add(devDesc);
254 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800255 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700256 } else {
257 return NO_MEMORY;
258 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800259
François Gaffie2110e042015-03-24 08:41:51 +0100260 // Propagate device availability to Engine
261 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700262 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700263
264 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700265 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700266 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700267 ALOGW("setDeviceConnectionState() device not connected: %d", device);
268 return INVALID_OPERATION;
269 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700270
271 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
272
273 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200274 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700275
Paul McLean9080a4c2015-06-18 08:24:02 -0700276 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700277 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700278
François Gaffie2110e042015-03-24 08:41:51 +0100279 // Propagate device availability to Engine
280 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700281 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700282
283 default:
284 ALOGE("setDeviceConnectionState() invalid state: %x", state);
285 return BAD_VALUE;
286 }
287
Eric Laurentd4692962014-05-05 18:13:44 -0700288 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700289 // As the input device list can impact the output device selection, update
290 // getDeviceForStrategy() cache
291 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700292
Eric Laurent87ffa392015-05-22 10:32:38 -0700293 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700294 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
295 updateCallRouting(newDevice);
296 }
297
Eric Laurentd60560a2015-04-10 11:31:20 -0700298 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
299 cleanUpForDevice(devDesc);
300 }
301
Eric Laurentb52c1522014-05-20 11:27:36 -0700302 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700303 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700304 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700305
306 ALOGW("setDeviceConnectionState() invalid device: %x", device);
307 return BAD_VALUE;
308}
309
Eric Laurente0720872014-03-11 09:30:41 -0700310audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100311 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700312{
Eric Laurent634b7142016-04-20 13:48:02 -0700313 sp<DeviceDescriptor> devDesc =
314 mHwModules.getDeviceDescriptor(device, device_address, "",
315 (strlen(device_address) != 0)/*matchAddress*/);
316
317 if (devDesc == 0) {
318 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
319 device, device_address);
320 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
321 }
François Gaffie53615e22015-03-19 09:24:12 +0100322
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 DeviceVector *deviceVector;
324
Eric Laurente552edb2014-03-10 17:42:56 -0700325 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700327 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 deviceVector = &mAvailableInputDevices;
329 } else {
330 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
331 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700332 }
Eric Laurent634b7142016-04-20 13:48:02 -0700333
334 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
335 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800336}
337
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800338status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
339 const char *device_address,
340 const char *device_name)
341{
342 status_t status;
343
344 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
345 device, device_address, device_name);
346
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800347 // connect/disconnect only 1 device at a time
348 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
349
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800350 // Check if the device is currently connected
351 sp<DeviceDescriptor> devDesc =
352 mHwModules.getDeviceDescriptor(device, device_address, device_name);
353 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
354 if (index < 0) {
355 // Nothing to do: device is not connected
356 return NO_ERROR;
357 }
358
359 // Toggle the device state: UNAVAILABLE -> AVAILABLE
360 // This will force reading again the device configuration
361 status = setDeviceConnectionState(device,
362 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
363 device_address, device_name);
364 if (status != NO_ERROR) {
365 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
366 status);
367 return status;
368 }
369
370 status = setDeviceConnectionState(device,
371 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
372 device_address, device_name);
373 if (status != NO_ERROR) {
374 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
375 status);
376 return status;
377 }
378
379 return NO_ERROR;
380}
381
Eric Laurentdc462862016-07-19 12:29:53 -0700382uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700383{
384 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700385 status_t status;
386 audio_patch_handle_t afPatchHandle;
387 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700388 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700389
Andy Hunga76c7de2016-12-13 19:14:31 -0800390 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700391 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700392 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800393 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700394 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
395
396 // release existing RX patch if any
397 if (mCallRxPatch != 0) {
398 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
399 mCallRxPatch.clear();
400 }
401 // release TX patch if any
402 if (mCallTxPatch != 0) {
403 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
404 mCallTxPatch.clear();
405 }
406
407 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
408 // via setOutputDevice() on primary output.
409 // Otherwise, create two audio patches for TX and RX path.
410 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700411 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700412 // If the TX device is also on the primary HW module, setOutputDevice() will take care
413 // of it due to legacy implementation. If not, create a patch.
414 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
415 == AUDIO_DEVICE_NONE) {
416 createTxPatch = true;
417 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700418 } else { // create RX path audio patch
419 struct audio_patch patch;
420
421 patch.num_sources = 1;
422 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700423 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
424 ALOG_ASSERT(!deviceList.isEmpty(),
425 "updateCallRouting() selected device not in output device list");
426 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
427 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
428 ALOG_ASSERT(!deviceList.isEmpty(),
429 "updateCallRouting() no telephony RX device");
430 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
431
432 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
433 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
434
435 // request to reuse existing output stream if one is already opened to reach the RX device
436 SortedVector<audio_io_handle_t> outputs =
437 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700438 audio_io_handle_t output = selectOutput(outputs,
439 AUDIO_OUTPUT_FLAG_NONE,
440 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700442 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700443 ALOG_ASSERT(!outputDesc->isDuplicated(),
444 "updateCallRouting() RX device output is duplicated");
445 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700446 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700447 patch.num_sources = 2;
448 }
449
450 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700451 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700452 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
453 status);
454 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100455 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700456 mCallRxPatch->mAfPatchHandle = afPatchHandle;
457 mCallRxPatch->mUid = mUidCached;
458 }
459 createTxPatch = true;
460 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700461 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700462 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700463
Eric Laurentc2730ba2014-07-20 15:47:07 -0700464 patch.num_sources = 1;
465 patch.num_sinks = 1;
466 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
467 ALOG_ASSERT(!deviceList.isEmpty(),
468 "updateCallRouting() selected device not in input device list");
469 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
470 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
471 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
472 ALOG_ASSERT(!deviceList.isEmpty(),
473 "updateCallRouting() no telephony TX device");
474 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
475 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
476
477 SortedVector<audio_io_handle_t> outputs =
478 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700479 audio_io_handle_t output = selectOutput(outputs,
480 AUDIO_OUTPUT_FLAG_NONE,
481 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700482 // request to reuse existing output stream if one is already opened to reach the TX
483 // path output device
484 if (output != AUDIO_IO_HANDLE_NONE) {
485 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
486 ALOG_ASSERT(!outputDesc->isDuplicated(),
487 "updateCallRouting() RX device output is duplicated");
488 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700489 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700490 patch.num_sources = 2;
491 }
492
Eric Laurentc0a889f2015-10-14 14:36:34 -0700493 // terminate active capture if on the same HW module as the call TX source device
494 // FIXME: would be better to refine to only inputs whose profile connects to the
495 // call TX device but this information is not in the audio patch and logic here must be
496 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800497 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
498 for (size_t i = 0; i < activeInputs.size(); i++) {
499 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
500 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
501 AudioSessionCollection activeSessions =
502 activeDesc->getAudioSessions(true /*activeOnly*/);
503 for (size_t j = 0; j < activeSessions.size(); j++) {
504 audio_session_t activeSession = activeSessions.keyAt(j);
505 stopInput(activeDesc->mIoHandle, activeSession);
506 releaseInput(activeDesc->mIoHandle, activeSession);
507 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700508 }
509 }
510
Eric Laurentc2730ba2014-07-20 15:47:07 -0700511 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700512 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700513 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
514 status);
515 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100516 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700517 mCallTxPatch->mAfPatchHandle = afPatchHandle;
518 mCallTxPatch->mUid = mUidCached;
519 }
520 }
Eric Laurentdc462862016-07-19 12:29:53 -0700521
522 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700523}
524
Eric Laurente0720872014-03-11 09:30:41 -0700525void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700526{
527 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100528 // store previous phone state for management of sonification strategy below
529 int oldState = mEngine->getPhoneState();
530
531 if (mEngine->setPhoneState(state) != NO_ERROR) {
532 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700533 return;
534 }
François Gaffie2110e042015-03-24 08:41:51 +0100535 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700536 // if leaving call state, handle special case of active streams
537 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700538 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800540 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700541 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800543
Eric Laurent63dea1d2015-07-02 17:10:28 -0700544 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800545 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700546 }
547
François Gaffie2110e042015-03-24 08:41:51 +0100548 /**
549 * Switching to or from incall state or switching between telephony and VoIP lead to force
550 * routing command.
551 */
552 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
553 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700554
555 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700556 checkA2dpSuspend();
557 checkOutputForAllStrategies();
558 updateDevicesAndOutputs();
559
Eric Laurente552edb2014-03-10 17:42:56 -0700560 int delayMs = 0;
561 if (isStateInCall(state)) {
562 nsecs_t sysTime = systemTime();
563 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700564 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700565 // mute media and sonification strategies and delay device switch by the largest
566 // latency of any output where either strategy is active.
567 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100568 if ((isStrategyActive(desc, STRATEGY_MEDIA,
569 SONIFICATION_HEADSET_MUSIC_DELAY,
570 sysTime) ||
571 isStrategyActive(desc, STRATEGY_SONIFICATION,
572 SONIFICATION_HEADSET_MUSIC_DELAY,
573 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700574 (delayMs < (int)desc->latency()*2)) {
575 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700576 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700577 setStrategyMute(STRATEGY_MEDIA, true, desc);
578 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700579 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700580 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
581 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700582 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
583 }
584 }
585
Eric Laurent87ffa392015-05-22 10:32:38 -0700586 if (hasPrimaryOutput()) {
587 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
588 // the device returned is not necessarily reachable via this output
589 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
590 // force routing command to audio hardware when ending call
591 // even if no device change is needed
592 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
593 rxDevice = mPrimaryOutput->device();
594 }
Eric Laurente552edb2014-03-10 17:42:56 -0700595
Eric Laurent87ffa392015-05-22 10:32:38 -0700596 if (state == AUDIO_MODE_IN_CALL) {
597 updateCallRouting(rxDevice, delayMs);
598 } else if (oldState == AUDIO_MODE_IN_CALL) {
599 if (mCallRxPatch != 0) {
600 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
601 mCallRxPatch.clear();
602 }
603 if (mCallTxPatch != 0) {
604 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
605 mCallTxPatch.clear();
606 }
607 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
608 } else {
609 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700610 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700611 }
Eric Laurente552edb2014-03-10 17:42:56 -0700612 // if entering in call state, handle special case of active streams
613 // pertaining to sonification strategy see handleIncallSonification()
614 if (isStateInCall(state)) {
615 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800616 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700617 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700618 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700619
620 // force reevaluating accessibility routing when call starts
621 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700622 }
623
624 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700625 if (state == AUDIO_MODE_RINGTONE &&
626 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700627 mLimitRingtoneVolume = true;
628 } else {
629 mLimitRingtoneVolume = false;
630 }
631}
632
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700633audio_mode_t AudioPolicyManager::getPhoneState() {
634 return mEngine->getPhoneState();
635}
636
Eric Laurente0720872014-03-11 09:30:41 -0700637void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700638 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700639{
François Gaffie2110e042015-03-24 08:41:51 +0100640 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700641 if (config == mEngine->getForceUse(usage)) {
642 return;
643 }
Eric Laurente552edb2014-03-10 17:42:56 -0700644
François Gaffie2110e042015-03-24 08:41:51 +0100645 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
646 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
647 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700648 }
François Gaffie2110e042015-03-24 08:41:51 +0100649 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
650 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
651 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700652
653 // check for device and output changes triggered by new force usage
654 checkA2dpSuspend();
655 checkOutputForAllStrategies();
656 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800657
Eric Laurentdc462862016-07-19 12:29:53 -0700658 //FIXME: workaround for truncated touch sounds
659 // to be removed when the problem is handled by system UI
660 uint32_t delayMs = 0;
661 uint32_t waitMs = 0;
662 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
663 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
664 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700665 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700667 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 }
Eric Laurente552edb2014-03-10 17:42:56 -0700669 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700670 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
671 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
672 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700673 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
674 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675 }
Eric Laurente552edb2014-03-10 17:42:56 -0700676 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700677 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700678 }
679 }
680
Eric Laurentfb66dd92016-01-28 18:32:03 -0800681 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
682 for (size_t i = 0; i < activeInputs.size(); i++) {
683 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
684 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 if (activeDesc->mProfile->getSupportedDevices().types() &
687 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
688 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700689 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800690 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700691 }
Eric Laurente552edb2014-03-10 17:42:56 -0700692 }
Eric Laurente552edb2014-03-10 17:42:56 -0700693}
694
Eric Laurente0720872014-03-11 09:30:41 -0700695void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700696{
697 ALOGV("setSystemProperty() property %s, value %s", property, value);
698}
699
700// Find a direct output profile compatible with the parameters passed, even if the input flags do
701// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800702sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700703 audio_devices_t device,
704 uint32_t samplingRate,
705 audio_format_t format,
706 audio_channel_mask_t channelMask,
707 audio_output_flags_t flags)
708{
Eric Laurent861a6282015-05-18 15:40:16 -0700709 // only retain flags that will drive the direct output profile selection
710 // if explicitly requested
711 static const uint32_t kRelevantFlags =
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700712 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
713 AUDIO_OUTPUT_FLAG_VOIP_RX);
Eric Laurent861a6282015-05-18 15:40:16 -0700714 flags =
715 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
716
717 sp<IOProfile> profile;
718
Eric Laurente552edb2014-03-10 17:42:56 -0700719 for (size_t i = 0; i < mHwModules.size(); i++) {
720 if (mHwModules[i]->mHandle == 0) {
721 continue;
722 }
723 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700724 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
725 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700726 samplingRate, NULL /*updatedSamplingRate*/,
727 format, NULL /*updatedFormat*/,
728 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700729 flags)) {
730 continue;
731 }
732 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100733 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700734 continue;
735 }
736 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100737 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700738 continue;
739 }
740 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100741 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700742 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700743 }
Eric Laurente552edb2014-03-10 17:42:56 -0700744 }
745 }
Eric Laurent861a6282015-05-18 15:40:16 -0700746 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700747}
748
Eric Laurente0720872014-03-11 09:30:41 -0700749audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100750 uint32_t samplingRate,
751 audio_format_t format,
752 audio_channel_mask_t channelMask,
753 audio_output_flags_t flags,
754 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700755{
Eric Laurent3b73df72014-03-11 09:06:29 -0700756 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700757 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
758 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
759 device, stream, samplingRate, format, channelMask, flags);
760
Kevin Rocard169753c2017-03-06 14:18:23 -0800761 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, stream, samplingRate, format,
762 channelMask, flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700763}
764
Eric Laurente83b55d2014-11-14 10:06:21 -0800765status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
766 audio_io_handle_t *output,
767 audio_session_t session,
768 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700769 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800770 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800771 audio_output_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700772 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800773 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700774{
Eric Laurente83b55d2014-11-14 10:06:21 -0800775 audio_attributes_t attributes;
776 if (attr != NULL) {
777 if (!isValidAttributes(attr)) {
778 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
779 attr->usage, attr->content_type, attr->flags,
780 attr->tags);
781 return BAD_VALUE;
782 }
783 attributes = *attr;
784 } else {
785 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
786 ALOGE("getOutputForAttr(): invalid stream type");
787 return BAD_VALUE;
788 }
789 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700790 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800791
792 // TODO: check for existing client for this port ID
793 if (*portId == AUDIO_PORT_HANDLE_NONE) {
794 *portId = AudioPort::getNextUniqueId();
795 }
796
Eric Laurentc75307b2015-03-17 15:29:32 -0700797 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800798 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100799 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800800 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100801 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800802 }
François Gaffie036e1e92015-03-19 10:16:24 +0100803 *stream = streamTypefromAttributesInt(&attributes);
804 *output = desc->mIoHandle;
805 ALOGV("getOutputForAttr() returns output %d", *output);
806 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800807 }
808 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
809 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
810 return BAD_VALUE;
811 }
812
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700813 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
814 " session %d selectedDeviceId %d",
815 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
Eric Laurent2ac76942017-06-22 17:17:09 -0700816 session, *selectedDeviceId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700817
818 *stream = streamTypefromAttributesInt(&attributes);
819
820 // Explicit routing?
821 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -0700822 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
823 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
824 if (mAvailableOutputDevices[i]->getId() == *selectedDeviceId) {
825 deviceDesc = mAvailableOutputDevices[i];
826 break;
827 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700828 }
829 }
830 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700831
Eric Laurente83b55d2014-11-14 10:06:21 -0800832 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700833 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700834
Eric Laurente83b55d2014-11-14 10:06:21 -0800835 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700836 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
837 }
838
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700839 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800840 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700841
Kevin Rocard169753c2017-03-06 14:18:23 -0800842 *output = getOutputForDevice(device, session, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800843 config->sample_rate, config->format, config->channel_mask,
844 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800845 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700846 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800847 return INVALID_OPERATION;
848 }
Paul McLeanaa981192015-03-21 09:55:15 -0700849
Eric Laurent2ac76942017-06-22 17:17:09 -0700850 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
851 *selectedDeviceId = outputDevices.size() > 0 ? outputDevices.itemAt(0)->getId()
852 : AUDIO_PORT_HANDLE_NONE;
853
854 ALOGV(" getOutputForAttr() returns output %d selectedDeviceId %d", *output, *selectedDeviceId);
855
Eric Laurente83b55d2014-11-14 10:06:21 -0800856 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700857}
858
859audio_io_handle_t AudioPolicyManager::getOutputForDevice(
860 audio_devices_t device,
Kevin Rocard169753c2017-03-06 14:18:23 -0800861 audio_session_t session,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700862 audio_stream_type_t stream,
863 uint32_t samplingRate,
864 audio_format_t format,
865 audio_channel_mask_t channelMask,
866 audio_output_flags_t flags,
867 const audio_offload_info_t *offloadInfo)
868{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700869 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700870 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700871
Eric Laurente552edb2014-03-10 17:42:56 -0700872#ifdef AUDIO_POLICY_TEST
873 if (mCurOutput != 0) {
874 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
875 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
876
877 if (mTestOutputs[mCurOutput] == 0) {
878 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700879 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
880 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700881 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700882 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700883 outputDesc->mFlags =
884 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700885 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700886 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
887 config.sample_rate = mTestSamplingRate;
888 config.channel_mask = mTestChannels;
889 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700890 if (offloadInfo != NULL) {
891 config.offload_info = *offloadInfo;
892 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700893 status = mpClientInterface->openOutput(0,
894 &mTestOutputs[mCurOutput],
895 &config,
896 &outputDesc->mDevice,
897 String8(""),
898 &outputDesc->mLatency,
899 outputDesc->mFlags);
900 if (status == NO_ERROR) {
901 outputDesc->mSamplingRate = config.sample_rate;
902 outputDesc->mFormat = config.format;
903 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700904 AudioParameter outputCmd = AudioParameter();
905 outputCmd.addInt(String8("set_id"),mCurOutput);
906 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
907 addOutput(mTestOutputs[mCurOutput], outputDesc);
908 }
909 }
910 return mTestOutputs[mCurOutput];
911 }
912#endif //AUDIO_POLICY_TEST
913
914 // open a direct output if required by specified parameters
915 //force direct flag if offload flag is set: offloading implies a direct output stream
916 // and all common behaviors are driven by checking only the direct flag
917 // this should normally be set appropriately in the policy configuration file
918 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700919 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700921 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
922 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
923 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800924 // only allow deep buffering for music stream type
925 if (stream != AUDIO_STREAM_MUSIC) {
926 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700927 } else if (/* stream == AUDIO_STREAM_MUSIC && */
928 flags == AUDIO_OUTPUT_FLAG_NONE &&
929 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
930 // use DEEP_BUFFER as default output for music stream type
931 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800932 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700933 if (stream == AUDIO_STREAM_TTS) {
934 flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700935 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Haynes Mathew George84c621e2017-04-25 11:41:50 -0700936 audio_is_linear_pcm(format)) {
937 flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
938 AUDIO_OUTPUT_FLAG_DIRECT);
939 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700940 }
Eric Laurente552edb2014-03-10 17:42:56 -0700941
Eric Laurentb732cf52014-09-24 19:08:21 -0700942 sp<IOProfile> profile;
943
944 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700945 // and not explicitly requested
946 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800947 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700948 audio_channel_count_from_out_mask(channelMask) <= 2) {
949 goto non_direct_output;
950 }
951
Andy Hung2ddee192015-12-18 17:34:44 -0800952 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
953 // This prevents creating an offloaded track and tearing it down immediately after start
954 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700955 // FIXME: We should check the audio session here but we do not have it in this context.
956 // This may prevent offloading in rare situations where effects are left active by apps
957 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700958
Eric Laurente552edb2014-03-10 17:42:56 -0700959 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800960 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700961 profile = getProfileForDirectOutput(device,
962 samplingRate,
963 format,
964 channelMask,
965 (audio_output_flags_t)flags);
966 }
967
Eric Laurent1c333e22014-05-20 10:48:17 -0700968 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700969 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700970
971 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700972 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700973 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
974 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800975 // reuse direct output if currently open by the same client
976 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700977 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800978 audio_formats_match(format, outputDesc->mFormat) &&
979 (channelMask == outputDesc->mChannelMask)) {
Kevin Rocard169753c2017-03-06 14:18:23 -0800980 if (session == outputDesc->mDirectClientSession) {
Kevin Rocard551061a2017-02-06 15:59:29 -0800981 outputDesc->mDirectOpenCount++;
Kevin Rocard169753c2017-03-06 14:18:23 -0800982 ALOGV("getOutput() reusing direct output %d for session %d",
983 mOutputs.keyAt(i), session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800984 return mOutputs.keyAt(i);
985 } else {
Kevin Rocard169753c2017-03-06 14:18:23 -0800986 ALOGV("getOutput() do not reuse direct output because current client (%d) "
987 "is not the same as requesting client (%d)",
988 outputDesc->mDirectClientSession, session);
Kevin Rocard551061a2017-02-06 15:59:29 -0800989 goto non_direct_output;
990 }
Eric Laurente552edb2014-03-10 17:42:56 -0700991 }
992 }
993 }
994 // close direct output if currently open and configured with different parameters
995 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700996 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700997 }
Eric Laurent861a6282015-05-18 15:40:16 -0700998
999 // if the selected profile is offloaded and no offload info was specified,
1000 // create a default one
1001 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001002 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -07001003 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1004 defaultOffloadInfo.sample_rate = samplingRate;
1005 defaultOffloadInfo.channel_mask = channelMask;
1006 defaultOffloadInfo.format = format;
1007 defaultOffloadInfo.stream_type = stream;
1008 defaultOffloadInfo.bit_rate = 0;
1009 defaultOffloadInfo.duration_us = -1;
1010 defaultOffloadInfo.has_video = true; // conservative
1011 defaultOffloadInfo.is_streaming = true; // likely
1012 offloadInfo = &defaultOffloadInfo;
1013 }
1014
Eric Laurentc75307b2015-03-17 15:29:32 -07001015 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07001016 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001017 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -07001018 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001019 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1020 config.sample_rate = samplingRate;
1021 config.channel_mask = channelMask;
1022 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001023 if (offloadInfo != NULL) {
1024 config.offload_info = *offloadInfo;
1025 }
Eric Laurente3014102017-05-03 11:15:43 -07001026 DeviceVector outputDevices = mAvailableOutputDevices.getDevicesFromType(device);
1027 String8 address = outputDevices.size() > 0 ? outputDevices.itemAt(0)->mAddress
1028 : String8("");
Eric Laurent322b4d22015-04-03 15:57:54 -07001029 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001030 &output,
1031 &config,
1032 &outputDesc->mDevice,
Eric Laurente3014102017-05-03 11:15:43 -07001033 address,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001034 &outputDesc->mLatency,
1035 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001036
1037 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001038 if (status != NO_ERROR ||
1039 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001040 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001041 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001042 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1043 "format %d %d, channelMask %04x %04x", output, samplingRate,
1044 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1045 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001046 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001047 mpClientInterface->closeOutput(output);
1048 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001049 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001050 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001051 goto non_direct_output;
1052 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001053 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001054 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001055 outputDesc->mSamplingRate = config.sample_rate;
1056 outputDesc->mChannelMask = config.channel_mask;
1057 outputDesc->mFormat = config.format;
1058 outputDesc->mRefCount[stream] = 0;
1059 outputDesc->mStopTime[stream] = 0;
1060 outputDesc->mDirectOpenCount = 1;
Kevin Rocard169753c2017-03-06 14:18:23 -08001061 outputDesc->mDirectClientSession = session;
1062
Eric Laurente552edb2014-03-10 17:42:56 -07001063 addOutput(output, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001064 mPreviousOutputs = mOutputs;
1065 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001066 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001067 return output;
1068 }
1069
Eric Laurentb732cf52014-09-24 19:08:21 -07001070non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001071
1072 // A request for HW A/V sync cannot fallback to a mixed output because time
1073 // stamps are embedded in audio data
1074 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1075 return AUDIO_IO_HANDLE_NONE;
1076 }
1077
Eric Laurente552edb2014-03-10 17:42:56 -07001078 // ignoring channel mask due to downmix capability in mixer
1079
1080 // open a non direct output
1081
1082 // for non direct outputs, only PCM is supported
1083 if (audio_is_linear_pcm(format)) {
1084 // get which output is suitable for the specified stream. The actual
1085 // routing change will happen when startOutput() will be called
1086 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1087
Eric Laurent8838a382014-09-08 16:44:28 -07001088 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1089 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1090 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001091 }
1092 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1093 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1094
Eric Laurente552edb2014-03-10 17:42:56 -07001095 return output;
1096}
1097
Eric Laurente0720872014-03-11 09:30:41 -07001098audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001099 audio_output_flags_t flags,
1100 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001101{
1102 // select one output among several that provide a path to a particular device or set of
1103 // devices (the list was previously build by getOutputsForDevice()).
1104 // The priority is as follows:
1105 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001106 // 2: the output with the bit depth the closest to the requested one
1107 // 3: the primary output
1108 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001109
1110 if (outputs.size() == 0) {
1111 return 0;
1112 }
1113 if (outputs.size() == 1) {
1114 return outputs[0];
1115 }
1116
1117 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001118 audio_io_handle_t outputForFlags = 0;
1119 audio_io_handle_t outputForPrimary = 0;
1120 audio_io_handle_t outputForFormat = 0;
1121 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1122 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001123
1124 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001125 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001126 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001127 // if a valid format is specified, skip output if not compatible
1128 if (format != AUDIO_FORMAT_INVALID) {
1129 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001130 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001131 continue;
1132 }
1133 } else if (!audio_is_linear_pcm(format)) {
1134 continue;
1135 }
Eric Laurente6930022016-02-11 10:20:40 -08001136 if (AudioPort::isBetterFormatMatch(
1137 outputDesc->mFormat, bestFormat, format)) {
1138 outputForFormat = outputs[i];
1139 bestFormat = outputDesc->mFormat;
1140 }
Eric Laurent8838a382014-09-08 16:44:28 -07001141 }
1142
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001143 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001144 if (commonFlags >= maxCommonFlags) {
1145 if (commonFlags == maxCommonFlags) {
1146 if (AudioPort::isBetterFormatMatch(
1147 outputDesc->mFormat, bestFormatForFlags, format)) {
1148 outputForFlags = outputs[i];
1149 bestFormatForFlags = outputDesc->mFormat;
1150 }
1151 } else {
1152 outputForFlags = outputs[i];
1153 maxCommonFlags = commonFlags;
1154 bestFormatForFlags = outputDesc->mFormat;
1155 }
Eric Laurente552edb2014-03-10 17:42:56 -07001156 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1157 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001158 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001159 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001160 }
1161 }
1162 }
1163
Eric Laurente6930022016-02-11 10:20:40 -08001164 if (outputForFlags != 0) {
1165 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001166 }
Eric Laurente6930022016-02-11 10:20:40 -08001167 if (outputForFormat != 0) {
1168 return outputForFormat;
1169 }
1170 if (outputForPrimary != 0) {
1171 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
1173
1174 return outputs[0];
1175}
1176
Eric Laurente0720872014-03-11 09:30:41 -07001177status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001178 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001179 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001180{
Paul McLeanaa981192015-03-21 09:55:15 -07001181 ALOGV("startOutput() output %d, stream %d, session %d",
1182 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001183 ssize_t index = mOutputs.indexOfKey(output);
1184 if (index < 0) {
1185 ALOGW("startOutput() unknown output %d", output);
1186 return BAD_VALUE;
1187 }
1188
Eric Laurentc75307b2015-03-17 15:29:32 -07001189 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1190
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001191 // Routing?
1192 mOutputRoutes.incRouteActivity(session);
1193
Eric Laurentc75307b2015-03-17 15:29:32 -07001194 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001195 AudioMix *policyMix = NULL;
1196 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001197 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001198 policyMix = outputDesc->mPolicyMix;
1199 address = policyMix->mDeviceAddress.string();
1200 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1201 newDevice = policyMix->mDeviceType;
1202 } else {
1203 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1204 }
Eric Laurent493404d2015-04-21 15:07:36 -07001205 } else if (mOutputRoutes.hasRouteChanged(session)) {
1206 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001207 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001208 } else {
1209 newDevice = AUDIO_DEVICE_NONE;
1210 }
1211
1212 uint32_t delayMs = 0;
1213
Eric Laurentc40d9692016-04-13 19:14:13 -07001214 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001215
1216 if (status != NO_ERROR) {
1217 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001218 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001219 }
1220 // Automatically enable the remote submix input when output is started on a re routing mix
1221 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001222 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1223 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001224 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1225 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001226 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001227 "remote-submix");
1228 }
1229
1230 if (delayMs != 0) {
1231 usleep(delayMs * 1000);
1232 }
1233
1234 return status;
1235}
1236
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001237status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001238 audio_stream_type_t stream,
1239 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001240 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001241 uint32_t *delayMs)
1242{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001243 // cannot start playback of STREAM_TTS if any other output is being used
1244 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001245
1246 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001247 if (stream == AUDIO_STREAM_TTS) {
1248 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001249 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001250 return INVALID_OPERATION;
1251 } else {
1252 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1253 }
1254 } else {
1255 // some playback other than beacon starts
1256 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1257 }
1258
Eric Laurent77305a62016-07-25 16:39:22 -07001259 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001260 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001261 bool force = !outputDesc->isActive() &&
1262 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001263
Eric Laurente552edb2014-03-10 17:42:56 -07001264 // increment usage count for this stream on the requested output:
1265 // NOTE that the usage count is the same for duplicated output and hardware output which is
1266 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1267 outputDesc->changeRefCount(stream, 1);
1268
Eric Laurent36829f92017-04-07 19:04:42 -07001269 if (stream == AUDIO_STREAM_MUSIC) {
1270 selectOutputForMusicEffects();
1271 }
1272
Eric Laurent493404d2015-04-21 15:07:36 -07001273 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001274 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001275 if (device == AUDIO_DEVICE_NONE) {
1276 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001277 }
Eric Laurent36829f92017-04-07 19:04:42 -07001278
Eric Laurente552edb2014-03-10 17:42:56 -07001279 routing_strategy strategy = getStrategy(stream);
1280 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001281 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1282 (beaconMuteLatency > 0);
1283 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001284 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001285 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001286 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001287 // force a device change if any other output is:
1288 // - managed by the same hw module
1289 // - has a current device selection that differs from selected device.
1290 // - supports currently selected device
1291 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001292 // In this case, the audio HAL must receive the new device selection so that it can
1293 // change the device currently selected by the other active output.
1294 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001295 desc->device() != device &&
1296 desc->supportedDevices() & device &&
1297 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001298 force = true;
1299 }
1300 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001301 // a notification so that audio focus effect can propagate, or that a mute/unmute
1302 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001303 uint32_t latency = desc->latency();
1304 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1305 waitMs = latency;
1306 }
1307 }
1308 }
Eric Laurentdc462862016-07-19 12:29:53 -07001309 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001310
1311 // handle special case for sonification while in call
1312 if (isInCall()) {
1313 handleIncallSonification(stream, true, false);
1314 }
1315
1316 // apply volume rules for current stream and device if necessary
1317 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001318 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001319 outputDesc,
1320 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001321
1322 // update the outputs if starting an output with a stream that can affect notification
1323 // routing
1324 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001325
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001326 // force reevaluating accessibility routing when ringtone or alarm starts
1327 if (strategy == STRATEGY_SONIFICATION) {
1328 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1329 }
Eric Laurentdc462862016-07-19 12:29:53 -07001330
1331 if (waitMs > muteWaitMs) {
1332 *delayMs = waitMs - muteWaitMs;
1333 }
Eric Laurente552edb2014-03-10 17:42:56 -07001334 }
Eric Laurentdc462862016-07-19 12:29:53 -07001335
Eric Laurente552edb2014-03-10 17:42:56 -07001336 return NO_ERROR;
1337}
1338
1339
Eric Laurente0720872014-03-11 09:30:41 -07001340status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001341 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001342 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001343{
1344 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1345 ssize_t index = mOutputs.indexOfKey(output);
1346 if (index < 0) {
1347 ALOGW("stopOutput() unknown output %d", output);
1348 return BAD_VALUE;
1349 }
1350
Eric Laurentc75307b2015-03-17 15:29:32 -07001351 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001352
Eric Laurentc75307b2015-03-17 15:29:32 -07001353 if (outputDesc->mRefCount[stream] == 1) {
1354 // Automatically disable the remote submix input when output is stopped on a
1355 // re routing mix of type MIX_TYPE_RECORDERS
1356 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1357 outputDesc->mPolicyMix != NULL &&
1358 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1359 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1360 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001361 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001362 "remote-submix");
1363 }
1364 }
1365
1366 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001367 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001368 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001369 int activityCount = mOutputRoutes.decRouteActivity(session);
1370 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1371
1372 if (forceDeviceUpdate) {
1373 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1374 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001375 }
1376
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001377 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001378}
1379
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001380status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001381 audio_stream_type_t stream,
1382 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001383{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001384 // always handle stream stop, check which stream type is stopping
1385 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1386
Eric Laurente552edb2014-03-10 17:42:56 -07001387 // handle special case for sonification while in call
1388 if (isInCall()) {
1389 handleIncallSonification(stream, false, false);
1390 }
1391
1392 if (outputDesc->mRefCount[stream] > 0) {
1393 // decrement usage count of this stream on the output
1394 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001395
Eric Laurente552edb2014-03-10 17:42:56 -07001396 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001397 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001398 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001399 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001400 // delay the device switch by twice the latency because stopOutput() is executed when
1401 // the track stop() command is received and at that time the audio track buffer can
1402 // still contain data that needs to be drained. The latency only covers the audio HAL
1403 // and kernel buffers. Also the latency does not always include additional delay in the
1404 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001405 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001406
1407 // force restoring the device selection on other active outputs if it differs from the
1408 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001409 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001410 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001411 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001412 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001413 desc->isActive() &&
1414 outputDesc->sharesHwModuleWith(desc) &&
1415 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001416 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1417 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001418 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001419 newDevice2,
1420 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001421 delayMs);
1422 // re-apply device specific volume if not done by setOutputDevice()
1423 if (!force) {
1424 applyStreamVolumes(desc, newDevice2, delayMs);
1425 }
Eric Laurente552edb2014-03-10 17:42:56 -07001426 }
1427 }
1428 // update the outputs if stopping one with a stream that can affect notification routing
1429 handleNotificationRoutingForStream(stream);
1430 }
Eric Laurent36829f92017-04-07 19:04:42 -07001431 if (stream == AUDIO_STREAM_MUSIC) {
1432 selectOutputForMusicEffects();
1433 }
Eric Laurente552edb2014-03-10 17:42:56 -07001434 return NO_ERROR;
1435 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001436 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001437 return INVALID_OPERATION;
1438 }
1439}
1440
Eric Laurente83b55d2014-11-14 10:06:21 -08001441void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001442 audio_stream_type_t stream __unused,
1443 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001444{
1445 ALOGV("releaseOutput() %d", output);
1446 ssize_t index = mOutputs.indexOfKey(output);
1447 if (index < 0) {
1448 ALOGW("releaseOutput() releasing unknown output %d", output);
1449 return;
1450 }
1451
1452#ifdef AUDIO_POLICY_TEST
1453 int testIndex = testOutputIndex(output);
1454 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001455 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001456 if (outputDesc->isActive()) {
1457 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001458 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001459 mTestOutputs[testIndex] = 0;
1460 }
1461 return;
1462 }
1463#endif //AUDIO_POLICY_TEST
1464
Paul McLeanaa981192015-03-21 09:55:15 -07001465 // Routing
1466 mOutputRoutes.removeRoute(session);
1467
Eric Laurentc75307b2015-03-17 15:29:32 -07001468 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001469 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001470 if (desc->mDirectOpenCount <= 0) {
1471 ALOGW("releaseOutput() invalid open count %d for output %d",
1472 desc->mDirectOpenCount, output);
1473 return;
1474 }
1475 if (--desc->mDirectOpenCount == 0) {
1476 closeOutput(output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001477 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
1479 }
1480}
1481
1482
Eric Laurentcaf7f482014-11-25 17:50:47 -08001483status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1484 audio_io_handle_t *input,
1485 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001486 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001487 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001488 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07001489 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001490 input_type_t *inputType,
1491 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001492{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001493 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1494 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001495 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001496
Eric Laurentcb4dae22017-07-01 19:39:32 -07001497 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1498 // possible
1499 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1500 *input != AUDIO_IO_HANDLE_NONE) {
1501 ssize_t index = mInputs.indexOfKey(*input);
1502 if (index < 0) {
1503 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1504 return BAD_VALUE;
1505 }
1506 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1507 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1508 if (audioSession == 0) {
1509 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1510 return BAD_VALUE;
1511 }
1512 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1513 // The second call is for the first active client and sets the UID. Any further call
1514 // corresponds to a new client and is only permitted from the same UId.
1515 if (audioSession->openCount() == 1) {
1516 audioSession->setUid(uid);
1517 } else if (audioSession->uid() != uid) {
1518 ALOGW("getInputForAttr() bad uid %d for session %d uid %d",
1519 uid, session, audioSession->uid());
1520 return INVALID_OPERATION;
1521 }
1522 audioSession->changeOpenCount(1);
1523 *inputType = API_INPUT_LEGACY;
1524 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1525 *portId = AudioPort::getNextUniqueId();
1526 }
1527 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(inputDesc->mDevice);
1528 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1529 : AUDIO_PORT_HANDLE_NONE;
1530 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1531 return NO_ERROR;
1532 }
1533
Eric Laurentcaf7f482014-11-25 17:50:47 -08001534 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001535 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001536
Eric Laurent275e8e92014-11-30 15:14:47 -08001537 audio_devices_t device;
1538 // handle legacy remote submix case where the address was not always specified
1539 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001540 audio_source_t inputSource = attr->source;
1541 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001542 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001543
Eric Laurentc447ded2015-01-06 08:47:05 -08001544 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1545 inputSource = AUDIO_SOURCE_MIC;
1546 }
1547 halInputSource = inputSource;
1548
Eric Laurent20b9ef02016-12-05 11:03:16 -08001549 // TODO: check for existing client for this port ID
1550 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1551 *portId = AudioPort::getNextUniqueId();
1552 }
1553
Paul McLean466dc8e2015-04-17 13:15:36 -06001554 // Explicit routing?
1555 sp<DeviceDescriptor> deviceDesc;
Eric Laurent2ac76942017-06-22 17:17:09 -07001556 if (*selectedDeviceId != AUDIO_PORT_HANDLE_NONE) {
1557 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1558 if (mAvailableInputDevices[i]->getId() == *selectedDeviceId) {
1559 deviceDesc = mAvailableInputDevices[i];
1560 break;
1561 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001562 }
1563 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001564 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001565
Eric Laurentc447ded2015-01-06 08:47:05 -08001566 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001567 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001568 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001569 if (ret != NO_ERROR) {
1570 return ret;
1571 }
1572 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001573 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1574 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001575 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001576 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001577 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001578 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001579 return BAD_VALUE;
1580 }
Eric Laurentc722f302014-12-10 11:21:49 -08001581 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001582 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001583 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1584 // there is an external policy, but this input is attached to a mix of recorders,
1585 // meaning it receives audio injected into the framework, so the recorder doesn't
1586 // know about it and is therefore considered "legacy"
1587 *inputType = API_INPUT_LEGACY;
1588 } else {
1589 // recording a mix of players defined by an external policy, we're rerouting for
1590 // an external policy
1591 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1592 }
Eric Laurentc722f302014-12-10 11:21:49 -08001593 } else if (audio_is_remote_submix_device(device)) {
1594 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001595 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001596 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1597 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001598 } else {
1599 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001600 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001601
Eric Laurent599c7582015-12-07 18:05:55 -08001602 }
1603
1604 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001605 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001606 policyMix);
1607 if (*input == AUDIO_IO_HANDLE_NONE) {
1608 mInputRoutes.removeRoute(session);
1609 return INVALID_OPERATION;
1610 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001611
Eric Laurent2ac76942017-06-22 17:17:09 -07001612 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1613 *selectedDeviceId = inputDevices.size() > 0 ? inputDevices.itemAt(0)->getId()
1614 : AUDIO_PORT_HANDLE_NONE;
1615
1616 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d",
1617 *input, *inputType, *selectedDeviceId);
1618
Eric Laurent599c7582015-12-07 18:05:55 -08001619 return NO_ERROR;
1620}
1621
1622
1623audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1624 String8 address,
1625 audio_session_t session,
1626 uid_t uid,
1627 audio_source_t inputSource,
1628 uint32_t samplingRate,
1629 audio_format_t format,
1630 audio_channel_mask_t channelMask,
1631 audio_input_flags_t flags,
1632 AudioMix *policyMix)
1633{
1634 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1635 audio_source_t halInputSource = inputSource;
1636 bool isSoundTrigger = false;
1637
1638 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1639 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1640 if (index >= 0) {
1641 input = mSoundTriggerSessions.valueFor(session);
1642 isSoundTrigger = true;
1643 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1644 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1645 } else {
1646 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001647 }
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001648 } else if (inputSource == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07001649 audio_is_linear_pcm(format)) {
1650 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001651 }
1652
Andy Hungf129b032015-04-07 13:45:50 -07001653 // find a compatible input profile (not necessarily identical in parameters)
1654 sp<IOProfile> profile;
1655 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001656 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001657 audio_format_t profileFormat = format;
1658 audio_channel_mask_t profileChannelMask = channelMask;
1659 audio_input_flags_t profileFlags = flags;
1660 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001661 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001662 profileSamplingRate, profileFormat, profileChannelMask,
1663 profileFlags);
1664 if (profile != 0) {
1665 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001666 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1667 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001668 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1669 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1670 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001671 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1672 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001673 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001674 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001675 }
Eric Laurente552edb2014-03-10 17:42:56 -07001676 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001677 // Pick input sampling rate if not specified by client
1678 if (samplingRate == 0) {
1679 samplingRate = profileSamplingRate;
1680 }
Eric Laurente552edb2014-03-10 17:42:56 -07001681
Eric Laurent322b4d22015-04-03 15:57:54 -07001682 if (profile->getModuleHandle() == 0) {
1683 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001684 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001685 }
1686
Eric Laurent599c7582015-12-07 18:05:55 -08001687 sp<AudioSession> audioSession = new AudioSession(session,
1688 inputSource,
1689 format,
1690 samplingRate,
1691 channelMask,
1692 flags,
1693 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001694 isSoundTrigger,
1695 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001696
Eric Laurent74708e72017-04-07 17:13:42 -07001697// FIXME: disable concurrent capture until UI is ready
1698#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001699 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001700 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001701 for (size_t i = 0; i < mInputs.size(); i++) {
1702 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001703 // reuse input if:
1704 // - it shares the same profile
1705 // AND
1706 // - it is not a reroute submix input
1707 // AND
1708 // - it is: not used for sound trigger
1709 // OR
1710 // used for sound trigger and all clients use the same session ID
1711 //
1712 if ((profile == desc->mProfile) &&
1713 (isSoundTrigger == desc->isSoundTrigger()) &&
1714 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001715
1716 sp<AudioSession> as = desc->getAudioSession(session);
1717 if (as != 0) {
1718 // do not allow unmatching properties on same session
1719 if (as->matches(audioSession)) {
1720 as->changeOpenCount(1);
1721 } else {
1722 ALOGW("getInputForDevice() record with different attributes"
1723 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001724 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001725 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001726 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001727 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001728 }
Eric Laurentbb948092017-01-23 18:33:30 -08001729
Eric Laurent555530a2017-02-07 18:17:24 -08001730 // Reuse the already opened input stream on this profile if:
1731 // - the new capture source is background OR
1732 // - the path requested configurations match OR
1733 // - the new source priority is less than the highest source priority on this input
1734 // If the input stream cannot be reused, close it before opening a new stream
1735 // on the same profile for the new client so that the requested path configuration
1736 // can be selected.
1737 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001738 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001739 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001740 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001741 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001742 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001743 reusedInputDesc = desc;
1744 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001745 } else {
1746 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001747 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1748 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001749 }
Eric Laurent599c7582015-12-07 18:05:55 -08001750 }
1751 }
Eric Laurent599c7582015-12-07 18:05:55 -08001752
Eric Laurent555530a2017-02-07 18:17:24 -08001753 if (reusedInputDesc != 0) {
1754 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1755 for (size_t j = 0; j < sessions.size(); j++) {
1756 audio_session_t currentSession = sessions.keyAt(j);
1757 stopInput(reusedInputDesc->mIoHandle, currentSession);
1758 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1759 }
1760 }
Eric Laurent74708e72017-04-07 17:13:42 -07001761#endif
Eric Laurent555530a2017-02-07 18:17:24 -08001762
Eric Laurentcf2c0212014-07-25 16:20:43 -07001763 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001764 config.sample_rate = profileSamplingRate;
1765 config.channel_mask = profileChannelMask;
1766 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001767
Eric Laurente3014102017-05-03 11:15:43 -07001768 if (address == "") {
1769 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(device);
1770 // the inputs vector must be of size 1, but we don't want to crash here
1771 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress : String8("");
1772 }
1773
Eric Laurent322b4d22015-04-03 15:57:54 -07001774 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001775 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001776 &config,
1777 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001778 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001779 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001780 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001781
1782 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001783 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001784 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001785 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001786 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001787 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1788 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001789 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001790 if (input != AUDIO_IO_HANDLE_NONE) {
1791 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001792 }
Eric Laurent599c7582015-12-07 18:05:55 -08001793 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001794 }
1795
Eric Laurent1f2f2232014-06-02 12:01:23 -07001796 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001797 inputDesc->mSamplingRate = profileSamplingRate;
1798 inputDesc->mFormat = profileFormat;
1799 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001800 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001801 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001802 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001803
Eric Laurent599c7582015-12-07 18:05:55 -08001804 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001805 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001806
Eric Laurent599c7582015-12-07 18:05:55 -08001807 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001808}
1809
Eric Laurentbb948092017-01-23 18:33:30 -08001810//static
1811bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1812{
1813 return (source == AUDIO_SOURCE_HOTWORD) ||
1814 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1815 (source == AUDIO_SOURCE_FM_TUNER);
1816}
1817
Eric Laurentfb66dd92016-01-28 18:32:03 -08001818bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1819 const sp<AudioSession>& audioSession)
1820{
1821 // Do not allow capture if an active voice call is using a software patch and
1822 // the call TX source device is on the same HW module.
1823 // FIXME: would be better to refine to only inputs whose profile connects to the
1824 // call TX device but this information is not in the audio patch
1825 if (mCallTxPatch != 0 &&
1826 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1827 return false;
1828 }
1829
1830 // starting concurrent capture is enabled if:
1831 // 1) capturing for re-routing
1832 // 2) capturing for HOTWORD source
1833 // 3) capturing for FM TUNER source
1834 // 3) All other active captures are either for re-routing or HOTWORD
1835
1836 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001837 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001838 return true;
1839 }
1840
1841 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1842 for (size_t i = 0; i < activeInputs.size(); i++) {
1843 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001844 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001845 !is_virtual_input_device(activeInput->mDevice)) {
1846 return false;
1847 }
1848 }
1849
1850 return true;
1851}
1852
Chris Thornton2b864642017-06-27 21:26:07 -07001853// FIXME: remove when concurrent capture is ready. This is a hack to work around bug b/63083537.
1854bool AudioPolicyManager::soundTriggerSupportsConcurrentCapture() {
1855 if (!mHasComputedSoundTriggerSupportsConcurrentCapture) {
1856 bool soundTriggerSupportsConcurrentCapture = false;
1857 unsigned int numModules = 0;
1858 struct sound_trigger_module_descriptor* nModules = NULL;
1859
1860 status_t status = SoundTrigger::listModules(nModules, &numModules);
1861 if (status == NO_ERROR && numModules != 0) {
1862 nModules = (struct sound_trigger_module_descriptor*) calloc(
1863 numModules, sizeof(struct sound_trigger_module_descriptor));
1864 if (nModules == NULL) {
1865 // We failed to malloc the buffer, so just say no for now, and hope that we have more
1866 // ram the next time this function is called.
1867 ALOGE("Failed to allocate buffer for module descriptors");
1868 return false;
1869 }
1870
1871 status = SoundTrigger::listModules(nModules, &numModules);
1872 if (status == NO_ERROR) {
1873 soundTriggerSupportsConcurrentCapture = true;
1874 for (size_t i = 0; i < numModules; ++i) {
1875 soundTriggerSupportsConcurrentCapture &=
1876 nModules[i].properties.concurrent_capture;
1877 }
1878 }
1879 free(nModules);
1880 }
1881 mSoundTriggerSupportsConcurrentCapture = soundTriggerSupportsConcurrentCapture;
1882 mHasComputedSoundTriggerSupportsConcurrentCapture = true;
1883 }
1884 return mSoundTriggerSupportsConcurrentCapture;
1885}
1886
Eric Laurentfb66dd92016-01-28 18:32:03 -08001887
Eric Laurent4dc68062014-07-28 17:26:49 -07001888status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001889 audio_session_t session,
1890 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001891{
1892 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001893 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001894 ssize_t index = mInputs.indexOfKey(input);
1895 if (index < 0) {
1896 ALOGW("startInput() unknown input %d", input);
1897 return BAD_VALUE;
1898 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001899 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001900
Eric Laurent599c7582015-12-07 18:05:55 -08001901 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1902 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001903 ALOGW("startInput() unknown session %d on input %d", session, input);
1904 return BAD_VALUE;
1905 }
1906
Eric Laurent74708e72017-04-07 17:13:42 -07001907// FIXME: disable concurrent capture until UI is ready
1908#if 0
Eric Laurentfb66dd92016-01-28 18:32:03 -08001909 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1910 ALOGW("startInput(%d) failed: other input already started", input);
1911 return INVALID_OPERATION;
1912 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001913
Eric Laurentfb66dd92016-01-28 18:32:03 -08001914 if (isInCall()) {
1915 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1916 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001917 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001918 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001919 }
Eric Laurent74708e72017-04-07 17:13:42 -07001920#else
1921 if (!is_virtual_input_device(inputDesc->mDevice)) {
1922 if (mCallTxPatch != 0 &&
1923 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1924 ALOGW("startInput(%d) failed: call in progress", input);
1925 return INVALID_OPERATION;
1926 }
1927
1928 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1929 for (size_t i = 0; i < activeInputs.size(); i++) {
1930 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1931
1932 if (is_virtual_input_device(activeDesc->mDevice)) {
1933 continue;
1934 }
1935
Eric Laurentcb4dae22017-07-01 19:39:32 -07001936 if ((audioSession->flags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0 &&
1937 activeDesc->getId() == inputDesc->getId()) {
1938 continue;
1939 }
1940
Eric Laurent74708e72017-04-07 17:13:42 -07001941 audio_source_t activeSource = activeDesc->inputSource(true);
1942 if (audioSession->inputSource() == AUDIO_SOURCE_HOTWORD) {
1943 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1944 if (activeDesc->hasPreemptedSession(session)) {
1945 ALOGW("startInput(%d) failed for HOTWORD: "
1946 "other input %d already started for HOTWORD",
1947 input, activeDesc->mIoHandle);
1948 return INVALID_OPERATION;
1949 }
1950 } else {
1951 ALOGV("startInput(%d) failed for HOTWORD: other input %d already started",
1952 input, activeDesc->mIoHandle);
1953 return INVALID_OPERATION;
1954 }
1955 } else {
1956 if (activeSource != AUDIO_SOURCE_HOTWORD) {
1957 ALOGW("startInput(%d) failed: other input %d already started",
1958 input, activeDesc->mIoHandle);
1959 return INVALID_OPERATION;
1960 }
1961 }
1962 }
1963
Chris Thornton2b864642017-06-27 21:26:07 -07001964 // We only need to check if the sound trigger session supports concurrent capture if the
1965 // input is also a sound trigger input. Otherwise, we should preempt any hotword stream
1966 // that's running.
1967 const bool allowConcurrentWithSoundTrigger =
1968 inputDesc->isSoundTrigger() ? soundTriggerSupportsConcurrentCapture() : false;
1969
Eric Laurent74708e72017-04-07 17:13:42 -07001970 // if capture is allowed, preempt currently active HOTWORD captures
1971 for (size_t i = 0; i < activeInputs.size(); i++) {
1972 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
1973
1974 if (is_virtual_input_device(activeDesc->mDevice)) {
1975 continue;
1976 }
1977
Chris Thornton2b864642017-06-27 21:26:07 -07001978 if (allowConcurrentWithSoundTrigger && activeDesc->isSoundTrigger()) {
1979 continue;
1980 }
1981
Eric Laurent74708e72017-04-07 17:13:42 -07001982 audio_source_t activeSource = activeDesc->inputSource(true);
1983 if (activeSource == AUDIO_SOURCE_HOTWORD) {
1984 AudioSessionCollection activeSessions =
1985 activeDesc->getAudioSessions(true /*activeOnly*/);
1986 audio_session_t activeSession = activeSessions.keyAt(0);
1987 audio_io_handle_t activeHandle = activeDesc->mIoHandle;
1988 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1989 sessions.add(activeSession);
1990 inputDesc->setPreemptedSessions(sessions);
1991 stopInput(activeHandle, activeSession);
1992 releaseInput(activeHandle, activeSession);
1993 ALOGV("startInput(%d) for HOTWORD preempting HOTWORD input %d",
1994 input, activeDesc->mIoHandle);
1995 }
1996 }
1997 }
1998#endif
Eric Laurente552edb2014-03-10 17:42:56 -07001999
Eric Laurent313d1e72016-01-29 09:56:57 -08002000 // increment activity count before calling getNewInputDevice() below as only active sessions
2001 // are considered for device selection
2002 audioSession->changeActiveCount(1);
2003
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002004 // Routing?
2005 mInputRoutes.incRouteActivity(session);
2006
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002007 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07002008 // indicate active capture to sound trigger service if starting capture from a mic on
2009 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07002010 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07002011 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07002012
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002013 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
2014 // if input maps to a dynamic policy with an activity listener, notify of state change
2015 if ((inputDesc->mPolicyMix != NULL)
2016 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2017 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2018 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08002019 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002020
Eric Laurentf7c50102016-09-30 15:19:43 -07002021 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2022 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08002023 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002024 SoundTrigger::setCaptureState(true);
2025 }
2026
2027 // automatically enable the remote submix output when input is started if not
2028 // used by a policy mix of type MIX_TYPE_RECORDERS
2029 // For remote submix (a virtual device), we open only one input per capture request.
2030 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2031 String8 address = String8("");
2032 if (inputDesc->mPolicyMix == NULL) {
2033 address = String8("0");
2034 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2035 address = inputDesc->mPolicyMix->mDeviceAddress;
2036 }
2037 if (address != "") {
2038 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2039 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2040 address, "remote-submix");
2041 }
Eric Laurentc722f302014-12-10 11:21:49 -08002042 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002043 }
Eric Laurente552edb2014-03-10 17:42:56 -07002044 }
2045
Eric Laurent599c7582015-12-07 18:05:55 -08002046 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07002047
Eric Laurente552edb2014-03-10 17:42:56 -07002048 return NO_ERROR;
2049}
2050
Eric Laurent4dc68062014-07-28 17:26:49 -07002051status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
2052 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002053{
2054 ALOGV("stopInput() input %d", input);
2055 ssize_t index = mInputs.indexOfKey(input);
2056 if (index < 0) {
2057 ALOGW("stopInput() unknown input %d", input);
2058 return BAD_VALUE;
2059 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002060 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07002061
Eric Laurent599c7582015-12-07 18:05:55 -08002062 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07002063 if (index < 0) {
2064 ALOGW("stopInput() unknown session %d on input %d", session, input);
2065 return BAD_VALUE;
2066 }
2067
Eric Laurent599c7582015-12-07 18:05:55 -08002068 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002069 ALOGW("stopInput() input %d already stopped", input);
2070 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002071 }
2072
Eric Laurent599c7582015-12-07 18:05:55 -08002073 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06002074
2075 // Routing?
2076 mInputRoutes.decRouteActivity(session);
2077
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002078 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00002079
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002080 if (inputDesc->isActive()) {
2081 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2082 } else {
2083 // if input maps to a dynamic policy with an activity listener, notify of state change
2084 if ((inputDesc->mPolicyMix != NULL)
2085 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2086 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
2087 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002088 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002089
2090 // automatically disable the remote submix output when input is stopped if not
2091 // used by a policy mix of type MIX_TYPE_RECORDERS
2092 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
2093 String8 address = String8("");
2094 if (inputDesc->mPolicyMix == NULL) {
2095 address = String8("0");
2096 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
2097 address = inputDesc->mPolicyMix->mDeviceAddress;
2098 }
2099 if (address != "") {
2100 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2101 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2102 address, "remote-submix");
2103 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002104 }
Eric Laurent84332aa2016-01-28 22:19:18 +00002105
Eric Laurentf7c50102016-09-30 15:19:43 -07002106 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08002107 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00002108
Eric Laurentf7c50102016-09-30 15:19:43 -07002109 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2110 // primary HW module
2111 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
2112 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
2113 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08002114 SoundTrigger::setCaptureState(false);
2115 }
2116 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00002117 }
Eric Laurente552edb2014-03-10 17:42:56 -07002118 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002119 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002120}
2121
Eric Laurent4dc68062014-07-28 17:26:49 -07002122void AudioPolicyManager::releaseInput(audio_io_handle_t input,
2123 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07002124{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08002125
Eric Laurente552edb2014-03-10 17:42:56 -07002126 ALOGV("releaseInput() %d", input);
2127 ssize_t index = mInputs.indexOfKey(input);
2128 if (index < 0) {
2129 ALOGW("releaseInput() releasing unknown input %d", input);
2130 return;
2131 }
Paul McLean466dc8e2015-04-17 13:15:36 -06002132
2133 // Routing
2134 mInputRoutes.removeRoute(session);
2135
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002136 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2137 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07002138
Eric Laurent599c7582015-12-07 18:05:55 -08002139 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08002140 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07002141 ALOGW("releaseInput() unknown session %d on input %d", session, input);
2142 return;
2143 }
Eric Laurent599c7582015-12-07 18:05:55 -08002144
2145 if (audioSession->openCount() == 0) {
2146 ALOGW("releaseInput() invalid open count %d on session %d",
2147 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002148 return;
2149 }
Eric Laurent599c7582015-12-07 18:05:55 -08002150
2151 if (audioSession->changeOpenCount(-1) == 0) {
2152 inputDesc->removeAudioSession(session);
2153 }
2154
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08002155 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002156 ALOGV("releaseInput() exit > 0");
2157 return;
2158 }
2159
Eric Laurent05b90f82014-08-27 15:32:29 -07002160 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002161 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002162 ALOGV("releaseInput() exit");
2163}
2164
Eric Laurentd4692962014-05-05 18:13:44 -07002165void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07002166 bool patchRemoved = false;
2167
Eric Laurentd4692962014-05-05 18:13:44 -07002168 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07002169 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08002170 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07002171 if (patch_index >= 0) {
2172 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07002173 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07002174 mAudioPatches.removeItemsAt(patch_index);
2175 patchRemoved = true;
2176 }
Eric Laurentd4692962014-05-05 18:13:44 -07002177 mpClientInterface->closeInput(mInputs.keyAt(input_index));
2178 }
2179 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08002180 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07002181 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07002182
2183 if (patchRemoved) {
2184 mpClientInterface->onAudioPatchListUpdate();
2185 }
Eric Laurentd4692962014-05-05 18:13:44 -07002186}
2187
Eric Laurente0720872014-03-11 09:30:41 -07002188void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002189 int indexMin,
2190 int indexMax)
2191{
2192 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002193 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002194
2195 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002196 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2197 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002198 continue;
2199 }
2200 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002201 }
Eric Laurente552edb2014-03-10 17:42:56 -07002202}
2203
Eric Laurente0720872014-03-11 09:30:41 -07002204status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002205 int index,
2206 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002207{
2208
François Gaffied1ab2bd2015-12-02 18:20:06 +01002209 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2210 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002211 return BAD_VALUE;
2212 }
2213 if (!audio_is_output_device(device)) {
2214 return BAD_VALUE;
2215 }
2216
2217 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002218 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002219
Eric Laurent1fd372e2016-04-06 14:23:53 -07002220 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002221 stream, device, index);
2222
Eric Laurent28d09f02016-03-08 10:43:05 -08002223 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002224 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2225 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002226 continue;
2227 }
2228 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2229 }
Eric Laurente552edb2014-03-10 17:42:56 -07002230
Eric Laurent1fd372e2016-04-06 14:23:53 -07002231 // update volume on all outputs and streams matching the following:
2232 // - The requested stream (or a stream matching for volume control) is active on the output
2233 // - The device (or devices) selected by the strategy corresponding to this stream includes
2234 // the requested device
2235 // - For non default requested device, currently selected device on the output is either the
2236 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002237 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2238 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002239 status_t status = NO_ERROR;
2240 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002241 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2242 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002243 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2244 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002245 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002246 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002247 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2248 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002249 continue;
2250 }
Eric Laurent794fde22016-03-11 09:50:45 -08002251 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002252 audio_devices_t curStreamDevice = Volume::getDeviceForVolume(getDeviceForStrategy(
2253 curStrategy, false /*fromCache*/));
Eric Laurente76f29c2016-09-14 17:17:53 -07002254 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2255 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002256 continue;
2257 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002258 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002259 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002260 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002261 applyVolume = (curDevice & curStreamDevice) != 0;
2262 } else {
2263 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
Jean-Michel Trivib7fdce62017-06-27 19:38:42 -07002264 stream, curStreamDevice);
Eric Laurent1fd372e2016-04-06 14:23:53 -07002265 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002266
Eric Laurente76f29c2016-09-14 17:17:53 -07002267 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002268 //FIXME: workaround for truncated touch sounds
2269 // delayed volume change for system stream to be removed when the problem is
2270 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002271 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002272 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2273 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002274 if (volStatus != NO_ERROR) {
2275 status = volStatus;
2276 }
2277 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002278 }
Eric Laurente552edb2014-03-10 17:42:56 -07002279 }
2280 return status;
2281}
2282
Eric Laurente0720872014-03-11 09:30:41 -07002283status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002284 int *index,
2285 audio_devices_t device)
2286{
2287 if (index == NULL) {
2288 return BAD_VALUE;
2289 }
2290 if (!audio_is_output_device(device)) {
2291 return BAD_VALUE;
2292 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002293 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002294 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002295 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002296 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2297 }
François Gaffiedfd74092015-03-19 12:10:59 +01002298 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002299
François Gaffied1ab2bd2015-12-02 18:20:06 +01002300 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002301 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2302 return NO_ERROR;
2303}
2304
Eric Laurent36829f92017-04-07 19:04:42 -07002305audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07002306{
2307 // select one output among several suitable for global effects.
2308 // The priority is as follows:
2309 // 1: An offloaded output. If the effect ends up not being offloadable,
2310 // AudioFlinger will invalidate the track and the offloaded output
2311 // will be closed causing the effect to be moved to a PCM output.
2312 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07002313 // 3: The primary output
2314 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002315
Eric Laurent3b73df72014-03-11 09:06:29 -07002316 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002317 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent36829f92017-04-07 19:04:42 -07002318 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07002319
Eric Laurent36829f92017-04-07 19:04:42 -07002320 if (outputs.size() == 0) {
2321 return AUDIO_IO_HANDLE_NONE;
2322 }
Eric Laurente552edb2014-03-10 17:42:56 -07002323
Eric Laurent36829f92017-04-07 19:04:42 -07002324 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2325 bool activeOnly = true;
2326
2327 while (output == AUDIO_IO_HANDLE_NONE) {
2328 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2329 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2330 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2331
2332 for (size_t i = 0; i < outputs.size(); i++) {
2333 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
2334 if (activeOnly && !desc->isStreamActive(AUDIO_STREAM_MUSIC)) {
2335 continue;
2336 }
2337 ALOGV("selectOutputForMusicEffects activeOnly %d outputs[%zu] flags 0x%08x",
2338 activeOnly, i, desc->mFlags);
2339 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2340 outputOffloaded = outputs[i];
2341 }
2342 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2343 outputDeepBuffer = outputs[i];
2344 }
2345 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2346 outputPrimary = outputs[i];
2347 }
2348 }
2349 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2350 output = outputOffloaded;
2351 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2352 output = outputDeepBuffer;
2353 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2354 output = outputPrimary;
2355 } else {
2356 output = outputs[0];
2357 }
2358 activeOnly = false;
2359 }
2360
2361 if (output != mMusicEffectOutput) {
2362 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2363 mMusicEffectOutput = output;
2364 }
2365
2366 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07002367 return output;
2368}
2369
Eric Laurent36829f92017-04-07 19:04:42 -07002370audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2371{
2372 return selectOutputForMusicEffects();
2373}
2374
Eric Laurente0720872014-03-11 09:30:41 -07002375status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002376 audio_io_handle_t io,
2377 uint32_t strategy,
2378 int session,
2379 int id)
2380{
2381 ssize_t index = mOutputs.indexOfKey(io);
2382 if (index < 0) {
2383 index = mInputs.indexOfKey(io);
2384 if (index < 0) {
2385 ALOGW("registerEffect() unknown io %d", io);
2386 return INVALID_OPERATION;
2387 }
2388 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002389 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002390}
2391
Eric Laurentc75307b2015-03-17 15:29:32 -07002392bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2393{
Eric Laurent28d09f02016-03-08 10:43:05 -08002394 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002395 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2396 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002397 continue;
2398 }
2399 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2400 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002401 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002402}
2403
2404bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2405{
2406 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2407}
2408
Eric Laurente0720872014-03-11 09:30:41 -07002409bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002410{
2411 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002412 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002413 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002414 return true;
2415 }
2416 }
2417 return false;
2418}
2419
Eric Laurent275e8e92014-11-30 15:14:47 -08002420// Register a list of custom mixes with their attributes and format.
2421// When a mix is registered, corresponding input and output profiles are
2422// added to the remote submix hw module. The profile contains only the
2423// parameters (sampling rate, format...) specified by the mix.
2424// The corresponding input remote submix device is also connected.
2425//
2426// When a remote submix device is connected, the address is checked to select the
2427// appropriate profile and the corresponding input or output stream is opened.
2428//
2429// When capture starts, getInputForAttr() will:
2430// - 1 look for a mix matching the address passed in attribtutes tags if any
2431// - 2 if none found, getDeviceForInputSource() will:
2432// - 2.1 look for a mix matching the attributes source
2433// - 2.2 if none found, default to device selection by policy rules
2434// At this time, the corresponding output remote submix device is also connected
2435// and active playback use cases can be transferred to this mix if needed when reconnecting
2436// after AudioTracks are invalidated
2437//
2438// When playback starts, getOutputForAttr() will:
2439// - 1 look for a mix matching the address passed in attribtutes tags if any
2440// - 2 if none found, look for a mix matching the attributes usage
2441// - 3 if none found, default to device and output selection by policy rules.
2442
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002443status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002444{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002445 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2446 status_t res = NO_ERROR;
2447
2448 sp<HwModule> rSubmixModule;
2449 // examine each mix's route type
2450 for (size_t i = 0; i < mixes.size(); i++) {
2451 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2452 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2453 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002454 break;
2455 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002456 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2457 // Loop back through "remote submix"
2458 if (rSubmixModule == 0) {
2459 for (size_t j = 0; i < mHwModules.size(); j++) {
2460 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2461 && mHwModules[j]->mHandle != 0) {
2462 rSubmixModule = mHwModules[j];
2463 break;
2464 }
2465 }
2466 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002467
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002468 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002469
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002470 if (rSubmixModule == 0) {
2471 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2472 res = INVALID_OPERATION;
2473 break;
2474 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002475
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002476 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002477
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002478 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002479 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002480 res = INVALID_OPERATION;
2481 break;
2482 }
2483 audio_config_t outputConfig = mixes[i].mFormat;
2484 audio_config_t inputConfig = mixes[i].mFormat;
2485 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2486 // stereo and let audio flinger do the channel conversion if needed.
2487 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2488 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2489 rSubmixModule->addOutputProfile(address, &outputConfig,
2490 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2491 rSubmixModule->addInputProfile(address, &inputConfig,
2492 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002493
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002494 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2495 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2496 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2497 address.string(), "remote-submix");
2498 } else {
2499 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2500 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2501 address.string(), "remote-submix");
2502 }
2503 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002504 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002505 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002506 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2507 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002508
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002509 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002510 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2511 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2512 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2513 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2514 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2515 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002516 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2517 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002518 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2519 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002520 } else {
2521 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002522 }
2523 break;
2524 }
2525 }
2526
2527 if (res != NO_ERROR) {
2528 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002529 i, device, address.string());
2530 res = INVALID_OPERATION;
2531 break;
2532 } else if (!foundOutput) {
2533 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2534 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002535 res = INVALID_OPERATION;
2536 break;
2537 }
Eric Laurentc722f302014-12-10 11:21:49 -08002538 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002539 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002540 if (res != NO_ERROR) {
2541 unregisterPolicyMixes(mixes);
2542 }
2543 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002544}
2545
2546status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2547{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002548 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002549 status_t res = NO_ERROR;
2550 sp<HwModule> rSubmixModule;
2551 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002552 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002553 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002554
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002555 if (rSubmixModule == 0) {
2556 for (size_t j = 0; i < mHwModules.size(); j++) {
2557 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2558 && mHwModules[j]->mHandle != 0) {
2559 rSubmixModule = mHwModules[j];
2560 break;
2561 }
2562 }
2563 }
2564 if (rSubmixModule == 0) {
2565 res = INVALID_OPERATION;
2566 continue;
2567 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002568
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002569 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002570
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002571 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2572 res = INVALID_OPERATION;
2573 continue;
2574 }
2575
2576 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2577 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2578 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2579 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2580 address.string(), "remote-submix");
2581 }
2582 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2584 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2585 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2586 address.string(), "remote-submix");
2587 }
2588 rSubmixModule->removeOutputProfile(address);
2589 rSubmixModule->removeInputProfile(address);
2590
2591 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2592 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2593 res = INVALID_OPERATION;
2594 continue;
2595 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002596 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002597 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002598 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002599}
2600
Eric Laurente552edb2014-03-10 17:42:56 -07002601
Eric Laurente0720872014-03-11 09:30:41 -07002602status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002603{
2604 const size_t SIZE = 256;
2605 char buffer[SIZE];
2606 String8 result;
2607
2608 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2609 result.append(buffer);
2610
Eric Laurent87ffa392015-05-22 10:32:38 -07002611 snprintf(buffer, SIZE, " Primary Output: %d\n",
2612 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002614 std::string stateLiteral;
2615 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2616 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002617 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002618 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002619 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002620 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002621 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002622 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002623 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002624 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002625 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002626 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002627 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002628 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002629 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002630 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002631 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002632 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2633 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2634 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002635 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2636 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002637 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2638 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002639
François Gaffie2110e042015-03-24 08:41:51 +01002640 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002641
François Gaffie112b0af2015-11-19 16:13:25 +01002642 mAvailableOutputDevices.dump(fd, String8("Available output"));
2643 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002644 mHwModules.dump(fd);
2645 mOutputs.dump(fd);
2646 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002647 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002648 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002649 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002650 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002651
2652 return NO_ERROR;
2653}
2654
2655// This function checks for the parameters which can be offloaded.
2656// This can be enhanced depending on the capability of the DSP and policy
2657// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002658bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002659{
2660 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002661 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002662 offloadInfo.sample_rate, offloadInfo.channel_mask,
2663 offloadInfo.format,
2664 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2665 offloadInfo.has_video);
2666
Andy Hung2ddee192015-12-18 17:34:44 -08002667 if (mMasterMono) {
2668 return false; // no offloading if mono is set.
2669 }
2670
Eric Laurente552edb2014-03-10 17:42:56 -07002671 // Check if offload has been disabled
2672 char propValue[PROPERTY_VALUE_MAX];
2673 if (property_get("audio.offload.disable", propValue, "0")) {
2674 if (atoi(propValue) != 0) {
2675 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2676 return false;
2677 }
2678 }
2679
2680 // Check if stream type is music, then only allow offload as of now.
2681 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2682 {
2683 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2684 return false;
2685 }
2686
2687 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002688 const bool allowOffloadWithVideo =
2689 property_get_bool("audio.offload.video", false /* default_value */);
2690 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002691 ALOGV("isOffloadSupported: has_video == true, returning false");
2692 return false;
2693 }
2694
2695 //If duration is less than minimum value defined in property, return false
2696 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2697 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2698 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2699 return false;
2700 }
2701 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2702 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2703 return false;
2704 }
2705
2706 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2707 // creating an offloaded track and tearing it down immediately after start when audioflinger
2708 // detects there is an active non offloadable effect.
2709 // FIXME: We should check the audio session here but we do not have it in this context.
2710 // This may prevent offloading in rare situations where effects are left active by apps
2711 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002712 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002713 return false;
2714 }
2715
2716 // See if there is a profile to support this.
2717 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002718 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002719 offloadInfo.sample_rate,
2720 offloadInfo.format,
2721 offloadInfo.channel_mask,
2722 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002723 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2724 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002725}
2726
Eric Laurent6a94d692014-05-20 11:18:06 -07002727status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2728 audio_port_type_t type,
2729 unsigned int *num_ports,
2730 struct audio_port *ports,
2731 unsigned int *generation)
2732{
2733 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2734 generation == NULL) {
2735 return BAD_VALUE;
2736 }
2737 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2738 if (ports == NULL) {
2739 *num_ports = 0;
2740 }
2741
2742 size_t portsWritten = 0;
2743 size_t portsMax = *num_ports;
2744 *num_ports = 0;
2745 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002746 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2747 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002748 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002749 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2750 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2751 continue;
2752 }
2753 if (portsWritten < portsMax) {
2754 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2755 }
2756 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002757 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002758 }
2759 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002760 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2761 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2762 continue;
2763 }
2764 if (portsWritten < portsMax) {
2765 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2766 }
2767 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002768 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002769 }
2770 }
2771 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2772 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2773 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2774 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2775 }
2776 *num_ports += mInputs.size();
2777 }
2778 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002779 size_t numOutputs = 0;
2780 for (size_t i = 0; i < mOutputs.size(); i++) {
2781 if (!mOutputs[i]->isDuplicated()) {
2782 numOutputs++;
2783 if (portsWritten < portsMax) {
2784 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2785 }
2786 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002787 }
Eric Laurent84c70242014-06-23 08:46:27 -07002788 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002789 }
2790 }
2791 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002792 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002793 return NO_ERROR;
2794}
2795
2796status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2797{
2798 return NO_ERROR;
2799}
2800
Eric Laurent6a94d692014-05-20 11:18:06 -07002801status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2802 audio_patch_handle_t *handle,
2803 uid_t uid)
2804{
2805 ALOGV("createAudioPatch()");
2806
2807 if (handle == NULL || patch == NULL) {
2808 return BAD_VALUE;
2809 }
2810 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2811
Eric Laurent874c42872014-08-08 15:13:39 -07002812 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2813 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2814 return BAD_VALUE;
2815 }
2816 // only one source per audio patch supported for now
2817 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002818 return INVALID_OPERATION;
2819 }
Eric Laurent874c42872014-08-08 15:13:39 -07002820
2821 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002822 return INVALID_OPERATION;
2823 }
Eric Laurent874c42872014-08-08 15:13:39 -07002824 for (size_t i = 0; i < patch->num_sinks; i++) {
2825 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2826 return INVALID_OPERATION;
2827 }
2828 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002829
2830 sp<AudioPatch> patchDesc;
2831 ssize_t index = mAudioPatches.indexOfKey(*handle);
2832
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2834 patch->sources[0].role,
2835 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002836#if LOG_NDEBUG == 0
2837 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002838 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002839 patch->sinks[i].role,
2840 patch->sinks[i].type);
2841 }
2842#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002843
2844 if (index >= 0) {
2845 patchDesc = mAudioPatches.valueAt(index);
2846 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2847 mUidCached, patchDesc->mUid, uid);
2848 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2849 return INVALID_OPERATION;
2850 }
2851 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002852 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002853 }
2854
2855 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002856 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002857 if (outputDesc == NULL) {
2858 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2859 return BAD_VALUE;
2860 }
Eric Laurent84c70242014-06-23 08:46:27 -07002861 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2862 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002863 if (patchDesc != 0) {
2864 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2865 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2866 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2867 return BAD_VALUE;
2868 }
2869 }
Eric Laurent874c42872014-08-08 15:13:39 -07002870 DeviceVector devices;
2871 for (size_t i = 0; i < patch->num_sinks; i++) {
2872 // Only support mix to devices connection
2873 // TODO add support for mix to mix connection
2874 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2875 ALOGV("createAudioPatch() source mix but sink is not a device");
2876 return INVALID_OPERATION;
2877 }
2878 sp<DeviceDescriptor> devDesc =
2879 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2880 if (devDesc == 0) {
2881 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2882 return BAD_VALUE;
2883 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002884
François Gaffie53615e22015-03-19 09:24:12 +01002885 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002886 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002887 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002888 NULL, // updatedSamplingRate
2889 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002890 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002891 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002892 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002893 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002894 ALOGV("createAudioPatch() profile not supported for device %08x",
2895 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002896 return INVALID_OPERATION;
2897 }
2898 devices.add(devDesc);
2899 }
2900 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002901 return INVALID_OPERATION;
2902 }
Eric Laurent874c42872014-08-08 15:13:39 -07002903
Eric Laurent6a94d692014-05-20 11:18:06 -07002904 // TODO: reconfigure output format and channels here
2905 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002906 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002907 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002908 index = mAudioPatches.indexOfKey(*handle);
2909 if (index >= 0) {
2910 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2911 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2912 }
2913 patchDesc = mAudioPatches.valueAt(index);
2914 patchDesc->mUid = uid;
2915 ALOGV("createAudioPatch() success");
2916 } else {
2917 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2918 return INVALID_OPERATION;
2919 }
2920 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2921 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2922 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002923 // only one sink supported when connecting an input device to a mix
2924 if (patch->num_sinks > 1) {
2925 return INVALID_OPERATION;
2926 }
François Gaffie53615e22015-03-19 09:24:12 +01002927 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002928 if (inputDesc == NULL) {
2929 return BAD_VALUE;
2930 }
2931 if (patchDesc != 0) {
2932 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2933 return BAD_VALUE;
2934 }
2935 }
2936 sp<DeviceDescriptor> devDesc =
2937 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2938 if (devDesc == 0) {
2939 return BAD_VALUE;
2940 }
2941
François Gaffie53615e22015-03-19 09:24:12 +01002942 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002943 devDesc->mAddress,
2944 patch->sinks[0].sample_rate,
2945 NULL, /*updatedSampleRate*/
2946 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002947 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002948 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002949 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002950 // FIXME for the parameter type,
2951 // and the NONE
2952 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002953 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002954 return INVALID_OPERATION;
2955 }
2956 // TODO: reconfigure output format and channels here
2957 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002958 devDesc->type(), inputDesc->mIoHandle);
2959 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002960 index = mAudioPatches.indexOfKey(*handle);
2961 if (index >= 0) {
2962 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2963 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2964 }
2965 patchDesc = mAudioPatches.valueAt(index);
2966 patchDesc->mUid = uid;
2967 ALOGV("createAudioPatch() success");
2968 } else {
2969 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2970 return INVALID_OPERATION;
2971 }
2972 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2973 // device to device connection
2974 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002975 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002976 return BAD_VALUE;
2977 }
2978 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002979 sp<DeviceDescriptor> srcDeviceDesc =
2980 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002981 if (srcDeviceDesc == 0) {
2982 return BAD_VALUE;
2983 }
Eric Laurent874c42872014-08-08 15:13:39 -07002984
Eric Laurent6a94d692014-05-20 11:18:06 -07002985 //update source and sink with our own data as the data passed in the patch may
2986 // be incomplete.
2987 struct audio_patch newPatch = *patch;
2988 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002989
Eric Laurent874c42872014-08-08 15:13:39 -07002990 for (size_t i = 0; i < patch->num_sinks; i++) {
2991 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2992 ALOGV("createAudioPatch() source device but one sink is not a device");
2993 return INVALID_OPERATION;
2994 }
2995
2996 sp<DeviceDescriptor> sinkDeviceDesc =
2997 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2998 if (sinkDeviceDesc == 0) {
2999 return BAD_VALUE;
3000 }
3001 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3002
Eric Laurent3bcf8592015-04-03 12:13:24 -07003003 // create a software bridge in PatchPanel if:
3004 // - source and sink devices are on differnt HW modules OR
3005 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08003006 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003007 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07003008 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07003009 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07003010 return INVALID_OPERATION;
3011 }
Eric Laurent874c42872014-08-08 15:13:39 -07003012 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01003013 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07003014 // if the sink device is reachable via an opened output stream, request to go via
3015 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07003016 audio_io_handle_t output = selectOutput(outputs,
3017 AUDIO_OUTPUT_FLAG_NONE,
3018 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07003019 if (output != AUDIO_IO_HANDLE_NONE) {
3020 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3021 if (outputDesc->isDuplicated()) {
3022 return INVALID_OPERATION;
3023 }
3024 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07003025 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07003026 newPatch.num_sources = 2;
3027 }
Eric Laurent83b88082014-06-20 18:31:16 -07003028 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003029 }
3030 // TODO: check from routing capabilities in config file and other conflicting patches
3031
3032 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3033 if (index >= 0) {
3034 afPatchHandle = patchDesc->mAfPatchHandle;
3035 }
3036
3037 status_t status = mpClientInterface->createAudioPatch(&newPatch,
3038 &afPatchHandle,
3039 0);
3040 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
3041 status, afPatchHandle);
3042 if (status == NO_ERROR) {
3043 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01003044 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003045 addAudioPatch(patchDesc->mHandle, patchDesc);
3046 } else {
3047 patchDesc->mPatch = newPatch;
3048 }
3049 patchDesc->mAfPatchHandle = afPatchHandle;
3050 *handle = patchDesc->mHandle;
3051 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003052 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003053 } else {
3054 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3055 status);
3056 return INVALID_OPERATION;
3057 }
3058 } else {
3059 return BAD_VALUE;
3060 }
3061 } else {
3062 return BAD_VALUE;
3063 }
3064 return NO_ERROR;
3065}
3066
3067status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3068 uid_t uid)
3069{
3070 ALOGV("releaseAudioPatch() patch %d", handle);
3071
3072 ssize_t index = mAudioPatches.indexOfKey(handle);
3073
3074 if (index < 0) {
3075 return BAD_VALUE;
3076 }
3077 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3078 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3079 mUidCached, patchDesc->mUid, uid);
3080 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3081 return INVALID_OPERATION;
3082 }
3083
3084 struct audio_patch *patch = &patchDesc->mPatch;
3085 patchDesc->mUid = mUidCached;
3086 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003087 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003088 if (outputDesc == NULL) {
3089 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3090 return BAD_VALUE;
3091 }
3092
Eric Laurentc75307b2015-03-17 15:29:32 -07003093 setOutputDevice(outputDesc,
3094 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07003095 true,
3096 0,
3097 NULL);
3098 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3099 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01003100 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07003101 if (inputDesc == NULL) {
3102 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3103 return BAD_VALUE;
3104 }
3105 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08003106 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07003107 true,
3108 NULL);
3109 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003110 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3111 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3112 status, patchDesc->mAfPatchHandle);
3113 removeAudioPatch(patchDesc->mHandle);
3114 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003115 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07003116 } else {
3117 return BAD_VALUE;
3118 }
3119 } else {
3120 return BAD_VALUE;
3121 }
3122 return NO_ERROR;
3123}
3124
3125status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3126 struct audio_patch *patches,
3127 unsigned int *generation)
3128{
François Gaffie53615e22015-03-19 09:24:12 +01003129 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003130 return BAD_VALUE;
3131 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003132 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01003133 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07003134}
3135
Eric Laurente1715a42014-05-20 11:30:42 -07003136status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07003137{
Eric Laurente1715a42014-05-20 11:30:42 -07003138 ALOGV("setAudioPortConfig()");
3139
3140 if (config == NULL) {
3141 return BAD_VALUE;
3142 }
3143 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3144 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07003145 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3146 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07003147 }
3148
Eric Laurenta121f902014-06-03 13:32:54 -07003149 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07003150 if (config->type == AUDIO_PORT_TYPE_MIX) {
3151 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003152 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003153 if (outputDesc == NULL) {
3154 return BAD_VALUE;
3155 }
Eric Laurent84c70242014-06-23 08:46:27 -07003156 ALOG_ASSERT(!outputDesc->isDuplicated(),
3157 "setAudioPortConfig() called on duplicated output %d",
3158 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07003159 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003160 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01003161 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07003162 if (inputDesc == NULL) {
3163 return BAD_VALUE;
3164 }
Eric Laurenta121f902014-06-03 13:32:54 -07003165 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003166 } else {
3167 return BAD_VALUE;
3168 }
3169 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3170 sp<DeviceDescriptor> deviceDesc;
3171 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3172 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3173 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3174 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3175 } else {
3176 return BAD_VALUE;
3177 }
3178 if (deviceDesc == NULL) {
3179 return BAD_VALUE;
3180 }
Eric Laurenta121f902014-06-03 13:32:54 -07003181 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07003182 } else {
3183 return BAD_VALUE;
3184 }
3185
Eric Laurenta121f902014-06-03 13:32:54 -07003186 struct audio_port_config backupConfig;
3187 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3188 if (status == NO_ERROR) {
3189 struct audio_port_config newConfig;
3190 audioPortConfig->toAudioPortConfig(&newConfig, config);
3191 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07003192 }
Eric Laurenta121f902014-06-03 13:32:54 -07003193 if (status != NO_ERROR) {
3194 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07003195 }
Eric Laurente1715a42014-05-20 11:30:42 -07003196
3197 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07003198}
3199
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003200void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3201{
Eric Laurentd60560a2015-04-10 11:31:20 -07003202 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003203 clearAudioPatches(uid);
3204 clearSessionRoutes(uid);
3205}
3206
Eric Laurent6a94d692014-05-20 11:18:06 -07003207void AudioPolicyManager::clearAudioPatches(uid_t uid)
3208{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003209 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003210 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3211 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003212 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003213 }
3214 }
3215}
3216
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003217void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3218 audio_io_handle_t ouptutToSkip)
3219{
3220 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3221 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3222 for (size_t j = 0; j < mOutputs.size(); j++) {
3223 if (mOutputs.keyAt(j) == ouptutToSkip) {
3224 continue;
3225 }
3226 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3227 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3228 continue;
3229 }
3230 // If the default device for this strategy is on another output mix,
3231 // invalidate all tracks in this strategy to force re connection.
3232 // Otherwise select new device on the output mix.
3233 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003234 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003235 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3236 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3237 }
3238 }
3239 } else {
3240 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3241 setOutputDevice(outputDesc, newDevice, false);
3242 }
3243 }
3244}
3245
3246void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3247{
3248 // remove output routes associated with this uid
3249 SortedVector<routing_strategy> affectedStrategies;
3250 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3251 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3252 if (route->mUid == uid) {
3253 mOutputRoutes.removeItemsAt(i);
3254 if (route->mDeviceDescriptor != 0) {
3255 affectedStrategies.add(getStrategy(route->mStreamType));
3256 }
3257 }
3258 }
3259 // reroute outputs if necessary
3260 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3261 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3262 }
3263
3264 // remove input routes associated with this uid
3265 SortedVector<audio_source_t> affectedSources;
3266 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3267 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3268 if (route->mUid == uid) {
3269 mInputRoutes.removeItemsAt(i);
3270 if (route->mDeviceDescriptor != 0) {
3271 affectedSources.add(route->mSource);
3272 }
3273 }
3274 }
3275 // reroute inputs if necessary
3276 SortedVector<audio_io_handle_t> inputsToClose;
3277 for (size_t i = 0; i < mInputs.size(); i++) {
3278 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003279 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003280 inputsToClose.add(inputDesc->mIoHandle);
3281 }
3282 }
3283 for (size_t i = 0; i < inputsToClose.size(); i++) {
3284 closeInput(inputsToClose[i]);
3285 }
3286}
3287
Eric Laurentd60560a2015-04-10 11:31:20 -07003288void AudioPolicyManager::clearAudioSources(uid_t uid)
3289{
3290 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3291 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3292 if (sourceDesc->mUid == uid) {
3293 stopAudioSource(mAudioSources.keyAt(i));
3294 }
3295 }
3296}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003297
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003298status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3299 audio_io_handle_t *ioHandle,
3300 audio_devices_t *device)
3301{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003302 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3303 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003304 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003305
François Gaffiedf372692015-03-19 10:43:27 +01003306 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003307}
3308
Eric Laurentd60560a2015-04-10 11:31:20 -07003309status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3310 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003311 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003312 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003313{
Eric Laurentd60560a2015-04-10 11:31:20 -07003314 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3315 if (source == NULL || attributes == NULL || handle == NULL) {
3316 return BAD_VALUE;
3317 }
3318
Glenn Kasten559d4392016-03-29 13:42:57 -07003319 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003320
3321 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3322 source->type != AUDIO_PORT_TYPE_DEVICE) {
3323 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3324 return INVALID_OPERATION;
3325 }
3326
3327 sp<DeviceDescriptor> srcDeviceDesc =
3328 mAvailableInputDevices.getDevice(source->ext.device.type,
3329 String8(source->ext.device.address));
3330 if (srcDeviceDesc == 0) {
3331 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3332 return BAD_VALUE;
3333 }
3334 sp<AudioSourceDescriptor> sourceDesc =
3335 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3336
3337 struct audio_patch dummyPatch;
3338 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3339 sourceDesc->mPatchDesc = patchDesc;
3340
3341 status_t status = connectAudioSource(sourceDesc);
3342 if (status == NO_ERROR) {
3343 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3344 *handle = sourceDesc->getHandle();
3345 }
3346 return status;
3347}
3348
3349status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3350{
3351 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3352
3353 // make sure we only have one patch per source.
3354 disconnectAudioSource(sourceDesc);
3355
3356 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003357 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003358 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3359
3360 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3361 sp<DeviceDescriptor> sinkDeviceDesc =
3362 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3363
3364 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3365 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3366
3367 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3368 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003369 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003370 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3371 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3372 // create patch between src device and output device
3373 // create Hwoutput and add to mHwOutputs
3374 } else {
3375 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3376 audio_io_handle_t output =
3377 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3378 if (output == AUDIO_IO_HANDLE_NONE) {
3379 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3380 return INVALID_OPERATION;
3381 }
3382 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3383 if (outputDesc->isDuplicated()) {
3384 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3385 return INVALID_OPERATION;
3386 }
3387 // create a special patch with no sink and two sources:
3388 // - the second source indicates to PatchPanel through which output mix this patch should
3389 // be connected as well as the stream type for volume control
3390 // - the sink is defined by whatever output device is currently selected for the output
3391 // though which this patch is routed.
3392 patch->num_sinks = 0;
3393 patch->num_sources = 2;
3394 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3395 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3396 patch->sources[1].ext.mix.usecase.stream = stream;
3397 status_t status = mpClientInterface->createAudioPatch(patch,
3398 &afPatchHandle,
3399 0);
3400 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3401 status, afPatchHandle);
3402 if (status != NO_ERROR) {
3403 ALOGW("%s patch panel could not connect device patch, error %d",
3404 __FUNCTION__, status);
3405 return INVALID_OPERATION;
3406 }
3407 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003408 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003409
3410 if (status != NO_ERROR) {
3411 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3412 return status;
3413 }
3414 sourceDesc->mSwOutput = outputDesc;
3415 if (delayMs != 0) {
3416 usleep(delayMs * 1000);
3417 }
3418 }
3419
3420 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3421 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3422
3423 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003424}
3425
Glenn Kasten559d4392016-03-29 13:42:57 -07003426status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003427{
Eric Laurentd60560a2015-04-10 11:31:20 -07003428 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3429 ALOGV("%s handle %d", __FUNCTION__, handle);
3430 if (sourceDesc == 0) {
3431 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3432 return BAD_VALUE;
3433 }
3434 status_t status = disconnectAudioSource(sourceDesc);
3435
3436 mAudioSources.removeItem(handle);
3437 return status;
3438}
3439
Andy Hung2ddee192015-12-18 17:34:44 -08003440status_t AudioPolicyManager::setMasterMono(bool mono)
3441{
3442 if (mMasterMono == mono) {
3443 return NO_ERROR;
3444 }
3445 mMasterMono = mono;
3446 // if enabling mono we close all offloaded devices, which will invalidate the
3447 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3448 // for recreating the new AudioTrack as non-offloaded PCM.
3449 //
3450 // If disabling mono, we leave all tracks as is: we don't know which clients
3451 // and tracks are able to be recreated as offloaded. The next "song" should
3452 // play back offloaded.
3453 if (mMasterMono) {
3454 Vector<audio_io_handle_t> offloaded;
3455 for (size_t i = 0; i < mOutputs.size(); ++i) {
3456 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3457 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3458 offloaded.push(desc->mIoHandle);
3459 }
3460 }
3461 for (size_t i = 0; i < offloaded.size(); ++i) {
3462 closeOutput(offloaded[i]);
3463 }
3464 }
3465 // update master mono for all remaining outputs
3466 for (size_t i = 0; i < mOutputs.size(); ++i) {
3467 updateMono(mOutputs.keyAt(i));
3468 }
3469 return NO_ERROR;
3470}
3471
3472status_t AudioPolicyManager::getMasterMono(bool *mono)
3473{
3474 *mono = mMasterMono;
3475 return NO_ERROR;
3476}
3477
Eric Laurentac9cef52017-06-09 15:46:26 -07003478float AudioPolicyManager::getStreamVolumeDB(
3479 audio_stream_type_t stream, int index, audio_devices_t device)
3480{
3481 return computeVolume(stream, index, device);
3482}
3483
Eric Laurentd60560a2015-04-10 11:31:20 -07003484status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3485{
3486 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3487
3488 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3489 if (patchDesc == 0) {
3490 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3491 sourceDesc->mPatchDesc->mHandle);
3492 return BAD_VALUE;
3493 }
3494 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3495
Eric Laurent28d09f02016-03-08 10:43:05 -08003496 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003497 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3498 if (swOutputDesc != 0) {
3499 stopSource(swOutputDesc, stream, false);
3500 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3501 } else {
3502 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3503 if (hwOutputDesc != 0) {
3504 // release patch between src device and output device
3505 // close Hwoutput and remove from mHwOutputs
3506 } else {
3507 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3508 }
3509 }
3510 return NO_ERROR;
3511}
3512
3513sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3514 audio_io_handle_t output, routing_strategy strategy)
3515{
3516 sp<AudioSourceDescriptor> source;
3517 for (size_t i = 0; i < mAudioSources.size(); i++) {
3518 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3519 routing_strategy sourceStrategy =
3520 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3521 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3522 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3523 source = sourceDesc;
3524 break;
3525 }
3526 }
3527 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003528}
3529
Eric Laurente552edb2014-03-10 17:42:56 -07003530// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003531// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003532// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003533uint32_t AudioPolicyManager::nextAudioPortGeneration()
3534{
3535 return android_atomic_inc(&mAudioPortGeneration);
3536}
3537
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003538#ifdef USE_XML_AUDIO_POLICY_CONF
3539// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3540static const char *kConfigLocationList[] =
3541 {"/odm/etc", "/vendor/etc", "/system/etc"};
3542static const int kConfigLocationListSize =
3543 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3544
3545static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3546 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3547 status_t ret;
3548
3549 for (int i = 0; i < kConfigLocationListSize; i++) {
3550 PolicySerializer serializer;
3551 snprintf(audioPolicyXmlConfigFile,
3552 sizeof(audioPolicyXmlConfigFile),
3553 "%s/%s",
3554 kConfigLocationList[i],
3555 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3556 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3557 if (ret == NO_ERROR) {
3558 break;
3559 }
3560 }
3561 return ret;
3562}
3563#endif
3564
Eric Laurente0720872014-03-11 09:30:41 -07003565AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003566 :
3567#ifdef AUDIO_POLICY_TEST
3568 Thread(false),
3569#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003570 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003571 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003572 mAudioPortGeneration(1),
3573 mBeaconMuteRefCount(0),
3574 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003575 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003576 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07003577 mMasterMono(false),
Chris Thornton2b864642017-06-27 21:26:07 -07003578 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE),
3579 mHasComputedSoundTriggerSupportsConcurrentCapture(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003580{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003581 mUidCached = getuid();
3582 mpClientInterface = clientInterface;
3583
3584 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3585 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3586 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3587 bool speakerDrcEnabled = false;
3588
3589#ifdef USE_XML_AUDIO_POLICY_CONF
3590 mVolumeCurves = new VolumeCurvesCollection();
3591 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3592 mDefaultOutputDevice, speakerDrcEnabled,
3593 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003594 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003595#else
3596 mVolumeCurves = new StreamDescriptorCollection();
3597 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3598 mDefaultOutputDevice, speakerDrcEnabled);
3599 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3600 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3601#endif
3602 ALOGE("could not load audio policy configuration file, setting defaults");
3603 config.setDefault();
3604 }
3605 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3606 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3607
3608 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003609 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3610 if (!engineInstance) {
3611 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3612 return;
3613 }
3614 // Retrieve the Policy Manager Interface
3615 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3616 if (mEngine == NULL) {
3617 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3618 return;
3619 }
3620 mEngine->setObserver(this);
3621 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003622 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003623 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3624
Eric Laurent3a4311c2014-03-17 12:00:47 -07003625 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003626 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003627 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3628 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003629 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003630 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003631 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003632 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003633 continue;
3634 }
3635 // open all output streams needed to access attached devices
3636 // except for direct output streams that are only opened when they are actually
3637 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003638 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003639 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3640 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003641 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003642
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003643 if (!outProfile->hasSupportedDevices()) {
3644 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003645 continue;
3646 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003647 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003648 mTtsOutputAvailable = true;
3649 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003650
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003651 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003652 continue;
3653 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003654 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003655 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3656 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003657 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003658 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003659 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003660 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003661 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003662 if ((profileType & outputDeviceTypes) == 0) {
3663 continue;
3664 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003665 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3666 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003667 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3668 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3669 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3670 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003671
3672 outputDesc->mDevice = profileType;
3673 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3674 config.sample_rate = outputDesc->mSamplingRate;
3675 config.channel_mask = outputDesc->mChannelMask;
3676 config.format = outputDesc->mFormat;
3677 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003678 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003679 &output,
3680 &config,
3681 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003682 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003683 &outputDesc->mLatency,
3684 outputDesc->mFlags);
3685
3686 if (status != NO_ERROR) {
3687 ALOGW("Cannot open output stream for device %08x on hw module %s",
3688 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003689 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003690 } else {
3691 outputDesc->mSamplingRate = config.sample_rate;
3692 outputDesc->mChannelMask = config.channel_mask;
3693 outputDesc->mFormat = config.format;
3694
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003695 for (size_t k = 0; k < supportedDevices.size(); k++) {
3696 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003697 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003698 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3699 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003700 }
3701 }
3702 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003703 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003704 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003705 }
3706 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003707 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003708 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003709 true,
3710 0,
3711 NULL,
3712 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003713 }
Eric Laurente552edb2014-03-10 17:42:56 -07003714 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003715 // open input streams needed to access attached devices to validate
3716 // mAvailableInputDevices list
3717 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3718 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003719 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003720
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003721 if (!inProfile->hasSupportedDevices()) {
3722 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003723 continue;
3724 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003725 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003726 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003727 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3728
Eric Laurentd78f1532014-09-16 16:38:20 -07003729 if ((profileType & inputDeviceTypes) == 0) {
3730 continue;
3731 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003732 sp<AudioInputDescriptor> inputDesc =
3733 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003734
Eric Laurentd78f1532014-09-16 16:38:20 -07003735 inputDesc->mDevice = profileType;
3736
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003737 // find the address
3738 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3739 // the inputs vector must be of size 1, but we don't want to crash here
3740 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3741 : String8("");
3742 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3743 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3744
Eric Laurentd78f1532014-09-16 16:38:20 -07003745 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3746 config.sample_rate = inputDesc->mSamplingRate;
3747 config.channel_mask = inputDesc->mChannelMask;
3748 config.format = inputDesc->mFormat;
3749 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003750 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003751 &input,
3752 &config,
3753 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003754 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003755 AUDIO_SOURCE_MIC,
3756 AUDIO_INPUT_FLAG_NONE);
3757
3758 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003759 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3760 for (size_t k = 0; k < supportedDevices.size(); k++) {
3761 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003762 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003763 if (index >= 0) {
3764 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3765 if (!devDesc->isAttached()) {
3766 devDesc->attach(mHwModules[i]);
Eric Laurent83efe1c2017-07-09 16:51:08 -07003767 devDesc->importAudioPort(inProfile, true);
Eric Laurent45aabc32015-08-06 09:11:13 -07003768 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003769 }
3770 }
3771 mpClientInterface->closeInput(input);
3772 } else {
3773 ALOGW("Cannot open input stream for device %08x on hw module %s",
3774 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003775 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003776 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003777 }
3778 }
3779 // make sure all attached devices have been allocated a unique ID
3780 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003781 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003782 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003783 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3784 continue;
3785 }
François Gaffie2110e042015-03-24 08:41:51 +01003786 // The device is now validated and can be appended to the available devices of the engine
3787 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3788 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003789 i++;
3790 }
3791 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003792 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003793 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003794 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3795 continue;
3796 }
François Gaffie2110e042015-03-24 08:41:51 +01003797 // The device is now validated and can be appended to the available devices of the engine
3798 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3799 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003800 i++;
3801 }
3802 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003803 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003804 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003805 }
Eric Laurente552edb2014-03-10 17:42:56 -07003806
3807 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3808
3809 updateDevicesAndOutputs();
3810
3811#ifdef AUDIO_POLICY_TEST
3812 if (mPrimaryOutput != 0) {
3813 AudioParameter outputCmd = AudioParameter();
3814 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003815 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003816
3817 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3818 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003819 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3820 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003821 mTestLatencyMs = 0;
3822 mCurOutput = 0;
3823 mDirectOutput = false;
3824 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3825 mTestOutputs[i] = 0;
3826 }
3827
3828 const size_t SIZE = 256;
3829 char buffer[SIZE];
3830 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3831 run(buffer, ANDROID_PRIORITY_AUDIO);
3832 }
3833#endif //AUDIO_POLICY_TEST
3834}
3835
Eric Laurente0720872014-03-11 09:30:41 -07003836AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003837{
3838#ifdef AUDIO_POLICY_TEST
3839 exit();
3840#endif //AUDIO_POLICY_TEST
3841 for (size_t i = 0; i < mOutputs.size(); i++) {
3842 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003843 }
3844 for (size_t i = 0; i < mInputs.size(); i++) {
3845 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003846 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003847 mAvailableOutputDevices.clear();
3848 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003849 mOutputs.clear();
3850 mInputs.clear();
3851 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003852}
3853
Eric Laurente0720872014-03-11 09:30:41 -07003854status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003855{
Eric Laurent87ffa392015-05-22 10:32:38 -07003856 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003857}
3858
3859#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003860bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003861{
3862 ALOGV("entering threadLoop()");
3863 while (!exitPending())
3864 {
3865 String8 command;
3866 int valueInt;
3867 String8 value;
3868
3869 Mutex::Autolock _l(mLock);
3870 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3871
3872 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3873 AudioParameter param = AudioParameter(command);
3874
3875 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3876 valueInt != 0) {
3877 ALOGV("Test command %s received", command.string());
3878 String8 target;
3879 if (param.get(String8("target"), target) != NO_ERROR) {
3880 target = "Manager";
3881 }
3882 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3883 param.remove(String8("test_cmd_policy_output"));
3884 mCurOutput = valueInt;
3885 }
3886 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3887 param.remove(String8("test_cmd_policy_direct"));
3888 if (value == "false") {
3889 mDirectOutput = false;
3890 } else if (value == "true") {
3891 mDirectOutput = true;
3892 }
3893 }
3894 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3895 param.remove(String8("test_cmd_policy_input"));
3896 mTestInput = valueInt;
3897 }
3898
3899 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3900 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003901 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003902 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003903 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003904 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003905 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003906 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003907 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003908 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003909 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003910 if (target == "Manager") {
3911 mTestFormat = format;
3912 } else if (mTestOutputs[mCurOutput] != 0) {
3913 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003914 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003915 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3916 }
3917 }
3918 }
3919 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3920 param.remove(String8("test_cmd_policy_channels"));
3921 int channels = 0;
3922
3923 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003924 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003925 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003926 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003927 }
3928 if (channels != 0) {
3929 if (target == "Manager") {
3930 mTestChannels = channels;
3931 } else if (mTestOutputs[mCurOutput] != 0) {
3932 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003933 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003934 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3935 }
3936 }
3937 }
3938 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3939 param.remove(String8("test_cmd_policy_sampleRate"));
3940 if (valueInt >= 0 && valueInt <= 96000) {
3941 int samplingRate = valueInt;
3942 if (target == "Manager") {
3943 mTestSamplingRate = samplingRate;
3944 } else if (mTestOutputs[mCurOutput] != 0) {
3945 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003946 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003947 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3948 }
3949 }
3950 }
3951
3952 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3953 param.remove(String8("test_cmd_policy_reopen"));
3954
Eric Laurentc75307b2015-03-17 15:29:32 -07003955 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003956
Eric Laurentc75307b2015-03-17 15:29:32 -07003957 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003958
Eric Laurentc75307b2015-03-17 15:29:32 -07003959 removeOutput(mPrimaryOutput->mIoHandle);
3960 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3961 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003962 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003963 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3964 config.sample_rate = outputDesc->mSamplingRate;
3965 config.channel_mask = outputDesc->mChannelMask;
3966 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003967 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003968 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003969 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003970 &config,
3971 &outputDesc->mDevice,
3972 String8(""),
3973 &outputDesc->mLatency,
3974 outputDesc->mFlags);
3975 if (status != NO_ERROR) {
3976 ALOGE("Failed to reopen hardware output stream, "
3977 "samplingRate: %d, format %d, channels %d",
3978 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003979 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003980 outputDesc->mSamplingRate = config.sample_rate;
3981 outputDesc->mChannelMask = config.channel_mask;
3982 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003983 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003984 AudioParameter outputCmd = AudioParameter();
3985 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003986 mpClientInterface->setParameters(handle, outputCmd.toString());
3987 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003988 }
3989 }
3990
3991
3992 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3993 }
3994 }
3995 return false;
3996}
3997
Eric Laurente0720872014-03-11 09:30:41 -07003998void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003999{
4000 {
4001 AutoMutex _l(mLock);
4002 requestExit();
4003 mWaitWorkCV.signal();
4004 }
4005 requestExitAndWait();
4006}
4007
Eric Laurente0720872014-03-11 09:30:41 -07004008int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004009{
4010 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
4011 if (output == mTestOutputs[i]) return i;
4012 }
4013 return 0;
4014}
4015#endif //AUDIO_POLICY_TEST
4016
4017// ---
4018
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004019void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004020{
François Gaffie98cc1912015-03-18 17:52:40 +01004021 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07004022 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08004023 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07004024 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07004026}
4027
François Gaffie53615e22015-03-19 09:24:12 +01004028void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4029{
4030 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07004031 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01004032}
4033
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004034void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07004035{
François Gaffie98cc1912015-03-18 17:52:40 +01004036 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004037 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07004038 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07004039}
Eric Laurente552edb2014-03-10 17:42:56 -07004040
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004041void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08004042 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004043 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004044 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08004045 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004046 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08004047 if (devDesc != 0) {
4048 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
4049 desc->mIoHandle, address.string());
4050 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004051 }
4052}
4053
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004054status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004055 audio_policy_dev_state_t state,
4056 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004057 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07004058{
François Gaffie53615e22015-03-19 09:24:12 +01004059 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07004060 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004061
4062 if (audio_device_is_digital(device)) {
4063 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004064 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004065 }
Eric Laurente552edb2014-03-10 17:42:56 -07004066
Eric Laurent3b73df72014-03-11 09:06:29 -07004067 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004068 // first list already open outputs that can be routed to this device
4069 for (size_t i = 0; i < mOutputs.size(); i++) {
4070 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07004071 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004072 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004073 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
4074 outputs.add(mOutputs.keyAt(i));
4075 } else {
4076 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08004077 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004078 }
Eric Laurente552edb2014-03-10 17:42:56 -07004079 }
4080 }
4081 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004082 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07004083 for (size_t i = 0; i < mHwModules.size(); i++)
4084 {
4085 if (mHwModules[i]->mHandle == 0) {
4086 continue;
4087 }
4088 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4089 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004090 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004091 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004092 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004093 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004094 profiles.add(profile);
4095 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
4096 }
Eric Laurente552edb2014-03-10 17:42:56 -07004097 }
4098 }
4099 }
4100
Eric Laurent7b279bb2015-12-14 10:18:23 -08004101 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004102
Eric Laurente552edb2014-03-10 17:42:56 -07004103 if (profiles.isEmpty() && outputs.isEmpty()) {
4104 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4105 return BAD_VALUE;
4106 }
4107
4108 // open outputs for matching profiles if needed. Direct outputs are also opened to
4109 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4110 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004111 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07004112
4113 // nothing to do if one output is already opened for this profile
4114 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004115 for (j = 0; j < outputs.size(); j++) {
4116 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07004117 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004118 // matching profile: save the sample rates, format and channel masks supported
4119 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07004120 if (audio_device_is_digital(device)) {
4121 devDesc->importAudioPort(profile);
4122 }
Eric Laurente552edb2014-03-10 17:42:56 -07004123 break;
4124 }
4125 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004126 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07004127 continue;
4128 }
4129
Eric Laurent83efe1c2017-07-09 16:51:08 -07004130 ALOGV("opening output for device %08x with params %s profile %p name %s",
4131 device, address.string(), profile.get(), profile->getName().string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004132 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07004133 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004134 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4135 config.sample_rate = desc->mSamplingRate;
4136 config.channel_mask = desc->mChannelMask;
4137 config.format = desc->mFormat;
4138 config.offload_info.sample_rate = desc->mSamplingRate;
4139 config.offload_info.channel_mask = desc->mChannelMask;
4140 config.offload_info.format = desc->mFormat;
4141 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004142 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004143 &output,
4144 &config,
4145 &desc->mDevice,
4146 address,
4147 &desc->mLatency,
4148 desc->mFlags);
4149 if (status == NO_ERROR) {
4150 desc->mSamplingRate = config.sample_rate;
4151 desc->mChannelMask = config.channel_mask;
4152 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07004153
Eric Laurentd4692962014-05-05 18:13:44 -07004154 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07004155 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004156 char *param = audio_device_address_to_parameter(device, address);
4157 mpClientInterface->setParameters(output, String8(param));
4158 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07004159 }
Phil Burk00eeb322016-03-31 12:41:00 -07004160 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004161 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004162 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07004163 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004164 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004165 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004166 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08004167 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01004168 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004169 config.offload_info.sample_rate = config.sample_rate;
4170 config.offload_info.channel_mask = config.channel_mask;
4171 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07004172 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004173 &output,
4174 &config,
4175 &desc->mDevice,
4176 address,
4177 &desc->mLatency,
4178 desc->mFlags);
4179 if (status == NO_ERROR) {
4180 desc->mSamplingRate = config.sample_rate;
4181 desc->mChannelMask = config.channel_mask;
4182 desc->mFormat = config.format;
4183 } else {
4184 output = AUDIO_IO_HANDLE_NONE;
4185 }
Eric Laurentd4692962014-05-05 18:13:44 -07004186 }
4187
Eric Laurentcf2c0212014-07-25 16:20:43 -07004188 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004189 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01004190 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01004191 sp<AudioPolicyMix> policyMix;
4192 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004193 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
4194 address.string());
4195 }
François Gaffie036e1e92015-03-19 10:16:24 +01004196 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07004197 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01004198
Eric Laurent87ffa392015-05-22 10:32:38 -07004199 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4200 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08004201 // no duplicated output for direct outputs and
4202 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07004203 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004204
Eric Laurentd4692962014-05-05 18:13:44 -07004205 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07004206 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07004207
Eric Laurentd4692962014-05-05 18:13:44 -07004208 //TODO: configure audio effect output stage here
4209
4210 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004211 duplicatedOutput =
4212 mpClientInterface->openDuplicateOutput(output,
4213 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004214 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004215 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004216 sp<SwAudioOutputDescriptor> dupOutputDesc =
4217 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4218 dupOutputDesc->mOutput1 = mPrimaryOutput;
4219 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004220 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4221 dupOutputDesc->mFormat = desc->mFormat;
4222 dupOutputDesc->mChannelMask = desc->mChannelMask;
4223 dupOutputDesc->mLatency = desc->mLatency;
4224 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004225 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004226 } else {
4227 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004228 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004229 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004230 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004231 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004232 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004233 }
Eric Laurente552edb2014-03-10 17:42:56 -07004234 }
4235 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004236 } else {
4237 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004238 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004239 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004240 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004241 profiles.removeAt(profile_index);
4242 profile_index--;
4243 } else {
4244 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004245 // Load digital format info only for digital devices
4246 if (audio_device_is_digital(device)) {
4247 devDesc->importAudioPort(profile);
4248 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004249
François Gaffie53615e22015-03-19 09:24:12 +01004250 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004251 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4252 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004253 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004254 NULL/*patch handle*/, address.string());
4255 }
Eric Laurente552edb2014-03-10 17:42:56 -07004256 ALOGV("checkOutputsForDevice(): adding output %d", output);
4257 }
4258 }
4259
4260 if (profiles.isEmpty()) {
4261 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4262 return BAD_VALUE;
4263 }
Eric Laurentd4692962014-05-05 18:13:44 -07004264 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004265 // check if one opened output is not needed any more after disconnecting one device
4266 for (size_t i = 0; i < mOutputs.size(); i++) {
4267 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004268 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004269 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004270 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004271 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004272 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004273 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004274 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4275 mOutputs.keyAt(i));
4276 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004277 }
Eric Laurente552edb2014-03-10 17:42:56 -07004278 }
4279 }
Eric Laurentd4692962014-05-05 18:13:44 -07004280 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004281 for (size_t i = 0; i < mHwModules.size(); i++)
4282 {
4283 if (mHwModules[i]->mHandle == 0) {
4284 continue;
4285 }
4286 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4287 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004288 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004289 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004290 ALOGV("checkOutputsForDevice(): "
4291 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004292 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
4294 }
4295 }
4296 }
4297 return NO_ERROR;
4298}
4299
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004300status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004301 audio_policy_dev_state_t state,
4302 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004303 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004304{
Paul McLean9080a4c2015-06-18 08:24:02 -07004305 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004306 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004307
4308 if (audio_device_is_digital(device)) {
4309 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004310 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004311 }
4312
Eric Laurentd4692962014-05-05 18:13:44 -07004313 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4314 // first list already open inputs that can be routed to this device
4315 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4316 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004317 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004318 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4319 inputs.add(mInputs.keyAt(input_index));
4320 }
4321 }
4322
4323 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004324 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004325 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4326 {
4327 if (mHwModules[module_idx]->mHandle == 0) {
4328 continue;
4329 }
4330 for (size_t profile_index = 0;
4331 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4332 profile_index++)
4333 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004334 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4335
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004336 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004337 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004338 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004339 profiles.add(profile);
4340 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4341 profile_index, module_idx);
4342 }
Eric Laurentd4692962014-05-05 18:13:44 -07004343 }
4344 }
4345 }
4346
4347 if (profiles.isEmpty() && inputs.isEmpty()) {
4348 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4349 return BAD_VALUE;
4350 }
4351
4352 // open inputs for matching profiles if needed. Direct inputs are also opened to
4353 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4354 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4355
Eric Laurent1c333e22014-05-20 10:48:17 -07004356 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004357 // nothing to do if one input is already opened for this profile
4358 size_t input_index;
4359 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4360 desc = mInputs.valueAt(input_index);
4361 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004362 if (audio_device_is_digital(device)) {
4363 devDesc->importAudioPort(profile);
4364 }
Eric Laurentd4692962014-05-05 18:13:44 -07004365 break;
4366 }
4367 }
4368 if (input_index != mInputs.size()) {
4369 continue;
4370 }
4371
4372 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4373 desc = new AudioInputDescriptor(profile);
4374 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004375 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4376 config.sample_rate = desc->mSamplingRate;
4377 config.channel_mask = desc->mChannelMask;
4378 config.format = desc->mFormat;
4379 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent83efe1c2017-07-09 16:51:08 -07004380
4381 ALOGV("opening inputput for device %08x with params %s profile %p name %s",
4382 desc->mDevice, address.string(), profile.get(), profile->getName().string());
4383
Eric Laurent322b4d22015-04-03 15:57:54 -07004384 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004385 &input,
4386 &config,
4387 &desc->mDevice,
4388 address,
4389 AUDIO_SOURCE_MIC,
4390 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004391
Eric Laurentcf2c0212014-07-25 16:20:43 -07004392 if (status == NO_ERROR) {
4393 desc->mSamplingRate = config.sample_rate;
4394 desc->mChannelMask = config.channel_mask;
4395 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004396
Eric Laurentd4692962014-05-05 18:13:44 -07004397 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004398 char *param = audio_device_address_to_parameter(device, address);
4399 mpClientInterface->setParameters(input, String8(param));
4400 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004401 }
Phil Burk00eeb322016-03-31 12:41:00 -07004402 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004403 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004404 ALOGW("checkInputsForDevice() direct input missing param");
4405 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004406 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004407 }
4408
4409 if (input != 0) {
4410 addInput(input, desc);
4411 }
4412 } // endif input != 0
4413
Eric Laurentcf2c0212014-07-25 16:20:43 -07004414 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004415 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004416 profiles.removeAt(profile_index);
4417 profile_index--;
4418 } else {
4419 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004420 if (audio_device_is_digital(device)) {
4421 devDesc->importAudioPort(profile);
4422 }
Eric Laurentd4692962014-05-05 18:13:44 -07004423 ALOGV("checkInputsForDevice(): adding input %d", input);
4424 }
4425 } // end scan profiles
4426
4427 if (profiles.isEmpty()) {
4428 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4429 return BAD_VALUE;
4430 }
4431 } else {
4432 // Disconnect
4433 // check if one opened input is not needed any more after disconnecting one device
4434 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4435 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004436 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004437 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4438 mInputs.keyAt(input_index));
4439 inputs.add(mInputs.keyAt(input_index));
4440 }
4441 }
4442 // Clear any profiles associated with the disconnected device.
4443 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4444 if (mHwModules[module_index]->mHandle == 0) {
4445 continue;
4446 }
4447 for (size_t profile_index = 0;
4448 profile_index < mHwModules[module_index]->mInputProfiles.size();
4449 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004450 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004451 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004452 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004453 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004454 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004455 }
4456 }
4457 }
4458 } // end disconnect
4459
4460 return NO_ERROR;
4461}
4462
4463
Eric Laurente0720872014-03-11 09:30:41 -07004464void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004465{
4466 ALOGV("closeOutput(%d)", output);
4467
Eric Laurentc75307b2015-03-17 15:29:32 -07004468 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004469 if (outputDesc == NULL) {
4470 ALOGW("closeOutput() unknown output %d", output);
4471 return;
4472 }
François Gaffie036e1e92015-03-19 10:16:24 +01004473 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004474
Eric Laurente552edb2014-03-10 17:42:56 -07004475 // look for duplicated outputs connected to the output being removed.
4476 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004477 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004478 if (dupOutputDesc->isDuplicated() &&
4479 (dupOutputDesc->mOutput1 == outputDesc ||
4480 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004481 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004482 if (dupOutputDesc->mOutput1 == outputDesc) {
4483 outputDesc2 = dupOutputDesc->mOutput2;
4484 } else {
4485 outputDesc2 = dupOutputDesc->mOutput1;
4486 }
4487 // As all active tracks on duplicated output will be deleted,
4488 // and as they were also referenced on the other output, the reference
4489 // count for their stream type must be adjusted accordingly on
4490 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004491 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004492 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004493 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004494 }
4495 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4496 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4497
4498 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004499 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004500 }
4501 }
4502
Eric Laurent05b90f82014-08-27 15:32:29 -07004503 nextAudioPortGeneration();
4504
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004505 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004506 if (index >= 0) {
4507 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004508 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004509 mAudioPatches.removeItemsAt(index);
4510 mpClientInterface->onAudioPatchListUpdate();
4511 }
4512
Eric Laurente552edb2014-03-10 17:42:56 -07004513 AudioParameter param;
4514 param.add(String8("closing"), String8("true"));
4515 mpClientInterface->setParameters(output, param.toString());
4516
4517 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004518 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004519 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004520}
4521
4522void AudioPolicyManager::closeInput(audio_io_handle_t input)
4523{
4524 ALOGV("closeInput(%d)", input);
4525
4526 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4527 if (inputDesc == NULL) {
4528 ALOGW("closeInput() unknown input %d", input);
4529 return;
4530 }
4531
Eric Laurent6a94d692014-05-20 11:18:06 -07004532 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004533
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004534 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004535 if (index >= 0) {
4536 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004537 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004538 mAudioPatches.removeItemsAt(index);
4539 mpClientInterface->onAudioPatchListUpdate();
4540 }
4541
4542 mpClientInterface->closeInput(input);
4543 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004544}
4545
Eric Laurentc75307b2015-03-17 15:29:32 -07004546SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4547 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004548 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004549{
4550 SortedVector<audio_io_handle_t> outputs;
4551
4552 ALOGVV("getOutputsForDevice() device %04x", device);
4553 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004554 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004555 i, openOutputs.valueAt(i)->isDuplicated(),
4556 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004557 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4558 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4559 outputs.add(openOutputs.keyAt(i));
4560 }
4561 }
4562 return outputs;
4563}
4564
Eric Laurente0720872014-03-11 09:30:41 -07004565bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004566 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004567{
4568 if (outputs1.size() != outputs2.size()) {
4569 return false;
4570 }
4571 for (size_t i = 0; i < outputs1.size(); i++) {
4572 if (outputs1[i] != outputs2[i]) {
4573 return false;
4574 }
4575 }
4576 return true;
4577}
4578
Eric Laurente0720872014-03-11 09:30:41 -07004579void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004580{
4581 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4582 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4583 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4584 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4585
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004586 // also take into account external policy-related changes: add all outputs which are
4587 // associated with policies in the "before" and "after" output vectors
4588 ALOGVV("checkOutputForStrategy(): policy related outputs");
4589 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004590 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004591 if (desc != 0 && desc->mPolicyMix != NULL) {
4592 srcOutputs.add(desc->mIoHandle);
4593 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4594 }
4595 }
4596 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004597 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004598 if (desc != 0 && desc->mPolicyMix != NULL) {
4599 dstOutputs.add(desc->mIoHandle);
4600 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4601 }
4602 }
4603
Eric Laurente552edb2014-03-10 17:42:56 -07004604 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4605 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4606 strategy, srcOutputs[0], dstOutputs[0]);
4607 // mute strategy while moving tracks from one output to another
4608 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004609 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004610 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004611 setStrategyMute(strategy, true, desc);
4612 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004613 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004614 sp<AudioSourceDescriptor> source =
4615 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4616 if (source != 0){
4617 connectAudioSource(source);
4618 }
Eric Laurente552edb2014-03-10 17:42:56 -07004619 }
4620
4621 // Move effects associated to this strategy from previous output to new output
4622 if (strategy == STRATEGY_MEDIA) {
Eric Laurent36829f92017-04-07 19:04:42 -07004623 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07004624 }
4625 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004626 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004627 if (getStrategy((audio_stream_type_t)i) == strategy) {
4628 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004629 }
4630 }
4631 }
4632}
4633
Eric Laurente0720872014-03-11 09:30:41 -07004634void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004635{
François Gaffie2110e042015-03-24 08:41:51 +01004636 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004637 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004638 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004639 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004640 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004641 checkOutputForStrategy(STRATEGY_SONIFICATION);
4642 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004643 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004644 checkOutputForStrategy(STRATEGY_MEDIA);
4645 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004646 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004647}
4648
Eric Laurente0720872014-03-11 09:30:41 -07004649void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004650{
François Gaffie53615e22015-03-19 09:24:12 +01004651 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004652 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004654 return;
4655 }
4656
Eric Laurent3a4311c2014-03-17 12:00:47 -07004657 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004658 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4659 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4660 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004661
4662 // if suspended, restore A2DP output if:
4663 // ((SCO device is NOT connected) ||
4664 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4665 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004666 //
Eric Laurentf732e072016-08-03 19:30:28 -07004667 // if not suspended, suspend A2DP output if:
4668 // (SCO device is connected) &&
4669 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4670 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004671 //
4672 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004673 if (!isScoConnected ||
4674 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4675 AUDIO_POLICY_FORCE_BT_SCO) &&
4676 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4677 AUDIO_POLICY_FORCE_BT_SCO) &&
4678 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004679 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004680
4681 mpClientInterface->restoreOutput(a2dpOutput);
4682 mA2dpSuspended = false;
4683 }
4684 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004685 if (isScoConnected &&
4686 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4687 AUDIO_POLICY_FORCE_BT_SCO) ||
4688 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4689 AUDIO_POLICY_FORCE_BT_SCO) ||
4690 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004691 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004692
4693 mpClientInterface->suspendOutput(a2dpOutput);
4694 mA2dpSuspended = true;
4695 }
4696 }
4697}
4698
Eric Laurentc75307b2015-03-17 15:29:32 -07004699audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4700 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004701{
4702 audio_devices_t device = AUDIO_DEVICE_NONE;
4703
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004704 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004705 if (index >= 0) {
4706 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4707 if (patchDesc->mUid != mUidCached) {
4708 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004709 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 return outputDesc->device();
4711 }
4712 }
4713
Eric Laurente552edb2014-03-10 17:42:56 -07004714 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004715 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004716 // use device for strategy enforced audible
4717 // 2: we are in call or the strategy phone is active on the output:
4718 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004719 // 3: the strategy for enforced audible is active but not enforced on the output:
4720 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004721 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004722 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004723 // 5: the strategy accessibility is active on the output:
4724 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004725 // 6: the strategy "respectful" sonification is active on the output:
4726 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004727 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004728 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004729 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004730 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004731 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004732 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004733 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004734 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004735 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4736 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004737 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004738 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004739 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004740 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004741 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004742 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004743 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4744 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004745 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004746 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004747 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004748 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004749 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004750 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004751 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004752 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004753 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004754 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004755 }
4756
Eric Laurent1c333e22014-05-20 10:48:17 -07004757 ALOGV("getNewOutputDevice() selected device %x", device);
4758 return device;
4759}
4760
Eric Laurentfb66dd92016-01-28 18:32:03 -08004761audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004762{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004763 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004764
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004765 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 if (index >= 0) {
4767 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4768 if (patchDesc->mUid != mUidCached) {
4769 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004770 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004771 return inputDesc->mDevice;
4772 }
4773 }
4774
Eric Laurentfb66dd92016-01-28 18:32:03 -08004775 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4776 if (isInCall()) {
4777 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4778 } else if (source != AUDIO_SOURCE_DEFAULT) {
4779 device = getDeviceAndMixForInputSource(source);
4780 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004781
Eric Laurente552edb2014-03-10 17:42:56 -07004782 return device;
4783}
4784
Eric Laurent794fde22016-03-11 09:50:45 -08004785bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4786 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004787 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004788}
4789
Eric Laurente0720872014-03-11 09:30:41 -07004790uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004791 return (uint32_t)getStrategy(stream);
4792}
4793
Eric Laurente0720872014-03-11 09:30:41 -07004794audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004795 // By checking the range of stream before calling getStrategy, we avoid
4796 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4797 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004798 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 return AUDIO_DEVICE_NONE;
4800 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004801 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004802 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4803 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004804 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 }
Eric Laurent794fde22016-03-11 09:50:45 -08004806 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004807 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004808 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004809 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4810 for (size_t i = 0; i < outputs.size(); i++) {
4811 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004812 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004813 curDevices |= outputDesc->device();
4814 }
4815 }
4816 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004817 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004818
4819 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4820 and doesn't really need to.*/
4821 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4822 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4823 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4824 }
Eric Laurente552edb2014-03-10 17:42:56 -07004825 return devices;
4826}
4827
François Gaffie2110e042015-03-24 08:41:51 +01004828routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4829{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004830 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004831 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004832}
4833
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004834uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4835 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004836 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4837 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4838 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004839 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4840 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4841 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004842 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004843 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004844}
4845
Eric Laurente0720872014-03-11 09:30:41 -07004846void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004847 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004848 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004849 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4850 updateDevicesAndOutputs();
4851 break;
4852 default:
4853 break;
4854 }
4855}
4856
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004857uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004858
4859 // skip beacon mute management if a dedicated TTS output is available
4860 if (mTtsOutputAvailable) {
4861 return 0;
4862 }
4863
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004864 switch(event) {
4865 case STARTING_OUTPUT:
4866 mBeaconMuteRefCount++;
4867 break;
4868 case STOPPING_OUTPUT:
4869 if (mBeaconMuteRefCount > 0) {
4870 mBeaconMuteRefCount--;
4871 }
4872 break;
4873 case STARTING_BEACON:
4874 mBeaconPlayingRefCount++;
4875 break;
4876 case STOPPING_BEACON:
4877 if (mBeaconPlayingRefCount > 0) {
4878 mBeaconPlayingRefCount--;
4879 }
4880 break;
4881 }
4882
4883 if (mBeaconMuteRefCount > 0) {
4884 // any playback causes beacon to be muted
4885 return setBeaconMute(true);
4886 } else {
4887 // no other playback: unmute when beacon starts playing, mute when it stops
4888 return setBeaconMute(mBeaconPlayingRefCount == 0);
4889 }
4890}
4891
4892uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4893 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4894 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4895 // keep track of muted state to avoid repeating mute/unmute operations
4896 if (mBeaconMuted != mute) {
4897 // mute/unmute AUDIO_STREAM_TTS on all outputs
4898 ALOGV("\t muting %d", mute);
4899 uint32_t maxLatency = 0;
4900 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004901 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004902 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004903 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004904 0 /*delay*/, AUDIO_DEVICE_NONE);
4905 const uint32_t latency = desc->latency() * 2;
4906 if (latency > maxLatency) {
4907 maxLatency = latency;
4908 }
4909 }
4910 mBeaconMuted = mute;
4911 return maxLatency;
4912 }
4913 return 0;
4914}
4915
Eric Laurente0720872014-03-11 09:30:41 -07004916audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004917 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004918{
Paul McLeanaa981192015-03-21 09:55:15 -07004919 // Routing
4920 // see if we have an explicit route
4921 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4922 // (getStrategy(stream)).
4923 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4924 // and activity count is non-zero
4925 // the device = the device from the descriptor in the RouteMap, and exit.
4926 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4927 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004928 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4929 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004930 return route->mDeviceDescriptor->type();
4931 }
4932 }
4933
Eric Laurente552edb2014-03-10 17:42:56 -07004934 if (fromCache) {
4935 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4936 strategy, mDeviceForStrategy[strategy]);
4937 return mDeviceForStrategy[strategy];
4938 }
François Gaffie2110e042015-03-24 08:41:51 +01004939 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004940}
4941
Eric Laurente0720872014-03-11 09:30:41 -07004942void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004943{
4944 for (int i = 0; i < NUM_STRATEGIES; i++) {
4945 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4946 }
4947 mPreviousOutputs = mOutputs;
4948}
4949
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004950uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004951 audio_devices_t prevDevice,
4952 uint32_t delayMs)
4953{
4954 // mute/unmute strategies using an incompatible device combination
4955 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4956 // if unmuting, unmute only after the specified delay
4957 if (outputDesc->isDuplicated()) {
4958 return 0;
4959 }
4960
4961 uint32_t muteWaitMs = 0;
4962 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004963 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004964
4965 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4966 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004967 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004968 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4969 bool doMute = false;
4970
4971 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4972 doMute = true;
4973 outputDesc->mStrategyMutedByDevice[i] = true;
4974 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4975 doMute = true;
4976 outputDesc->mStrategyMutedByDevice[i] = false;
4977 }
Eric Laurent99401132014-05-07 19:48:15 -07004978 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004979 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004980 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004981 // skip output if it does not share any device with current output
4982 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4983 == AUDIO_DEVICE_NONE) {
4984 continue;
4985 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004986 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004987 mute ? "muting" : "unmuting", i, curDevice);
4988 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004989 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004990 if (mute) {
4991 // FIXME: should not need to double latency if volume could be applied
4992 // immediately by the audioflinger mixer. We must account for the delay
4993 // between now and the next time the audioflinger thread for this output
4994 // will process a buffer (which corresponds to one buffer size,
4995 // usually 1/2 or 1/4 of the latency).
4996 if (muteWaitMs < desc->latency() * 2) {
4997 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004998 }
4999 }
5000 }
5001 }
5002 }
5003 }
5004
Eric Laurent99401132014-05-07 19:48:15 -07005005 // temporary mute output if device selection changes to avoid volume bursts due to
5006 // different per device volumes
5007 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005008 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5009 // temporary mute duration is conservatively set to 4 times the reported latency
5010 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5011 if (muteWaitMs < tempMuteWaitMs) {
5012 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07005013 }
Eric Laurentdc462862016-07-19 12:29:53 -07005014
Eric Laurent99401132014-05-07 19:48:15 -07005015 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005016 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07005017 // make sure that we do not start the temporary mute period too early in case of
5018 // delayed device change
5019 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07005020 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07005021 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07005022 }
5023 }
5024 }
5025
Eric Laurente552edb2014-03-10 17:42:56 -07005026 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5027 if (muteWaitMs > delayMs) {
5028 muteWaitMs -= delayMs;
5029 usleep(muteWaitMs * 1000);
5030 return muteWaitMs;
5031 }
5032 return 0;
5033}
5034
Eric Laurentc75307b2015-03-17 15:29:32 -07005035uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005036 audio_devices_t device,
5037 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005039 audio_patch_handle_t *patchHandle,
5040 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07005041{
Eric Laurentc75307b2015-03-17 15:29:32 -07005042 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005043 AudioParameter param;
5044 uint32_t muteWaitMs;
5045
5046 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005047 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
5048 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005049 return muteWaitMs;
5050 }
5051 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5052 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07005053 if ((device != AUDIO_DEVICE_NONE) &&
5054 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005055 return 0;
5056 }
5057
5058 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07005059 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07005060
5061 audio_devices_t prevDevice = outputDesc->mDevice;
5062
Paul McLeanaa981192015-03-21 09:55:15 -07005063 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005064
5065 if (device != AUDIO_DEVICE_NONE) {
5066 outputDesc->mDevice = device;
5067 }
5068 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
5069
5070 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07005071 // the requested device is AUDIO_DEVICE_NONE
5072 // OR the requested device is the same as current device
5073 // AND force is not specified
5074 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07005075 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07005076 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
5077 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005078 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005079 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005080 return muteWaitMs;
5081 }
5082
5083 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07005084
Eric Laurente552edb2014-03-10 17:42:56 -07005085 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07005086 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005087 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07005088 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07005089 DeviceVector deviceList;
5090 if ((address == NULL) || (strlen(address) == 0)) {
5091 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
5092 } else {
5093 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
5094 }
5095
Eric Laurent1c333e22014-05-20 10:48:17 -07005096 if (!deviceList.isEmpty()) {
5097 struct audio_patch patch;
5098 outputDesc->toAudioPortConfig(&patch.sources[0]);
5099 patch.num_sources = 1;
5100 patch.num_sinks = 0;
5101 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
5102 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005103 patch.num_sinks++;
5104 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005105 ssize_t index;
5106 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5107 index = mAudioPatches.indexOfKey(*patchHandle);
5108 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005109 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 }
5111 sp< AudioPatch> patchDesc;
5112 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5113 if (index >= 0) {
5114 patchDesc = mAudioPatches.valueAt(index);
5115 afPatchHandle = patchDesc->mAfPatchHandle;
5116 }
5117
Eric Laurent1c333e22014-05-20 10:48:17 -07005118 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 &afPatchHandle,
5120 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005121 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
5122 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07005124 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005126 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 addAudioPatch(patchDesc->mHandle, patchDesc);
5128 } else {
5129 patchDesc->mPatch = patch;
5130 }
5131 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 if (patchHandle) {
5133 *patchHandle = patchDesc->mHandle;
5134 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005135 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005136 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005137 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005138 }
5139 }
bryant_liuf5e7e792014-08-19 20:07:05 +08005140
5141 // inform all input as well
5142 for (size_t i = 0; i < mInputs.size(); i++) {
5143 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01005144 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08005145 AudioParameter inputCmd = AudioParameter();
5146 ALOGV("%s: inform input %d of device:%d", __func__,
5147 inputDescriptor->mIoHandle, device);
5148 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5149 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5150 inputCmd.toString(),
5151 delayMs);
5152 }
5153 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005154 }
Eric Laurente552edb2014-03-10 17:42:56 -07005155
5156 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07005157 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005158
5159 return muteWaitMs;
5160}
5161
Eric Laurentc75307b2015-03-17 15:29:32 -07005162status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07005163 int delayMs,
5164 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005165{
Eric Laurent6a94d692014-05-20 11:18:06 -07005166 ssize_t index;
5167 if (patchHandle) {
5168 index = mAudioPatches.indexOfKey(*patchHandle);
5169 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08005170 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005171 }
5172 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005173 return INVALID_OPERATION;
5174 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005175 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5176 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005177 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005178 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 removeAudioPatch(patchDesc->mHandle);
5180 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005181 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005182 return status;
5183}
5184
5185status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5186 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 bool force,
5188 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005189{
5190 status_t status = NO_ERROR;
5191
Eric Laurent1f2f2232014-06-02 12:01:23 -07005192 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005193 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5194 inputDesc->mDevice = device;
5195
5196 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5197 if (!deviceList.isEmpty()) {
5198 struct audio_patch patch;
5199 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005200 // AUDIO_SOURCE_HOTWORD is for internal use only:
5201 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005202 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005203 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005204 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5205 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005206 patch.num_sinks = 1;
5207 //only one input device for now
5208 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005209 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 ssize_t index;
5211 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5212 index = mAudioPatches.indexOfKey(*patchHandle);
5213 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005214 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 }
5216 sp< AudioPatch> patchDesc;
5217 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5218 if (index >= 0) {
5219 patchDesc = mAudioPatches.valueAt(index);
5220 afPatchHandle = patchDesc->mAfPatchHandle;
5221 }
5222
Eric Laurent1c333e22014-05-20 10:48:17 -07005223 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005224 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005225 0);
5226 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005227 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005228 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005230 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 addAudioPatch(patchDesc->mHandle, patchDesc);
5232 } else {
5233 patchDesc->mPatch = patch;
5234 }
5235 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 if (patchHandle) {
5237 *patchHandle = patchDesc->mHandle;
5238 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005239 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005240 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005241 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005242 }
5243 }
5244 }
5245 return status;
5246}
5247
Eric Laurent6a94d692014-05-20 11:18:06 -07005248status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5249 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005250{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005251 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 ssize_t index;
5253 if (patchHandle) {
5254 index = mAudioPatches.indexOfKey(*patchHandle);
5255 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005256 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 }
5258 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005259 return INVALID_OPERATION;
5260 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5262 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005263 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005264 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 removeAudioPatch(patchDesc->mHandle);
5266 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005267 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005268 return status;
5269}
5270
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005271sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005272 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005273 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005274 audio_format_t& format,
5275 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005276 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005277{
5278 // Choose an input profile based on the requested capture parameters: select the first available
5279 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005280 //
5281 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5282 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005283
5284 for (size_t i = 0; i < mHwModules.size(); i++)
5285 {
5286 if (mHwModules[i]->mHandle == 0) {
5287 continue;
5288 }
5289 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5290 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005291 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005292 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005293 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005294 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005295 format,
5296 &format /*updatedFormat*/,
5297 channelMask,
5298 &channelMask /*updatedChannelMask*/,
5299 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005300
Eric Laurente552edb2014-03-10 17:42:56 -07005301 return profile;
5302 }
5303 }
5304 }
5305 return NULL;
5306}
5307
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005308
5309audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005310 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005311{
François Gaffie036e1e92015-03-19 10:16:24 +01005312 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5313 audio_devices_t selectedDeviceFromMix =
5314 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005315
François Gaffie036e1e92015-03-19 10:16:24 +01005316 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5317 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005318 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005319 return getDeviceForInputSource(inputSource);
5320}
5321
5322audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5323{
Paul McLean466dc8e2015-04-17 13:15:36 -06005324 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5325 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005326 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005327 return route->mDeviceDescriptor->type();
5328 }
5329 }
5330
5331 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005332}
5333
Eric Laurente0720872014-03-11 09:30:41 -07005334float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005335 int index,
5336 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005337{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005338 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005339
5340 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5341 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5342 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5343 // the ringtone volume
5344 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5345 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5346 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5347 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5348 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5349 }
5350
Eric Laurente552edb2014-03-10 17:42:56 -07005351 // if a headset is connected, apply the following rules to ring tones and notifications
5352 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005353 // - always attenuate notifications volume by 6dB
5354 // - attenuate ring tones volume by 6dB unless music is not playing and
5355 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005356 // - if music is playing, always limit the volume to current music volume,
5357 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005358 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005359 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5360 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5361 AUDIO_DEVICE_OUT_WIRED_HEADSET |
Eric Laurent904d6322017-03-17 17:20:47 -07005362 AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5363 AUDIO_DEVICE_OUT_USB_HEADSET)) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005364 ((stream_strategy == STRATEGY_SONIFICATION)
5365 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005366 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005367 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005368 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005369 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005370 // when the phone is ringing we must consider that music could have been paused just before
5371 // by the music application and behave as if music was active if the last music track was
5372 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005373 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005374 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005375 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005376 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005377 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005378 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5379 musicDevice),
5380 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005381 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5382 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005383 if (volumeDB > minVolDB) {
5384 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005385 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005386 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005387 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5388 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5389 // on A2DP, also ensure notification volume is not too low compared to media when
5390 // intended to be played
5391 if ((volumeDB > -96.0f) &&
5392 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5393 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5394 stream, device,
5395 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5396 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5397 }
5398 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005399 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5400 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005401 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005402 }
5403 }
5404
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005405 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005406}
5407
Eric Laurente0720872014-03-11 09:30:41 -07005408status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005409 int index,
5410 const sp<AudioOutputDescriptor>& outputDesc,
5411 audio_devices_t device,
5412 int delayMs,
5413 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005414{
Eric Laurente552edb2014-03-10 17:42:56 -07005415 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005416 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005417 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005418 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005419 return NO_ERROR;
5420 }
François Gaffie2110e042015-03-24 08:41:51 +01005421 audio_policy_forced_cfg_t forceUseForComm =
5422 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005423 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005424 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5425 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005426 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005427 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005428 return INVALID_OPERATION;
5429 }
5430
Eric Laurentc75307b2015-03-17 15:29:32 -07005431 if (device == AUDIO_DEVICE_NONE) {
5432 device = outputDesc->device();
5433 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005434
Eric Laurentffbc80f2015-03-18 18:30:19 -07005435 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005436 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005437 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005438 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005439
Eric Laurentffbc80f2015-03-18 18:30:19 -07005440 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005441
Eric Laurent3b73df72014-03-11 09:06:29 -07005442 if (stream == AUDIO_STREAM_VOICE_CALL ||
5443 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005444 float voiceVolume;
5445 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005446 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005447 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005448 } else {
5449 voiceVolume = 1.0;
5450 }
5451
Eric Laurent18fba842016-03-31 14:41:26 -07005452 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005453 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5454 mLastVoiceVolume = voiceVolume;
5455 }
5456 }
5457
5458 return NO_ERROR;
5459}
5460
Eric Laurentc75307b2015-03-17 15:29:32 -07005461void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5462 audio_devices_t device,
5463 int delayMs,
5464 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005465{
Eric Laurentc75307b2015-03-17 15:29:32 -07005466 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005467
Eric Laurent794fde22016-03-11 09:50:45 -08005468 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005469 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005470 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005471 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005472 device,
5473 delayMs,
5474 force);
5475 }
5476}
5477
Eric Laurente0720872014-03-11 09:30:41 -07005478void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005479 bool on,
5480 const sp<AudioOutputDescriptor>& outputDesc,
5481 int delayMs,
5482 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005483{
Eric Laurent72249d52015-06-08 11:12:15 -07005484 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5485 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005486 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005487 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005488 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005489 }
5490 }
5491}
5492
Eric Laurente0720872014-03-11 09:30:41 -07005493void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005494 bool on,
5495 const sp<AudioOutputDescriptor>& outputDesc,
5496 int delayMs,
5497 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005498{
Eric Laurente552edb2014-03-10 17:42:56 -07005499 if (device == AUDIO_DEVICE_NONE) {
5500 device = outputDesc->device();
5501 }
5502
Eric Laurentc75307b2015-03-17 15:29:32 -07005503 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5504 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005505
5506 if (on) {
5507 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005508 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005509 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005510 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005511 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005512 }
5513 }
5514 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5515 outputDesc->mMuteCount[stream]++;
5516 } else {
5517 if (outputDesc->mMuteCount[stream] == 0) {
5518 ALOGV("setStreamMute() unmuting non muted stream!");
5519 return;
5520 }
5521 if (--outputDesc->mMuteCount[stream] == 0) {
5522 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005523 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005524 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005525 device,
5526 delayMs);
5527 }
5528 }
5529}
5530
Eric Laurente0720872014-03-11 09:30:41 -07005531void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005532 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005533{
Eric Laurent87ffa392015-05-22 10:32:38 -07005534 if(!hasPrimaryOutput()) {
5535 return;
5536 }
5537
Eric Laurente552edb2014-03-10 17:42:56 -07005538 // if the stream pertains to sonification strategy and we are in call we must
5539 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5540 // in the device used for phone strategy and play the tone if the selected device does not
5541 // interfere with the device used for phone strategy
5542 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5543 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005544 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005545 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5546 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005547 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005548 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5549 stream, starting, outputDesc->mDevice, stateChange);
5550 if (outputDesc->mRefCount[stream]) {
5551 int muteCount = 1;
5552 if (stateChange) {
5553 muteCount = outputDesc->mRefCount[stream];
5554 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005555 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005556 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5557 for (int i = 0; i < muteCount; i++) {
5558 setStreamMute(stream, starting, mPrimaryOutput);
5559 }
5560 } else {
5561 ALOGV("handleIncallSonification() high visibility");
5562 if (outputDesc->device() &
5563 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5564 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5565 for (int i = 0; i < muteCount; i++) {
5566 setStreamMute(stream, starting, mPrimaryOutput);
5567 }
5568 }
5569 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005570 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5571 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005572 } else {
5573 mpClientInterface->stopTone();
5574 }
5575 }
5576 }
5577 }
5578}
5579
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005580audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5581{
5582 // flags to stream type mapping
5583 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5584 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5585 }
5586 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5587 return AUDIO_STREAM_BLUETOOTH_SCO;
5588 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005589 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5590 return AUDIO_STREAM_TTS;
5591 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005592
5593 // usage to stream type mapping
5594 switch (attr->usage) {
5595 case AUDIO_USAGE_MEDIA:
5596 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005597 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005598 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5599 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005600 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5601 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005602 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5603 return AUDIO_STREAM_SYSTEM;
5604 case AUDIO_USAGE_VOICE_COMMUNICATION:
5605 return AUDIO_STREAM_VOICE_CALL;
5606
5607 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5608 return AUDIO_STREAM_DTMF;
5609
5610 case AUDIO_USAGE_ALARM:
5611 return AUDIO_STREAM_ALARM;
5612 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5613 return AUDIO_STREAM_RING;
5614
5615 case AUDIO_USAGE_NOTIFICATION:
5616 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5617 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5618 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5619 case AUDIO_USAGE_NOTIFICATION_EVENT:
5620 return AUDIO_STREAM_NOTIFICATION;
5621
5622 case AUDIO_USAGE_UNKNOWN:
5623 default:
5624 return AUDIO_STREAM_MUSIC;
5625 }
5626}
Eric Laurente83b55d2014-11-14 10:06:21 -08005627
François Gaffie53615e22015-03-19 09:24:12 +01005628bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5629{
Eric Laurente83b55d2014-11-14 10:06:21 -08005630 // has flags that map to a strategy?
5631 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5632 return true;
5633 }
5634
5635 // has known usage?
5636 switch (paa->usage) {
5637 case AUDIO_USAGE_UNKNOWN:
5638 case AUDIO_USAGE_MEDIA:
5639 case AUDIO_USAGE_VOICE_COMMUNICATION:
5640 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5641 case AUDIO_USAGE_ALARM:
5642 case AUDIO_USAGE_NOTIFICATION:
5643 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5644 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5645 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5646 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5647 case AUDIO_USAGE_NOTIFICATION_EVENT:
5648 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5649 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5650 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5651 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005652 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005653 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005654 break;
5655 default:
5656 return false;
5657 }
5658 return true;
5659}
5660
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005661bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005662 routing_strategy strategy, uint32_t inPastMs,
5663 nsecs_t sysTime) const
5664{
5665 if ((sysTime == 0) && (inPastMs != 0)) {
5666 sysTime = systemTime();
5667 }
Eric Laurent794fde22016-03-11 09:50:45 -08005668 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005669 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5670 (NUM_STRATEGIES == strategy)) &&
5671 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5672 return true;
5673 }
5674 }
5675 return false;
5676}
5677
François Gaffie2110e042015-03-24 08:41:51 +01005678audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5679{
5680 return mEngine->getForceUse(usage);
5681}
5682
5683bool AudioPolicyManager::isInCall()
5684{
5685 return isStateInCall(mEngine->getPhoneState());
5686}
5687
5688bool AudioPolicyManager::isStateInCall(int state)
5689{
5690 return is_state_in_call(state);
5691}
5692
Eric Laurentd60560a2015-04-10 11:31:20 -07005693void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5694{
5695 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5696 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5697 if (sourceDesc->mDevice->equals(deviceDesc)) {
5698 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5699 stopAudioSource(sourceDesc->getHandle());
5700 }
5701 }
5702
5703 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5704 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5705 bool release = false;
5706 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5707 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5708 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5709 source->ext.device.type == deviceDesc->type()) {
5710 release = true;
5711 }
5712 }
5713 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5714 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5715 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5716 sink->ext.device.type == deviceDesc->type()) {
5717 release = true;
5718 }
5719 }
5720 if (release) {
5721 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5722 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5723 }
5724 }
5725}
5726
Phil Burk09bc4612016-02-24 15:58:15 -08005727// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005728void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5729 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005730 // TODO Set this based on Config properties.
5731 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005732
5733 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5734 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005735 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005736
5737 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005738 bool supportsAC3 = false;
5739 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005740 bool supportsIEC61937 = false;
5741 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5742 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005743 switch (format) {
5744 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005745 supportsAC3 = true;
5746 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005747 case AUDIO_FORMAT_E_AC3:
5748 case AUDIO_FORMAT_DTS:
5749 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005750 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005751 break;
5752 case AUDIO_FORMAT_IEC61937:
5753 supportsIEC61937 = true;
5754 break;
5755 default:
5756 break;
5757 }
5758 }
Phil Burk09bc4612016-02-24 15:58:15 -08005759
5760 // Modify formats based on surround preferences.
5761 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005762 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5763 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5764 // Remove surround sound related formats.
5765 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5766 audio_format_t format = formats[formatIndex];
5767 switch(format) {
5768 case AUDIO_FORMAT_AC3:
5769 case AUDIO_FORMAT_E_AC3:
5770 case AUDIO_FORMAT_DTS:
5771 case AUDIO_FORMAT_DTS_HD:
5772 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005773 formats.removeAt(formatIndex);
5774 break;
5775 default:
5776 formatIndex++; // keep it
5777 break;
5778 }
Phil Burk09bc4612016-02-24 15:58:15 -08005779 }
Phil Burk07ac1142016-03-25 13:39:29 -07005780 supportsAC3 = false;
5781 supportsOtherSurround = false;
5782 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005783 }
Phil Burk07ac1142016-03-25 13:39:29 -07005784 } else { // AUTO or ALWAYS
5785 // Most TVs support AC3 even if they do not report it in the EDID.
5786 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5787 && !supportsAC3) {
5788 formats.add(AUDIO_FORMAT_AC3);
5789 supportsAC3 = true;
5790 }
5791
5792 // If ALWAYS, add support for raw surround formats if all are missing.
5793 // This assumes that if any of these formats are reported by the HAL
5794 // then the report is valid and should not be modified.
5795 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5796 && !supportsOtherSurround) {
5797 formats.add(AUDIO_FORMAT_E_AC3);
5798 formats.add(AUDIO_FORMAT_DTS);
5799 formats.add(AUDIO_FORMAT_DTS_HD);
5800 supportsOtherSurround = true;
5801 }
5802
5803 // Add support for IEC61937 if any raw surround supported.
5804 // The HAL could do this but add it here, just in case.
5805 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5806 formats.add(AUDIO_FORMAT_IEC61937);
5807 supportsIEC61937 = true;
5808 }
Phil Burk09bc4612016-02-24 15:58:15 -08005809 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005810}
5811
5812// Modify the list of channel masks supported.
5813void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5814 ChannelsVector &channelMasks = *channelMasksPtr;
5815 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5816 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5817
5818 // If NEVER, then remove support for channelMasks > stereo.
5819 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5820 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5821 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5822 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5823 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5824 channelMasks.removeAt(maskIndex);
5825 } else {
5826 maskIndex++;
5827 }
5828 }
5829 // If ALWAYS, then make sure we at least support 5.1
5830 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5831 bool supports5dot1 = false;
5832 // Are there any channel masks that can be considered "surround"?
5833 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5834 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5835 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5836 supports5dot1 = true;
5837 break;
5838 }
5839 }
5840 // If not then add 5.1 support.
5841 if (!supports5dot1) {
5842 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5843 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5844 }
Phil Burk09bc4612016-02-24 15:58:15 -08005845 }
5846}
5847
Phil Burk00eeb322016-03-31 12:41:00 -07005848void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5849 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005850 AudioProfileVector &profiles)
5851{
5852 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005853
François Gaffie112b0af2015-11-19 16:13:25 +01005854 // Format MUST be checked first to update the list of AudioProfile
5855 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005856 reply = mpClientInterface->getParameters(
5857 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005858 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005859 AudioParameter repliedParameters(reply);
5860 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005861 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005862 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5863 return;
5864 }
Phil Burk09bc4612016-02-24 15:58:15 -08005865 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005866 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005867 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005868 }
Phil Burk09bc4612016-02-24 15:58:15 -08005869 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005870 }
5871 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5872
Eric Laurent20eb3a42016-01-26 18:39:17 -08005873 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005874 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005875 ChannelsVector channelMasks;
5876 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005877 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005878 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005879
5880 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005881 reply = mpClientInterface->getParameters(
5882 ioHandle,
5883 requestedParameters.toString() + ";" +
5884 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005885 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005886 AudioParameter repliedParameters(reply);
5887 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005888 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005889 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005890 }
5891 }
5892 if (profiles.hasDynamicChannelsFor(format)) {
5893 reply = mpClientInterface->getParameters(ioHandle,
5894 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005895 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005896 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005897 AudioParameter repliedParameters(reply);
5898 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005899 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005900 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005901 if (device == AUDIO_DEVICE_OUT_HDMI) {
5902 filterSurroundChannelMasks(&channelMasks);
5903 }
François Gaffie112b0af2015-11-19 16:13:25 +01005904 }
5905 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005906 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005907 }
5908}
Eric Laurentd60560a2015-04-10 11:31:20 -07005909
Eric Laurente552edb2014-03-10 17:42:56 -07005910}; // namespace android