blob: 31c145e867e7a1ca371c90b1c0faec75318df0e9 [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>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036#include <utils/Log.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070037#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080038#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070039#include <soundtrigger/SoundTrigger.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070040#include <system/audio.h>
Mikhail Naganov9ee05402016-10-13 15:58:17 -070041#include <audio_policy_conf.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010043#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010044#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010045#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010046#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010047#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010048#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010049#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
Eric Laurentdc462862016-07-19 12:29:53 -070053//FIXME: workaround for truncated touch sounds
54// to be removed when the problem is handled by system UI
55#define TOUCH_SOUND_FIXED_DELAY_MS 100
Eric Laurente552edb2014-03-10 17:42:56 -070056// ----------------------------------------------------------------------------
57// AudioPolicyInterface implementation
58// ----------------------------------------------------------------------------
59
Eric Laurente0720872014-03-11 09:30:41 -070060status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080061 audio_policy_dev_state_t state,
62 const char *device_address,
63 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070064{
Paul McLeane743a472015-01-28 11:07:31 -080065 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080066}
67
François Gaffie44481e72016-04-20 07:49:57 +020068void AudioPolicyManager::broadcastDeviceConnectionState(audio_devices_t device,
69 audio_policy_dev_state_t state,
70 const String8 &device_address)
71{
72 AudioParameter param(device_address);
73 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
Mikhail Naganov388360c2016-10-17 17:09:41 -070074 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
François Gaffie44481e72016-04-20 07:49:57 +020075 param.addInt(key, device);
76 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
77}
78
Eric Laurentc73ca6e2014-12-12 14:34:22 -080079status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080080 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080081 const char *device_address,
82 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080083{
Paul McLeane743a472015-01-28 11:07:31 -080084 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
85- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070086
87 // connect/disconnect only 1 device at a time
88 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
89
François Gaffie53615e22015-03-19 09:24:12 +010090 sp<DeviceDescriptor> devDesc =
91 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080092
Eric Laurente552edb2014-03-10 17:42:56 -070093 // handle output devices
94 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070095 SortedVector <audio_io_handle_t> outputs;
96
Eric Laurent3a4311c2014-03-17 12:00:47 -070097 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
98
Eric Laurente552edb2014-03-10 17:42:56 -070099 // save a copy of the opened output descriptors before any output is opened or closed
100 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
101 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700102 switch (state)
103 {
104 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800105 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700106 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700107 ALOGW("setDeviceConnectionState() device already connected: %x", device);
108 return INVALID_OPERATION;
109 }
110 ALOGV("setDeviceConnectionState() connecting device %x", device);
111
Eric Laurente552edb2014-03-10 17:42:56 -0700112 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700113 index = mAvailableOutputDevices.add(devDesc);
114 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100115 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700116 if (module == 0) {
117 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
118 device);
119 mAvailableOutputDevices.remove(devDesc);
120 return INVALID_OPERATION;
121 }
Paul McLeane743a472015-01-28 11:07:31 -0800122 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700123 } else {
124 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 }
126
François Gaffie44481e72016-04-20 07:49:57 +0200127 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
128 // parameters on newly connected devices (instead of opening the outputs...)
129 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
130
Eric Laurenta1d525f2015-01-29 13:36:45 -0800131 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700132 mAvailableOutputDevices.remove(devDesc);
François Gaffie44481e72016-04-20 07:49:57 +0200133
134 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
135 devDesc->mAddress);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700136 return INVALID_OPERATION;
137 }
François Gaffie2110e042015-03-24 08:41:51 +0100138 // Propagate device availability to Engine
139 mEngine->setDeviceConnectionState(devDesc, state);
140
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700141 // outputs should never be empty here
142 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
143 "checkOutputsForDevice() returned no outputs but status OK");
144 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
145 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800146
Eric Laurent3ae5f312015-02-03 17:12:08 -0800147 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700148 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700149 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700151 ALOGW("setDeviceConnectionState() device not connected: %x", device);
152 return INVALID_OPERATION;
153 }
154
Paul McLean5c477aa2014-08-20 16:47:57 -0700155 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
156
Paul McLeane743a472015-01-28 11:07:31 -0800157 // Send Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200158 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700159
Eric Laurente552edb2014-03-10 17:42:56 -0700160 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700161 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700162
Eric Laurenta1d525f2015-01-29 13:36:45 -0800163 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100164
165 // Propagate device availability to Engine
166 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700167 } break;
168
169 default:
170 ALOGE("setDeviceConnectionState() invalid state: %x", state);
171 return BAD_VALUE;
172 }
173
Eric Laurent3a4311c2014-03-17 12:00:47 -0700174 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
175 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700176 checkA2dpSuspend();
177 checkOutputForAllStrategies();
178 // outputs must be closed after checkOutputForAllStrategies() is executed
179 if (!outputs.isEmpty()) {
180 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700181 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700182 // close unused outputs after device disconnection or direct outputs that have been
183 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700184 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700185 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
186 (desc->mDirectOpenCount == 0))) {
187 closeOutput(outputs[i]);
188 }
189 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700190 // check again after closing A2DP output to reset mA2dpSuspended if needed
191 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700192 }
193
194 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700195 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700196 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
197 updateCallRouting(newDevice);
198 }
Eric Laurente552edb2014-03-10 17:42:56 -0700199 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700200 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
201 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
202 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700203 // do not force device change on duplicated output because if device is 0, it will
204 // also force a device 0 for the two outputs it is duplicated to which may override
205 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700206 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100207 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700208 // always force when disconnecting (a non-duplicated device)
209 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700210 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700211 }
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
Eric Laurentd60560a2015-04-10 11:31:20 -0700214 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
215 cleanUpForDevice(devDesc);
216 }
217
Eric Laurent72aa32f2014-05-30 18:51:48 -0700218 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700219 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700220 } // end if is output device
221
Eric Laurente552edb2014-03-10 17:42:56 -0700222 // handle input devices
223 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700224 SortedVector <audio_io_handle_t> inputs;
225
Eric Laurent3a4311c2014-03-17 12:00:47 -0700226 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700227 switch (state)
228 {
229 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700232 ALOGW("setDeviceConnectionState() device already connected: %d", device);
233 return INVALID_OPERATION;
234 }
François Gaffie53615e22015-03-19 09:24:12 +0100235 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700236 if (module == NULL) {
237 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
238 device);
239 return INVALID_OPERATION;
240 }
François Gaffie44481e72016-04-20 07:49:57 +0200241
242 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
243 // parameters on newly connected devices (instead of opening the inputs...)
244 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
245
Paul McLean9080a4c2015-06-18 08:24:02 -0700246 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
François Gaffie44481e72016-04-20 07:49:57 +0200247 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
248 devDesc->mAddress);
Eric Laurentd4692962014-05-05 18:13:44 -0700249 return INVALID_OPERATION;
250 }
251
Eric Laurent3a4311c2014-03-17 12:00:47 -0700252 index = mAvailableInputDevices.add(devDesc);
253 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800254 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 } else {
256 return NO_MEMORY;
257 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800258
François Gaffie2110e042015-03-24 08:41:51 +0100259 // Propagate device availability to Engine
260 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700261 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700262
263 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700264 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700265 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700266 ALOGW("setDeviceConnectionState() device not connected: %d", device);
267 return INVALID_OPERATION;
268 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700269
270 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
271
272 // Set Disconnect to HALs
François Gaffie44481e72016-04-20 07:49:57 +0200273 broadcastDeviceConnectionState(device, state, devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700274
Paul McLean9080a4c2015-06-18 08:24:02 -0700275 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700276 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700277
François Gaffie2110e042015-03-24 08:41:51 +0100278 // Propagate device availability to Engine
279 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700280 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700281
282 default:
283 ALOGE("setDeviceConnectionState() invalid state: %x", state);
284 return BAD_VALUE;
285 }
286
Eric Laurentd4692962014-05-05 18:13:44 -0700287 closeAllInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700288 // As the input device list can impact the output device selection, update
289 // getDeviceForStrategy() cache
290 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700291
Eric Laurent87ffa392015-05-22 10:32:38 -0700292 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700293 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
294 updateCallRouting(newDevice);
295 }
296
Eric Laurentd60560a2015-04-10 11:31:20 -0700297 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
298 cleanUpForDevice(devDesc);
299 }
300
Eric Laurentb52c1522014-05-20 11:27:36 -0700301 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700302 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700303 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700304
305 ALOGW("setDeviceConnectionState() invalid device: %x", device);
306 return BAD_VALUE;
307}
308
Eric Laurente0720872014-03-11 09:30:41 -0700309audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100310 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700311{
Eric Laurent634b7142016-04-20 13:48:02 -0700312 sp<DeviceDescriptor> devDesc =
313 mHwModules.getDeviceDescriptor(device, device_address, "",
314 (strlen(device_address) != 0)/*matchAddress*/);
315
316 if (devDesc == 0) {
317 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
318 device, device_address);
319 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
320 }
François Gaffie53615e22015-03-19 09:24:12 +0100321
Eric Laurent3a4311c2014-03-17 12:00:47 -0700322 DeviceVector *deviceVector;
323
Eric Laurente552edb2014-03-10 17:42:56 -0700324 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700325 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700326 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700327 deviceVector = &mAvailableInputDevices;
328 } else {
329 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
330 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700331 }
Eric Laurent634b7142016-04-20 13:48:02 -0700332
333 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
334 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800335}
336
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800337status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
338 const char *device_address,
339 const char *device_name)
340{
341 status_t status;
342
343 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s",
344 device, device_address, device_name);
345
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800346 // connect/disconnect only 1 device at a time
347 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
348
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800349 // Check if the device is currently connected
350 sp<DeviceDescriptor> devDesc =
351 mHwModules.getDeviceDescriptor(device, device_address, device_name);
352 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
353 if (index < 0) {
354 // Nothing to do: device is not connected
355 return NO_ERROR;
356 }
357
358 // Toggle the device state: UNAVAILABLE -> AVAILABLE
359 // This will force reading again the device configuration
360 status = setDeviceConnectionState(device,
361 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
362 device_address, device_name);
363 if (status != NO_ERROR) {
364 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
365 status);
366 return status;
367 }
368
369 status = setDeviceConnectionState(device,
370 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
371 device_address, device_name);
372 if (status != NO_ERROR) {
373 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
374 status);
375 return status;
376 }
377
378 return NO_ERROR;
379}
380
Eric Laurentdc462862016-07-19 12:29:53 -0700381uint32_t AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, uint32_t delayMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700382{
383 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700384 status_t status;
385 audio_patch_handle_t afPatchHandle;
386 DeviceVector deviceList;
Eric Laurentdc462862016-07-19 12:29:53 -0700387 uint32_t muteWaitMs = 0;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388
Andy Hunga76c7de2016-12-13 19:14:31 -0800389 if(!hasPrimaryOutput() || mPrimaryOutput->device() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurentdc462862016-07-19 12:29:53 -0700390 return muteWaitMs;
Eric Laurent87ffa392015-05-22 10:32:38 -0700391 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800392 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700393 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
394
395 // release existing RX patch if any
396 if (mCallRxPatch != 0) {
397 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
398 mCallRxPatch.clear();
399 }
400 // release TX patch if any
401 if (mCallTxPatch != 0) {
402 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
403 mCallTxPatch.clear();
404 }
405
406 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
407 // via setOutputDevice() on primary output.
408 // Otherwise, create two audio patches for TX and RX path.
409 if (availablePrimaryOutputDevices() & rxDevice) {
Eric Laurentdc462862016-07-19 12:29:53 -0700410 muteWaitMs = setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700411 // If the TX device is also on the primary HW module, setOutputDevice() will take care
412 // of it due to legacy implementation. If not, create a patch.
413 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
414 == AUDIO_DEVICE_NONE) {
415 createTxPatch = true;
416 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700417 } else { // create RX path audio patch
418 struct audio_patch patch;
419
420 patch.num_sources = 1;
421 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700422 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
423 ALOG_ASSERT(!deviceList.isEmpty(),
424 "updateCallRouting() selected device not in output device list");
425 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
426 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
427 ALOG_ASSERT(!deviceList.isEmpty(),
428 "updateCallRouting() no telephony RX device");
429 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
430
431 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
432 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
433
434 // request to reuse existing output stream if one is already opened to reach the RX device
435 SortedVector<audio_io_handle_t> outputs =
436 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700437 audio_io_handle_t output = selectOutput(outputs,
438 AUDIO_OUTPUT_FLAG_NONE,
439 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700440 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700441 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700442 ALOG_ASSERT(!outputDesc->isDuplicated(),
443 "updateCallRouting() RX device output is duplicated");
444 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700445 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700446 patch.num_sources = 2;
447 }
448
449 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700450 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
452 status);
453 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100454 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700455 mCallRxPatch->mAfPatchHandle = afPatchHandle;
456 mCallRxPatch->mUid = mUidCached;
457 }
458 createTxPatch = true;
459 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700460 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700461 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700462
Eric Laurentc2730ba2014-07-20 15:47:07 -0700463 patch.num_sources = 1;
464 patch.num_sinks = 1;
465 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
466 ALOG_ASSERT(!deviceList.isEmpty(),
467 "updateCallRouting() selected device not in input device list");
468 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
469 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
470 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
471 ALOG_ASSERT(!deviceList.isEmpty(),
472 "updateCallRouting() no telephony TX device");
473 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
474 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
475
476 SortedVector<audio_io_handle_t> outputs =
477 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700478 audio_io_handle_t output = selectOutput(outputs,
479 AUDIO_OUTPUT_FLAG_NONE,
480 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700481 // request to reuse existing output stream if one is already opened to reach the TX
482 // path output device
483 if (output != AUDIO_IO_HANDLE_NONE) {
484 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
485 ALOG_ASSERT(!outputDesc->isDuplicated(),
486 "updateCallRouting() RX device output is duplicated");
487 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700488 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700489 patch.num_sources = 2;
490 }
491
Eric Laurentc0a889f2015-10-14 14:36:34 -0700492 // terminate active capture if on the same HW module as the call TX source device
493 // FIXME: would be better to refine to only inputs whose profile connects to the
494 // call TX device but this information is not in the audio patch and logic here must be
495 // symmetric to the one in startInput()
Eric Laurentfb66dd92016-01-28 18:32:03 -0800496 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
497 for (size_t i = 0; i < activeInputs.size(); i++) {
498 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
499 if (activeDesc->hasSameHwModuleAs(txSourceDeviceDesc)) {
500 AudioSessionCollection activeSessions =
501 activeDesc->getAudioSessions(true /*activeOnly*/);
502 for (size_t j = 0; j < activeSessions.size(); j++) {
503 audio_session_t activeSession = activeSessions.keyAt(j);
504 stopInput(activeDesc->mIoHandle, activeSession);
505 releaseInput(activeDesc->mIoHandle, activeSession);
506 }
Eric Laurentc0a889f2015-10-14 14:36:34 -0700507 }
508 }
509
Eric Laurentc2730ba2014-07-20 15:47:07 -0700510 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentdc462862016-07-19 12:29:53 -0700511 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700512 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
513 status);
514 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100515 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700516 mCallTxPatch->mAfPatchHandle = afPatchHandle;
517 mCallTxPatch->mUid = mUidCached;
518 }
519 }
Eric Laurentdc462862016-07-19 12:29:53 -0700520
521 return muteWaitMs;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700522}
523
Eric Laurente0720872014-03-11 09:30:41 -0700524void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700525{
526 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100527 // store previous phone state for management of sonification strategy below
528 int oldState = mEngine->getPhoneState();
529
530 if (mEngine->setPhoneState(state) != NO_ERROR) {
531 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700532 return;
533 }
François Gaffie2110e042015-03-24 08:41:51 +0100534 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700535 // if leaving call state, handle special case of active streams
536 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700537 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700538 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800539 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700540 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700541 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800542
Eric Laurent63dea1d2015-07-02 17:10:28 -0700543 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800544 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700545 }
546
François Gaffie2110e042015-03-24 08:41:51 +0100547 /**
548 * Switching to or from incall state or switching between telephony and VoIP lead to force
549 * routing command.
550 */
551 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
552 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700553
554 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700555 checkA2dpSuspend();
556 checkOutputForAllStrategies();
557 updateDevicesAndOutputs();
558
Eric Laurente552edb2014-03-10 17:42:56 -0700559 int delayMs = 0;
560 if (isStateInCall(state)) {
561 nsecs_t sysTime = systemTime();
562 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700564 // mute media and sonification strategies and delay device switch by the largest
565 // latency of any output where either strategy is active.
566 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100567 if ((isStrategyActive(desc, STRATEGY_MEDIA,
568 SONIFICATION_HEADSET_MUSIC_DELAY,
569 sysTime) ||
570 isStrategyActive(desc, STRATEGY_SONIFICATION,
571 SONIFICATION_HEADSET_MUSIC_DELAY,
572 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700573 (delayMs < (int)desc->latency()*2)) {
574 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700575 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700576 setStrategyMute(STRATEGY_MEDIA, true, desc);
577 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700578 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
580 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700581 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
582 }
583 }
584
Eric Laurent87ffa392015-05-22 10:32:38 -0700585 if (hasPrimaryOutput()) {
586 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
587 // the device returned is not necessarily reachable via this output
588 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
589 // force routing command to audio hardware when ending call
590 // even if no device change is needed
591 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
592 rxDevice = mPrimaryOutput->device();
593 }
Eric Laurente552edb2014-03-10 17:42:56 -0700594
Eric Laurent87ffa392015-05-22 10:32:38 -0700595 if (state == AUDIO_MODE_IN_CALL) {
596 updateCallRouting(rxDevice, delayMs);
597 } else if (oldState == AUDIO_MODE_IN_CALL) {
598 if (mCallRxPatch != 0) {
599 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
600 mCallRxPatch.clear();
601 }
602 if (mCallTxPatch != 0) {
603 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
604 mCallTxPatch.clear();
605 }
606 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
607 } else {
608 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700609 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700610 }
Eric Laurente552edb2014-03-10 17:42:56 -0700611 // if entering in call state, handle special case of active streams
612 // pertaining to sonification strategy see handleIncallSonification()
613 if (isStateInCall(state)) {
614 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800615 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700616 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700617 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700618
619 // force reevaluating accessibility routing when call starts
620 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700621 }
622
623 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700624 if (state == AUDIO_MODE_RINGTONE &&
625 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700626 mLimitRingtoneVolume = true;
627 } else {
628 mLimitRingtoneVolume = false;
629 }
630}
631
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700632audio_mode_t AudioPolicyManager::getPhoneState() {
633 return mEngine->getPhoneState();
634}
635
Eric Laurente0720872014-03-11 09:30:41 -0700636void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700637 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700638{
François Gaffie2110e042015-03-24 08:41:51 +0100639 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700640
François Gaffie2110e042015-03-24 08:41:51 +0100641 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
642 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
643 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700644 }
François Gaffie2110e042015-03-24 08:41:51 +0100645 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
646 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
647 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700648
649 // check for device and output changes triggered by new force usage
650 checkA2dpSuspend();
651 checkOutputForAllStrategies();
652 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800653
Eric Laurentdc462862016-07-19 12:29:53 -0700654 //FIXME: workaround for truncated touch sounds
655 // to be removed when the problem is handled by system UI
656 uint32_t delayMs = 0;
657 uint32_t waitMs = 0;
658 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
659 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
660 }
Eric Laurent87ffa392015-05-22 10:32:38 -0700661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
Eric Laurentdc462862016-07-19 12:29:53 -0700663 waitMs = updateCallRouting(newDevice, delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700664 }
Eric Laurente552edb2014-03-10 17:42:56 -0700665 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700666 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
667 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
668 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700669 waitMs = setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE),
670 delayMs);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 }
Eric Laurente552edb2014-03-10 17:42:56 -0700672 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentdc462862016-07-19 12:29:53 -0700673 applyStreamVolumes(outputDesc, newDevice, waitMs, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700674 }
675 }
676
Eric Laurentfb66dd92016-01-28 18:32:03 -0800677 Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
678 for (size_t i = 0; i < activeInputs.size(); i++) {
679 sp<AudioInputDescriptor> activeDesc = activeInputs[i];
680 audio_devices_t newDevice = getNewInputDevice(activeDesc);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700681 // Force new input selection if the new device can not be reached via current input
Eric Laurentfb66dd92016-01-28 18:32:03 -0800682 if (activeDesc->mProfile->getSupportedDevices().types() &
683 (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
684 setInputDevice(activeDesc->mIoHandle, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700685 } else {
Eric Laurentfb66dd92016-01-28 18:32:03 -0800686 closeInput(activeDesc->mIoHandle);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700687 }
Eric Laurente552edb2014-03-10 17:42:56 -0700688 }
Eric Laurente552edb2014-03-10 17:42:56 -0700689}
690
Eric Laurente0720872014-03-11 09:30:41 -0700691void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700692{
693 ALOGV("setSystemProperty() property %s, value %s", property, value);
694}
695
696// Find a direct output profile compatible with the parameters passed, even if the input flags do
697// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800698sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700699 audio_devices_t device,
700 uint32_t samplingRate,
701 audio_format_t format,
702 audio_channel_mask_t channelMask,
703 audio_output_flags_t flags)
704{
Eric Laurent861a6282015-05-18 15:40:16 -0700705 // only retain flags that will drive the direct output profile selection
706 // if explicitly requested
707 static const uint32_t kRelevantFlags =
708 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
709 flags =
710 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
711
712 sp<IOProfile> profile;
713
Eric Laurente552edb2014-03-10 17:42:56 -0700714 for (size_t i = 0; i < mHwModules.size(); i++) {
715 if (mHwModules[i]->mHandle == 0) {
716 continue;
717 }
718 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700719 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
720 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700721 samplingRate, NULL /*updatedSamplingRate*/,
722 format, NULL /*updatedFormat*/,
723 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700724 flags)) {
725 continue;
726 }
727 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100728 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700729 continue;
730 }
731 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100732 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700733 continue;
734 }
735 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100736 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700737 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700738 }
Eric Laurente552edb2014-03-10 17:42:56 -0700739 }
740 }
Eric Laurent861a6282015-05-18 15:40:16 -0700741 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700742}
743
Eric Laurente0720872014-03-11 09:30:41 -0700744audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100745 uint32_t samplingRate,
746 audio_format_t format,
747 audio_channel_mask_t channelMask,
748 audio_output_flags_t flags,
749 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700750{
Eric Laurent3b73df72014-03-11 09:06:29 -0700751 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700752 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
753 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
754 device, stream, samplingRate, format, channelMask, flags);
755
Kevin Rocard551061a2017-02-06 15:59:29 -0800756 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE, uid_t{0} /*Invalid uid*/,
Eric Laurente83b55d2014-11-14 10:06:21 -0800757 stream, samplingRate,format, channelMask,
758 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700759}
760
Eric Laurente83b55d2014-11-14 10:06:21 -0800761status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
762 audio_io_handle_t *output,
763 audio_session_t session,
764 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700765 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800766 const audio_config_t *config,
Eric Laurente83b55d2014-11-14 10:06:21 -0800767 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700768 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800769 audio_port_handle_t *portId)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700770{
Eric Laurente83b55d2014-11-14 10:06:21 -0800771 audio_attributes_t attributes;
772 if (attr != NULL) {
773 if (!isValidAttributes(attr)) {
774 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
775 attr->usage, attr->content_type, attr->flags,
776 attr->tags);
777 return BAD_VALUE;
778 }
779 attributes = *attr;
780 } else {
781 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
782 ALOGE("getOutputForAttr(): invalid stream type");
783 return BAD_VALUE;
784 }
785 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700786 }
Eric Laurent20b9ef02016-12-05 11:03:16 -0800787
788 // TODO: check for existing client for this port ID
789 if (*portId == AUDIO_PORT_HANDLE_NONE) {
790 *portId = AudioPort::getNextUniqueId();
791 }
792
Eric Laurentc75307b2015-03-17 15:29:32 -0700793 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800794 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100795 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Eric Laurent20b9ef02016-12-05 11:03:16 -0800796 if (!audio_has_proportional_frames(config->format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100797 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800798 }
François Gaffie036e1e92015-03-19 10:16:24 +0100799 *stream = streamTypefromAttributesInt(&attributes);
800 *output = desc->mIoHandle;
801 ALOGV("getOutputForAttr() returns output %d", *output);
802 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800803 }
804 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
805 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
806 return BAD_VALUE;
807 }
808
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700809 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
810 " session %d selectedDeviceId %d",
811 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
812 session, selectedDeviceId);
813
814 *stream = streamTypefromAttributesInt(&attributes);
815
816 // Explicit routing?
817 sp<DeviceDescriptor> deviceDesc;
818 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
819 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
820 deviceDesc = mAvailableOutputDevices[i];
821 break;
822 }
823 }
824 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700825
Eric Laurente83b55d2014-11-14 10:06:21 -0800826 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700827 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700828
Eric Laurente83b55d2014-11-14 10:06:21 -0800829 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700830 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
831 }
832
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700833 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Eric Laurent20b9ef02016-12-05 11:03:16 -0800834 device, config->sample_rate, config->format, config->channel_mask, flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700835
Kevin Rocard551061a2017-02-06 15:59:29 -0800836 *output = getOutputForDevice(device, session, uid, *stream,
Eric Laurent20b9ef02016-12-05 11:03:16 -0800837 config->sample_rate, config->format, config->channel_mask,
838 flags, &config->offload_info);
Eric Laurente83b55d2014-11-14 10:06:21 -0800839 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700840 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800841 return INVALID_OPERATION;
842 }
Paul McLeanaa981192015-03-21 09:55:15 -0700843
Eric Laurente83b55d2014-11-14 10:06:21 -0800844 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700845}
846
847audio_io_handle_t AudioPolicyManager::getOutputForDevice(
848 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800849 audio_session_t session __unused,
Kevin Rocard551061a2017-02-06 15:59:29 -0800850 uid_t clientUid,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700851 audio_stream_type_t stream,
852 uint32_t samplingRate,
853 audio_format_t format,
854 audio_channel_mask_t channelMask,
855 audio_output_flags_t flags,
856 const audio_offload_info_t *offloadInfo)
857{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700858 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700859 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700860
Eric Laurente552edb2014-03-10 17:42:56 -0700861#ifdef AUDIO_POLICY_TEST
862 if (mCurOutput != 0) {
863 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
864 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
865
866 if (mTestOutputs[mCurOutput] == 0) {
867 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700868 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
869 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700870 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700871 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700872 outputDesc->mFlags =
873 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700874 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700875 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
876 config.sample_rate = mTestSamplingRate;
877 config.channel_mask = mTestChannels;
878 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700879 if (offloadInfo != NULL) {
880 config.offload_info = *offloadInfo;
881 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700882 status = mpClientInterface->openOutput(0,
883 &mTestOutputs[mCurOutput],
884 &config,
885 &outputDesc->mDevice,
886 String8(""),
887 &outputDesc->mLatency,
888 outputDesc->mFlags);
889 if (status == NO_ERROR) {
890 outputDesc->mSamplingRate = config.sample_rate;
891 outputDesc->mFormat = config.format;
892 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700893 AudioParameter outputCmd = AudioParameter();
894 outputCmd.addInt(String8("set_id"),mCurOutput);
895 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
896 addOutput(mTestOutputs[mCurOutput], outputDesc);
897 }
898 }
899 return mTestOutputs[mCurOutput];
900 }
901#endif //AUDIO_POLICY_TEST
902
903 // open a direct output if required by specified parameters
904 //force direct flag if offload flag is set: offloading implies a direct output stream
905 // and all common behaviors are driven by checking only the direct flag
906 // this should normally be set appropriately in the policy configuration file
907 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700908 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700909 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700910 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
911 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
912 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800913 // only allow deep buffering for music stream type
914 if (stream != AUDIO_STREAM_MUSIC) {
915 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700916 } else if (/* stream == AUDIO_STREAM_MUSIC && */
917 flags == AUDIO_OUTPUT_FLAG_NONE &&
918 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
919 // use DEEP_BUFFER as default output for music stream type
920 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800921 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700922 if (stream == AUDIO_STREAM_TTS) {
923 flags = AUDIO_OUTPUT_FLAG_TTS;
924 }
Eric Laurente552edb2014-03-10 17:42:56 -0700925
Eric Laurentb732cf52014-09-24 19:08:21 -0700926 sp<IOProfile> profile;
927
928 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700929 // and not explicitly requested
930 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800931 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700932 audio_channel_count_from_out_mask(channelMask) <= 2) {
933 goto non_direct_output;
934 }
935
Andy Hung2ddee192015-12-18 17:34:44 -0800936 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
937 // This prevents creating an offloaded track and tearing it down immediately after start
938 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700939 // FIXME: We should check the audio session here but we do not have it in this context.
940 // This may prevent offloading in rare situations where effects are left active by apps
941 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700942
Eric Laurente552edb2014-03-10 17:42:56 -0700943 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800944 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700945 profile = getProfileForDirectOutput(device,
946 samplingRate,
947 format,
948 channelMask,
949 (audio_output_flags_t)flags);
950 }
951
Eric Laurent1c333e22014-05-20 10:48:17 -0700952 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700953 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700954
955 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700956 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700957 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
958 outputDesc = desc;
Kevin Rocard551061a2017-02-06 15:59:29 -0800959 // reuse direct output if currently open by the same client
960 // and configured with same parameters
Eric Laurente552edb2014-03-10 17:42:56 -0700961 if ((samplingRate == outputDesc->mSamplingRate) &&
Kevin Rocard551061a2017-02-06 15:59:29 -0800962 audio_formats_match(format, outputDesc->mFormat) &&
963 (channelMask == outputDesc->mChannelMask)) {
964 if (clientUid == outputDesc->mDirectClientUid) {
965 outputDesc->mDirectOpenCount++;
966 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
967 return mOutputs.keyAt(i);
968 } else {
969 ALOGV("getOutput() do not reuse direct output because current client (%ld) "
970 "is not the same as requesting client (%ld)",
971 (long)outputDesc->mDirectClientUid, (long)clientUid);
972 goto non_direct_output;
973 }
Eric Laurente552edb2014-03-10 17:42:56 -0700974 }
975 }
976 }
977 // close direct output if currently open and configured with different parameters
978 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700979 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
Eric Laurent861a6282015-05-18 15:40:16 -0700981
982 // if the selected profile is offloaded and no offload info was specified,
983 // create a default one
984 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100985 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700986 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
987 defaultOffloadInfo.sample_rate = samplingRate;
988 defaultOffloadInfo.channel_mask = channelMask;
989 defaultOffloadInfo.format = format;
990 defaultOffloadInfo.stream_type = stream;
991 defaultOffloadInfo.bit_rate = 0;
992 defaultOffloadInfo.duration_us = -1;
993 defaultOffloadInfo.has_video = true; // conservative
994 defaultOffloadInfo.is_streaming = true; // likely
995 offloadInfo = &defaultOffloadInfo;
996 }
997
Eric Laurentc75307b2015-03-17 15:29:32 -0700998 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700999 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001000 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -07001001 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001002 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1003 config.sample_rate = samplingRate;
1004 config.channel_mask = channelMask;
1005 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001006 if (offloadInfo != NULL) {
1007 config.offload_info = *offloadInfo;
1008 }
Eric Laurent322b4d22015-04-03 15:57:54 -07001009 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07001010 &output,
1011 &config,
1012 &outputDesc->mDevice,
1013 String8(""),
1014 &outputDesc->mLatency,
1015 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001016
1017 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001018 if (status != NO_ERROR ||
1019 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001020 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001021 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001022 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1023 "format %d %d, channelMask %04x %04x", output, samplingRate,
1024 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1025 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001026 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001027 mpClientInterface->closeOutput(output);
1028 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001029 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -08001030 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -08001031 goto non_direct_output;
1032 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001033 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001034 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001035 outputDesc->mSamplingRate = config.sample_rate;
1036 outputDesc->mChannelMask = config.channel_mask;
1037 outputDesc->mFormat = config.format;
1038 outputDesc->mRefCount[stream] = 0;
1039 outputDesc->mStopTime[stream] = 0;
1040 outputDesc->mDirectOpenCount = 1;
Kevin Rocard551061a2017-02-06 15:59:29 -08001041 outputDesc->mDirectClientUid = clientUid;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001042
Eric Laurente552edb2014-03-10 17:42:56 -07001043 audio_io_handle_t srcOutput = getOutputForEffect();
1044 addOutput(output, outputDesc);
1045 audio_io_handle_t dstOutput = getOutputForEffect();
1046 if (dstOutput == output) {
1047 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1048 }
1049 mPreviousOutputs = mOutputs;
1050 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001051 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001052 return output;
1053 }
1054
Eric Laurentb732cf52014-09-24 19:08:21 -07001055non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -07001056
1057 // A request for HW A/V sync cannot fallback to a mixed output because time
1058 // stamps are embedded in audio data
1059 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1060 return AUDIO_IO_HANDLE_NONE;
1061 }
1062
Eric Laurente552edb2014-03-10 17:42:56 -07001063 // ignoring channel mask due to downmix capability in mixer
1064
1065 // open a non direct output
1066
1067 // for non direct outputs, only PCM is supported
1068 if (audio_is_linear_pcm(format)) {
1069 // get which output is suitable for the specified stream. The actual
1070 // routing change will happen when startOutput() will be called
1071 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1072
Eric Laurent8838a382014-09-08 16:44:28 -07001073 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1074 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1075 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
1077 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1078 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1079
Paul McLeanaa981192015-03-21 09:55:15 -07001080 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07001081
1082 return output;
1083}
1084
Eric Laurente0720872014-03-11 09:30:41 -07001085audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001086 audio_output_flags_t flags,
1087 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001088{
1089 // select one output among several that provide a path to a particular device or set of
1090 // devices (the list was previously build by getOutputsForDevice()).
1091 // The priority is as follows:
1092 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001093 // 2: the output with the bit depth the closest to the requested one
1094 // 3: the primary output
1095 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001096
1097 if (outputs.size() == 0) {
1098 return 0;
1099 }
1100 if (outputs.size() == 1) {
1101 return outputs[0];
1102 }
1103
1104 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001105 audio_io_handle_t outputForFlags = 0;
1106 audio_io_handle_t outputForPrimary = 0;
1107 audio_io_handle_t outputForFormat = 0;
1108 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1109 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001110
1111 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001112 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001113 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001114 // if a valid format is specified, skip output if not compatible
1115 if (format != AUDIO_FORMAT_INVALID) {
1116 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001117 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001118 continue;
1119 }
1120 } else if (!audio_is_linear_pcm(format)) {
1121 continue;
1122 }
Eric Laurente6930022016-02-11 10:20:40 -08001123 if (AudioPort::isBetterFormatMatch(
1124 outputDesc->mFormat, bestFormat, format)) {
1125 outputForFormat = outputs[i];
1126 bestFormat = outputDesc->mFormat;
1127 }
Eric Laurent8838a382014-09-08 16:44:28 -07001128 }
1129
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001130 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001131 if (commonFlags >= maxCommonFlags) {
1132 if (commonFlags == maxCommonFlags) {
1133 if (AudioPort::isBetterFormatMatch(
1134 outputDesc->mFormat, bestFormatForFlags, format)) {
1135 outputForFlags = outputs[i];
1136 bestFormatForFlags = outputDesc->mFormat;
1137 }
1138 } else {
1139 outputForFlags = outputs[i];
1140 maxCommonFlags = commonFlags;
1141 bestFormatForFlags = outputDesc->mFormat;
1142 }
Eric Laurente552edb2014-03-10 17:42:56 -07001143 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1144 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001145 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001146 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001147 }
1148 }
1149 }
1150
Eric Laurente6930022016-02-11 10:20:40 -08001151 if (outputForFlags != 0) {
1152 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001153 }
Eric Laurente6930022016-02-11 10:20:40 -08001154 if (outputForFormat != 0) {
1155 return outputForFormat;
1156 }
1157 if (outputForPrimary != 0) {
1158 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001159 }
1160
1161 return outputs[0];
1162}
1163
Eric Laurente0720872014-03-11 09:30:41 -07001164status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001165 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001166 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001167{
Paul McLeanaa981192015-03-21 09:55:15 -07001168 ALOGV("startOutput() output %d, stream %d, session %d",
1169 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001170 ssize_t index = mOutputs.indexOfKey(output);
1171 if (index < 0) {
1172 ALOGW("startOutput() unknown output %d", output);
1173 return BAD_VALUE;
1174 }
1175
Eric Laurentc75307b2015-03-17 15:29:32 -07001176 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1177
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001178 // Routing?
1179 mOutputRoutes.incRouteActivity(session);
1180
Eric Laurentc75307b2015-03-17 15:29:32 -07001181 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001182 AudioMix *policyMix = NULL;
1183 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001184 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001185 policyMix = outputDesc->mPolicyMix;
1186 address = policyMix->mDeviceAddress.string();
1187 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1188 newDevice = policyMix->mDeviceType;
1189 } else {
1190 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1191 }
Eric Laurent493404d2015-04-21 15:07:36 -07001192 } else if (mOutputRoutes.hasRouteChanged(session)) {
1193 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001194 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 } else {
1196 newDevice = AUDIO_DEVICE_NONE;
1197 }
1198
1199 uint32_t delayMs = 0;
1200
Eric Laurentc40d9692016-04-13 19:14:13 -07001201 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001202
1203 if (status != NO_ERROR) {
1204 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001205 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001206 }
1207 // Automatically enable the remote submix input when output is started on a re routing mix
1208 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001209 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1210 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001211 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1212 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001213 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001214 "remote-submix");
1215 }
1216
1217 if (delayMs != 0) {
1218 usleep(delayMs * 1000);
1219 }
1220
1221 return status;
1222}
1223
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001224status_t AudioPolicyManager::startSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurentc75307b2015-03-17 15:29:32 -07001225 audio_stream_type_t stream,
1226 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001227 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001228 uint32_t *delayMs)
1229{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001230 // cannot start playback of STREAM_TTS if any other output is being used
1231 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001232
1233 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001234 if (stream == AUDIO_STREAM_TTS) {
1235 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001236 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001237 return INVALID_OPERATION;
1238 } else {
1239 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1240 }
1241 } else {
1242 // some playback other than beacon starts
1243 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1244 }
1245
Eric Laurent77305a62016-07-25 16:39:22 -07001246 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001247 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001248 bool force = !outputDesc->isActive() &&
1249 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001250
Eric Laurente552edb2014-03-10 17:42:56 -07001251 // increment usage count for this stream on the requested output:
1252 // NOTE that the usage count is the same for duplicated output and hardware output which is
1253 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1254 outputDesc->changeRefCount(stream, 1);
1255
Eric Laurent493404d2015-04-21 15:07:36 -07001256 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001257 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001258 if (device == AUDIO_DEVICE_NONE) {
1259 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001260 }
Eric Laurente552edb2014-03-10 17:42:56 -07001261 routing_strategy strategy = getStrategy(stream);
1262 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001263 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1264 (beaconMuteLatency > 0);
1265 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001266 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001267 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001268 if (desc != outputDesc) {
Eric Laurent77305a62016-07-25 16:39:22 -07001269 // force a device change if any other output is:
1270 // - managed by the same hw module
1271 // - has a current device selection that differs from selected device.
1272 // - supports currently selected device
1273 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07001274 // In this case, the audio HAL must receive the new device selection so that it can
1275 // change the device currently selected by the other active output.
1276 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurent77305a62016-07-25 16:39:22 -07001277 desc->device() != device &&
1278 desc->supportedDevices() & device &&
1279 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001280 force = true;
1281 }
1282 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001283 // a notification so that audio focus effect can propagate, or that a mute/unmute
1284 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001285 uint32_t latency = desc->latency();
1286 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1287 waitMs = latency;
1288 }
1289 }
1290 }
Eric Laurentdc462862016-07-19 12:29:53 -07001291 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001292
1293 // handle special case for sonification while in call
1294 if (isInCall()) {
1295 handleIncallSonification(stream, true, false);
1296 }
1297
1298 // apply volume rules for current stream and device if necessary
1299 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001300 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001301 outputDesc,
1302 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001303
1304 // update the outputs if starting an output with a stream that can affect notification
1305 // routing
1306 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001307
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001308 // force reevaluating accessibility routing when ringtone or alarm starts
1309 if (strategy == STRATEGY_SONIFICATION) {
1310 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1311 }
Eric Laurentdc462862016-07-19 12:29:53 -07001312
1313 if (waitMs > muteWaitMs) {
1314 *delayMs = waitMs - muteWaitMs;
1315 }
Eric Laurente552edb2014-03-10 17:42:56 -07001316 }
Eric Laurentdc462862016-07-19 12:29:53 -07001317
Eric Laurente552edb2014-03-10 17:42:56 -07001318 return NO_ERROR;
1319}
1320
1321
Eric Laurente0720872014-03-11 09:30:41 -07001322status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001323 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001324 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001325{
1326 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1327 ssize_t index = mOutputs.indexOfKey(output);
1328 if (index < 0) {
1329 ALOGW("stopOutput() unknown output %d", output);
1330 return BAD_VALUE;
1331 }
1332
Eric Laurentc75307b2015-03-17 15:29:32 -07001333 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001334
Eric Laurentc75307b2015-03-17 15:29:32 -07001335 if (outputDesc->mRefCount[stream] == 1) {
1336 // Automatically disable the remote submix input when output is stopped on a
1337 // re routing mix of type MIX_TYPE_RECORDERS
1338 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1339 outputDesc->mPolicyMix != NULL &&
1340 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1341 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1342 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001343 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001344 "remote-submix");
1345 }
1346 }
1347
1348 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001349 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001350 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001351 int activityCount = mOutputRoutes.decRouteActivity(session);
1352 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1353
1354 if (forceDeviceUpdate) {
1355 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1356 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001357 }
1358
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001359 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001360}
1361
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001362status_t AudioPolicyManager::stopSource(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001363 audio_stream_type_t stream,
1364 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001365{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001366 // always handle stream stop, check which stream type is stopping
1367 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1368
Eric Laurente552edb2014-03-10 17:42:56 -07001369 // handle special case for sonification while in call
1370 if (isInCall()) {
1371 handleIncallSonification(stream, false, false);
1372 }
1373
1374 if (outputDesc->mRefCount[stream] > 0) {
1375 // decrement usage count of this stream on the output
1376 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001377
Eric Laurente552edb2014-03-10 17:42:56 -07001378 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001379 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001380 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001381 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001382 // delay the device switch by twice the latency because stopOutput() is executed when
1383 // the track stop() command is received and at that time the audio track buffer can
1384 // still contain data that needs to be drained. The latency only covers the audio HAL
1385 // and kernel buffers. Also the latency does not always include additional delay in the
1386 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001387 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001388
1389 // force restoring the device selection on other active outputs if it differs from the
1390 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07001391 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07001392 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001393 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001394 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001395 desc->isActive() &&
1396 outputDesc->sharesHwModuleWith(desc) &&
1397 (newDevice != desc->device())) {
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001398 audio_devices_t newDevice2 = getNewOutputDevice(desc, false /*fromCache*/);
1399 bool force = desc->device() != newDevice2;
Eric Laurentc75307b2015-03-17 15:29:32 -07001400 setOutputDevice(desc,
Haynes Mathew George11c499a2016-08-26 12:08:25 -07001401 newDevice2,
1402 force,
Eric Laurent57de36c2016-09-28 16:59:11 -07001403 delayMs);
1404 // re-apply device specific volume if not done by setOutputDevice()
1405 if (!force) {
1406 applyStreamVolumes(desc, newDevice2, delayMs);
1407 }
Eric Laurente552edb2014-03-10 17:42:56 -07001408 }
1409 }
1410 // update the outputs if stopping one with a stream that can affect notification routing
1411 handleNotificationRoutingForStream(stream);
1412 }
1413 return NO_ERROR;
1414 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001415 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001416 return INVALID_OPERATION;
1417 }
1418}
1419
Eric Laurente83b55d2014-11-14 10:06:21 -08001420void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001421 audio_stream_type_t stream __unused,
1422 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001423{
1424 ALOGV("releaseOutput() %d", output);
1425 ssize_t index = mOutputs.indexOfKey(output);
1426 if (index < 0) {
1427 ALOGW("releaseOutput() releasing unknown output %d", output);
1428 return;
1429 }
1430
1431#ifdef AUDIO_POLICY_TEST
1432 int testIndex = testOutputIndex(output);
1433 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001434 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001435 if (outputDesc->isActive()) {
1436 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001437 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001438 mTestOutputs[testIndex] = 0;
1439 }
1440 return;
1441 }
1442#endif //AUDIO_POLICY_TEST
1443
Paul McLeanaa981192015-03-21 09:55:15 -07001444 // Routing
1445 mOutputRoutes.removeRoute(session);
1446
Eric Laurentc75307b2015-03-17 15:29:32 -07001447 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001448 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001449 if (desc->mDirectOpenCount <= 0) {
1450 ALOGW("releaseOutput() invalid open count %d for output %d",
1451 desc->mDirectOpenCount, output);
1452 return;
1453 }
1454 if (--desc->mDirectOpenCount == 0) {
1455 closeOutput(output);
1456 // If effects where present on the output, audioflinger moved them to the primary
1457 // output by default: move them back to the appropriate output.
1458 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001459 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001460 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1461 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001462 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001463 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001464 }
1465 }
1466}
1467
1468
Eric Laurentcaf7f482014-11-25 17:50:47 -08001469status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1470 audio_io_handle_t *input,
1471 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001472 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001473 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001474 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001475 audio_port_handle_t selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001476 input_type_t *inputType,
1477 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001478{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001479 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1480 "session %d, flags %#x",
Eric Laurent20b9ef02016-12-05 11:03:16 -08001481 attr->source, config->sample_rate, config->format, config->channel_mask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001482
Eric Laurentcaf7f482014-11-25 17:50:47 -08001483 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001484 *inputType = API_INPUT_INVALID;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001485
Eric Laurent275e8e92014-11-30 15:14:47 -08001486 audio_devices_t device;
1487 // handle legacy remote submix case where the address was not always specified
1488 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001489 audio_source_t inputSource = attr->source;
1490 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001491 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001492
Eric Laurentc447ded2015-01-06 08:47:05 -08001493 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1494 inputSource = AUDIO_SOURCE_MIC;
1495 }
1496 halInputSource = inputSource;
1497
Eric Laurent20b9ef02016-12-05 11:03:16 -08001498 // TODO: check for existing client for this port ID
1499 if (*portId == AUDIO_PORT_HANDLE_NONE) {
1500 *portId = AudioPort::getNextUniqueId();
1501 }
1502
Paul McLean466dc8e2015-04-17 13:15:36 -06001503 // Explicit routing?
1504 sp<DeviceDescriptor> deviceDesc;
1505 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1506 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1507 deviceDesc = mAvailableInputDevices[i];
1508 break;
1509 }
1510 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001511 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001512
Eric Laurentc447ded2015-01-06 08:47:05 -08001513 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001514 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001515 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001516 if (ret != NO_ERROR) {
1517 return ret;
1518 }
1519 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001520 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1521 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001522 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001523 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001524 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001525 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001526 return BAD_VALUE;
1527 }
Eric Laurentc722f302014-12-10 11:21:49 -08001528 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001529 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001530 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1531 // there is an external policy, but this input is attached to a mix of recorders,
1532 // meaning it receives audio injected into the framework, so the recorder doesn't
1533 // know about it and is therefore considered "legacy"
1534 *inputType = API_INPUT_LEGACY;
1535 } else {
1536 // recording a mix of players defined by an external policy, we're rerouting for
1537 // an external policy
1538 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1539 }
Eric Laurentc722f302014-12-10 11:21:49 -08001540 } else if (audio_is_remote_submix_device(device)) {
1541 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001542 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001543 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1544 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001545 } else {
1546 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001547 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001548
Eric Laurent599c7582015-12-07 18:05:55 -08001549 }
1550
1551 *input = getInputForDevice(device, address, session, uid, inputSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001552 config->sample_rate, config->format, config->channel_mask, flags,
Eric Laurent599c7582015-12-07 18:05:55 -08001553 policyMix);
1554 if (*input == AUDIO_IO_HANDLE_NONE) {
1555 mInputRoutes.removeRoute(session);
1556 return INVALID_OPERATION;
1557 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08001558
Eric Laurent599c7582015-12-07 18:05:55 -08001559 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1560 return NO_ERROR;
1561}
1562
1563
1564audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1565 String8 address,
1566 audio_session_t session,
1567 uid_t uid,
1568 audio_source_t inputSource,
1569 uint32_t samplingRate,
1570 audio_format_t format,
1571 audio_channel_mask_t channelMask,
1572 audio_input_flags_t flags,
1573 AudioMix *policyMix)
1574{
1575 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1576 audio_source_t halInputSource = inputSource;
1577 bool isSoundTrigger = false;
1578
1579 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1580 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1581 if (index >= 0) {
1582 input = mSoundTriggerSessions.valueFor(session);
1583 isSoundTrigger = true;
1584 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1585 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1586 } else {
1587 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001588 }
1589 }
1590
Andy Hungf129b032015-04-07 13:45:50 -07001591 // find a compatible input profile (not necessarily identical in parameters)
1592 sp<IOProfile> profile;
1593 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001594 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001595 audio_format_t profileFormat = format;
1596 audio_channel_mask_t profileChannelMask = channelMask;
1597 audio_input_flags_t profileFlags = flags;
1598 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001599 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001600 profileSamplingRate, profileFormat, profileChannelMask,
1601 profileFlags);
1602 if (profile != 0) {
1603 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07001604 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
1605 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Andy Hungf129b032015-04-07 13:45:50 -07001606 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1607 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1608 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001609 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1610 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001611 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001612 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001613 }
Eric Laurente552edb2014-03-10 17:42:56 -07001614 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001615 // Pick input sampling rate if not specified by client
1616 if (samplingRate == 0) {
1617 samplingRate = profileSamplingRate;
1618 }
Eric Laurente552edb2014-03-10 17:42:56 -07001619
Eric Laurent322b4d22015-04-03 15:57:54 -07001620 if (profile->getModuleHandle() == 0) {
1621 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001622 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001623 }
1624
Eric Laurent599c7582015-12-07 18:05:55 -08001625 sp<AudioSession> audioSession = new AudioSession(session,
1626 inputSource,
1627 format,
1628 samplingRate,
1629 channelMask,
1630 flags,
1631 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001632 isSoundTrigger,
1633 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001634
Eric Laurent599c7582015-12-07 18:05:55 -08001635 // reuse an open input if possible
Eric Laurent555530a2017-02-07 18:17:24 -08001636 sp<AudioInputDescriptor> reusedInputDesc;
Eric Laurent599c7582015-12-07 18:05:55 -08001637 for (size_t i = 0; i < mInputs.size(); i++) {
1638 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001639 // reuse input if:
1640 // - it shares the same profile
1641 // AND
1642 // - it is not a reroute submix input
1643 // AND
1644 // - it is: not used for sound trigger
1645 // OR
1646 // used for sound trigger and all clients use the same session ID
1647 //
1648 if ((profile == desc->mProfile) &&
1649 (isSoundTrigger == desc->isSoundTrigger()) &&
1650 !is_virtual_input_device(device)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001651
1652 sp<AudioSession> as = desc->getAudioSession(session);
1653 if (as != 0) {
1654 // do not allow unmatching properties on same session
1655 if (as->matches(audioSession)) {
1656 as->changeOpenCount(1);
1657 } else {
1658 ALOGW("getInputForDevice() record with different attributes"
1659 " exists for session %d", session);
Eric Laurent555530a2017-02-07 18:17:24 -08001660 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001661 }
Eric Laurentfb66dd92016-01-28 18:32:03 -08001662 } else if (isSoundTrigger) {
Eric Laurent555530a2017-02-07 18:17:24 -08001663 continue;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001664 }
Eric Laurentbb948092017-01-23 18:33:30 -08001665
Eric Laurent555530a2017-02-07 18:17:24 -08001666 // Reuse the already opened input stream on this profile if:
1667 // - the new capture source is background OR
1668 // - the path requested configurations match OR
1669 // - the new source priority is less than the highest source priority on this input
1670 // If the input stream cannot be reused, close it before opening a new stream
1671 // on the same profile for the new client so that the requested path configuration
1672 // can be selected.
1673 if (!isConcurrentSource(inputSource) &&
Eric Laurentbb948092017-01-23 18:33:30 -08001674 ((desc->mSamplingRate != samplingRate ||
Eric Laurentfb66dd92016-01-28 18:32:03 -08001675 desc->mChannelMask != channelMask ||
Eric Laurente6930022016-02-11 10:20:40 -08001676 !audio_formats_match(desc->mFormat, format)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001677 (source_priority(desc->getHighestPrioritySource(false /*activeOnly*/)) <
Eric Laurentbb948092017-01-23 18:33:30 -08001678 source_priority(inputSource)))) {
Eric Laurent555530a2017-02-07 18:17:24 -08001679 reusedInputDesc = desc;
1680 continue;
Eric Laurent599c7582015-12-07 18:05:55 -08001681 } else {
1682 desc->addAudioSession(session, audioSession);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001683 ALOGV("%s: reusing input %d", __FUNCTION__, mInputs.keyAt(i));
1684 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001685 }
Eric Laurent599c7582015-12-07 18:05:55 -08001686 }
1687 }
Eric Laurent599c7582015-12-07 18:05:55 -08001688
Eric Laurent555530a2017-02-07 18:17:24 -08001689 if (reusedInputDesc != 0) {
1690 AudioSessionCollection sessions = reusedInputDesc->getAudioSessions(false /*activeOnly*/);
1691 for (size_t j = 0; j < sessions.size(); j++) {
1692 audio_session_t currentSession = sessions.keyAt(j);
1693 stopInput(reusedInputDesc->mIoHandle, currentSession);
1694 releaseInput(reusedInputDesc->mIoHandle, currentSession);
1695 }
1696 }
1697
Eric Laurentcf2c0212014-07-25 16:20:43 -07001698 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001699 config.sample_rate = profileSamplingRate;
1700 config.channel_mask = profileChannelMask;
1701 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001702
Eric Laurent322b4d22015-04-03 15:57:54 -07001703 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001704 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001705 &config,
1706 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001707 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001708 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001709 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001710
1711 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001712 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001713 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001714 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001715 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001716 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1717 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001718 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001719 if (input != AUDIO_IO_HANDLE_NONE) {
1720 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001721 }
Eric Laurent599c7582015-12-07 18:05:55 -08001722 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001723 }
1724
Eric Laurent1f2f2232014-06-02 12:01:23 -07001725 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001726 inputDesc->mSamplingRate = profileSamplingRate;
1727 inputDesc->mFormat = profileFormat;
1728 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001729 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001730 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001731 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001732
Eric Laurent599c7582015-12-07 18:05:55 -08001733 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001734 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001735
Eric Laurent599c7582015-12-07 18:05:55 -08001736 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001737}
1738
Eric Laurentbb948092017-01-23 18:33:30 -08001739//static
1740bool AudioPolicyManager::isConcurrentSource(audio_source_t source)
1741{
1742 return (source == AUDIO_SOURCE_HOTWORD) ||
1743 (source == AUDIO_SOURCE_VOICE_RECOGNITION) ||
1744 (source == AUDIO_SOURCE_FM_TUNER);
1745}
1746
Eric Laurentfb66dd92016-01-28 18:32:03 -08001747bool AudioPolicyManager::isConcurentCaptureAllowed(const sp<AudioInputDescriptor>& inputDesc,
1748 const sp<AudioSession>& audioSession)
1749{
1750 // Do not allow capture if an active voice call is using a software patch and
1751 // the call TX source device is on the same HW module.
1752 // FIXME: would be better to refine to only inputs whose profile connects to the
1753 // call TX device but this information is not in the audio patch
1754 if (mCallTxPatch != 0 &&
1755 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1756 return false;
1757 }
1758
1759 // starting concurrent capture is enabled if:
1760 // 1) capturing for re-routing
1761 // 2) capturing for HOTWORD source
1762 // 3) capturing for FM TUNER source
1763 // 3) All other active captures are either for re-routing or HOTWORD
1764
1765 if (is_virtual_input_device(inputDesc->mDevice) ||
Eric Laurentbb948092017-01-23 18:33:30 -08001766 isConcurrentSource(audioSession->inputSource())) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001767 return true;
1768 }
1769
1770 Vector< sp<AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
1771 for (size_t i = 0; i < activeInputs.size(); i++) {
1772 sp<AudioInputDescriptor> activeInput = activeInputs[i];
Eric Laurentbb948092017-01-23 18:33:30 -08001773 if (!isConcurrentSource(activeInput->inputSource(true)) &&
Eric Laurentfb66dd92016-01-28 18:32:03 -08001774 !is_virtual_input_device(activeInput->mDevice)) {
1775 return false;
1776 }
1777 }
1778
1779 return true;
1780}
1781
1782
Eric Laurent4dc68062014-07-28 17:26:49 -07001783status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurentfb66dd92016-01-28 18:32:03 -08001784 audio_session_t session,
1785 concurrency_type__mask_t *concurrency)
Eric Laurente552edb2014-03-10 17:42:56 -07001786{
1787 ALOGV("startInput() input %d", input);
Eric Laurentfb66dd92016-01-28 18:32:03 -08001788 *concurrency = API_INPUT_CONCURRENCY_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001789 ssize_t index = mInputs.indexOfKey(input);
1790 if (index < 0) {
1791 ALOGW("startInput() unknown input %d", input);
1792 return BAD_VALUE;
1793 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001794 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001795
Eric Laurent599c7582015-12-07 18:05:55 -08001796 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1797 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001798 ALOGW("startInput() unknown session %d on input %d", session, input);
1799 return BAD_VALUE;
1800 }
1801
Eric Laurentfb66dd92016-01-28 18:32:03 -08001802 if (!isConcurentCaptureAllowed(inputDesc, audioSession)) {
1803 ALOGW("startInput(%d) failed: other input already started", input);
1804 return INVALID_OPERATION;
1805 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001806
Eric Laurentfb66dd92016-01-28 18:32:03 -08001807 if (isInCall()) {
1808 *concurrency |= API_INPUT_CONCURRENCY_CALL;
1809 }
Eric Laurentf7c50102016-09-30 15:19:43 -07001810 if (mInputs.activeInputsCountOnDevices() != 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001811 *concurrency |= API_INPUT_CONCURRENCY_CAPTURE;
Eric Laurente552edb2014-03-10 17:42:56 -07001812 }
1813
Eric Laurent313d1e72016-01-29 09:56:57 -08001814 // increment activity count before calling getNewInputDevice() below as only active sessions
1815 // are considered for device selection
1816 audioSession->changeActiveCount(1);
1817
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001818 // Routing?
1819 mInputRoutes.incRouteActivity(session);
1820
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001821 if (audioSession->activeCount() == 1 || mInputRoutes.hasRouteChanged(session)) {
Eric Laurent271a93e2016-09-29 14:47:06 -07001822 // indicate active capture to sound trigger service if starting capture from a mic on
1823 // primary HW module
Eric Laurentf7c50102016-09-30 15:19:43 -07001824 audio_devices_t device = getNewInputDevice(inputDesc);
Eric Laurent271a93e2016-09-29 14:47:06 -07001825 setInputDevice(input, device, true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001826
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001827 if (inputDesc->getAudioSessionCount(true/*activeOnly*/) == 1) {
1828 // if input maps to a dynamic policy with an activity listener, notify of state change
1829 if ((inputDesc->mPolicyMix != NULL)
1830 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1831 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1832 MIX_STATE_MIXING);
Eric Laurentc722f302014-12-10 11:21:49 -08001833 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001834
Eric Laurentf7c50102016-09-30 15:19:43 -07001835 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1836 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Eric Laurent05b345e2016-11-18 12:36:27 -08001837 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001838 SoundTrigger::setCaptureState(true);
1839 }
1840
1841 // automatically enable the remote submix output when input is started if not
1842 // used by a policy mix of type MIX_TYPE_RECORDERS
1843 // For remote submix (a virtual device), we open only one input per capture request.
1844 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1845 String8 address = String8("");
1846 if (inputDesc->mPolicyMix == NULL) {
1847 address = String8("0");
1848 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1849 address = inputDesc->mPolicyMix->mDeviceAddress;
1850 }
1851 if (address != "") {
1852 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1853 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1854 address, "remote-submix");
1855 }
Eric Laurentc722f302014-12-10 11:21:49 -08001856 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001857 }
Eric Laurente552edb2014-03-10 17:42:56 -07001858 }
1859
Eric Laurent599c7582015-12-07 18:05:55 -08001860 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001861
Eric Laurente552edb2014-03-10 17:42:56 -07001862 return NO_ERROR;
1863}
1864
Eric Laurent4dc68062014-07-28 17:26:49 -07001865status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1866 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001867{
1868 ALOGV("stopInput() input %d", input);
1869 ssize_t index = mInputs.indexOfKey(input);
1870 if (index < 0) {
1871 ALOGW("stopInput() unknown input %d", input);
1872 return BAD_VALUE;
1873 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001874 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001875
Eric Laurent599c7582015-12-07 18:05:55 -08001876 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001877 if (index < 0) {
1878 ALOGW("stopInput() unknown session %d on input %d", session, input);
1879 return BAD_VALUE;
1880 }
1881
Eric Laurent599c7582015-12-07 18:05:55 -08001882 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001883 ALOGW("stopInput() input %d already stopped", input);
1884 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001885 }
1886
Eric Laurent599c7582015-12-07 18:05:55 -08001887 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001888
1889 // Routing?
1890 mInputRoutes.decRouteActivity(session);
1891
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001892 if (audioSession->activeCount() == 0) {
Eric Laurent84332aa2016-01-28 22:19:18 +00001893
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001894 if (inputDesc->isActive()) {
1895 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
1896 } else {
1897 // if input maps to a dynamic policy with an activity listener, notify of state change
1898 if ((inputDesc->mPolicyMix != NULL)
1899 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
1900 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
1901 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001902 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07001903
1904 // automatically disable the remote submix output when input is stopped if not
1905 // used by a policy mix of type MIX_TYPE_RECORDERS
1906 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1907 String8 address = String8("");
1908 if (inputDesc->mPolicyMix == NULL) {
1909 address = String8("0");
1910 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1911 address = inputDesc->mPolicyMix->mDeviceAddress;
1912 }
1913 if (address != "") {
1914 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1915 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1916 address, "remote-submix");
1917 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001918 }
Eric Laurent84332aa2016-01-28 22:19:18 +00001919
Eric Laurentf7c50102016-09-30 15:19:43 -07001920 audio_devices_t device = inputDesc->mDevice;
Eric Laurentfb66dd92016-01-28 18:32:03 -08001921 resetInputDevice(input);
Eric Laurent84332aa2016-01-28 22:19:18 +00001922
Eric Laurentf7c50102016-09-30 15:19:43 -07001923 // indicate inactive capture to sound trigger service if stopping capture from a mic on
1924 // primary HW module
1925 audio_devices_t primaryInputDevices = availablePrimaryInputDevices();
1926 if (((device & primaryInputDevices & ~AUDIO_DEVICE_BIT_IN) != 0) &&
1927 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Eric Laurentfb66dd92016-01-28 18:32:03 -08001928 SoundTrigger::setCaptureState(false);
1929 }
1930 inputDesc->clearPreemptedSessions();
Eric Laurent84332aa2016-01-28 22:19:18 +00001931 }
Eric Laurente552edb2014-03-10 17:42:56 -07001932 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001933 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001934}
1935
Eric Laurent4dc68062014-07-28 17:26:49 -07001936void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1937 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001938{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001939
Eric Laurente552edb2014-03-10 17:42:56 -07001940 ALOGV("releaseInput() %d", input);
1941 ssize_t index = mInputs.indexOfKey(input);
1942 if (index < 0) {
1943 ALOGW("releaseInput() releasing unknown input %d", input);
1944 return;
1945 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001946
1947 // Routing
1948 mInputRoutes.removeRoute(session);
1949
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001950 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1951 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001952
Eric Laurent599c7582015-12-07 18:05:55 -08001953 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
vivek mehta587b8df2017-01-31 14:58:44 -08001954 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001955 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1956 return;
1957 }
Eric Laurent599c7582015-12-07 18:05:55 -08001958
1959 if (audioSession->openCount() == 0) {
1960 ALOGW("releaseInput() invalid open count %d on session %d",
1961 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001962 return;
1963 }
Eric Laurent599c7582015-12-07 18:05:55 -08001964
1965 if (audioSession->changeOpenCount(-1) == 0) {
1966 inputDesc->removeAudioSession(session);
1967 }
1968
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001969 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001970 ALOGV("releaseInput() exit > 0");
1971 return;
1972 }
1973
Eric Laurent05b90f82014-08-27 15:32:29 -07001974 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001975 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001976 ALOGV("releaseInput() exit");
1977}
1978
Eric Laurentd4692962014-05-05 18:13:44 -07001979void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001980 bool patchRemoved = false;
1981
Eric Laurentd4692962014-05-05 18:13:44 -07001982 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001983 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001984 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001985 if (patch_index >= 0) {
1986 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07001987 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07001988 mAudioPatches.removeItemsAt(patch_index);
1989 patchRemoved = true;
1990 }
Eric Laurentd4692962014-05-05 18:13:44 -07001991 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1992 }
1993 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001994 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001995 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001996
1997 if (patchRemoved) {
1998 mpClientInterface->onAudioPatchListUpdate();
1999 }
Eric Laurentd4692962014-05-05 18:13:44 -07002000}
2001
Eric Laurente0720872014-03-11 09:30:41 -07002002void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002003 int indexMin,
2004 int indexMax)
2005{
2006 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002007 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002008
2009 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002010 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2011 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002012 continue;
2013 }
2014 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002015 }
Eric Laurente552edb2014-03-10 17:42:56 -07002016}
2017
Eric Laurente0720872014-03-11 09:30:41 -07002018status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002019 int index,
2020 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002021{
2022
François Gaffied1ab2bd2015-12-02 18:20:06 +01002023 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
2024 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002025 return BAD_VALUE;
2026 }
2027 if (!audio_is_output_device(device)) {
2028 return BAD_VALUE;
2029 }
2030
2031 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01002032 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002033
Eric Laurent1fd372e2016-04-06 14:23:53 -07002034 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07002035 stream, device, index);
2036
Eric Laurent28d09f02016-03-08 10:43:05 -08002037 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002038 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2039 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002040 continue;
2041 }
2042 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
2043 }
Eric Laurente552edb2014-03-10 17:42:56 -07002044
Eric Laurent1fd372e2016-04-06 14:23:53 -07002045 // update volume on all outputs and streams matching the following:
2046 // - The requested stream (or a stream matching for volume control) is active on the output
2047 // - The device (or devices) selected by the strategy corresponding to this stream includes
2048 // the requested device
2049 // - For non default requested device, currently selected device on the output is either the
2050 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07002051 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2052 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002053 status_t status = NO_ERROR;
2054 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002055 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2056 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08002057 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2058 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002059 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07002060 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07002061 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
2062 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002063 continue;
2064 }
Eric Laurent794fde22016-03-11 09:50:45 -08002065 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurente76f29c2016-09-14 17:17:53 -07002066 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, false /*fromCache*/);
2067 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) &&
2068 ((curStreamDevice & device) == 0)) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002069 continue;
2070 }
Eric Laurente76f29c2016-09-14 17:17:53 -07002071 bool applyVolume;
Eric Laurent5a2b6292016-04-14 18:05:57 -07002072 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07002073 curStreamDevice |= device;
Eric Laurente76f29c2016-09-14 17:17:53 -07002074 applyVolume = (curDevice & curStreamDevice) != 0;
2075 } else {
2076 applyVolume = !mVolumeCurves->hasVolumeIndexForDevice(
2077 stream, Volume::getDeviceForVolume(curStreamDevice));
Eric Laurent1fd372e2016-04-06 14:23:53 -07002078 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002079
Eric Laurente76f29c2016-09-14 17:17:53 -07002080 if (applyVolume) {
Eric Laurentdc462862016-07-19 12:29:53 -07002081 //FIXME: workaround for truncated touch sounds
2082 // delayed volume change for system stream to be removed when the problem is
2083 // handled by system UI
Eric Laurent28d09f02016-03-08 10:43:05 -08002084 status_t volStatus =
Eric Laurentdc462862016-07-19 12:29:53 -07002085 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice,
2086 (stream == AUDIO_STREAM_SYSTEM) ? TOUCH_SOUND_FIXED_DELAY_MS : 0);
Eric Laurent28d09f02016-03-08 10:43:05 -08002087 if (volStatus != NO_ERROR) {
2088 status = volStatus;
2089 }
2090 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08002091 }
Eric Laurente552edb2014-03-10 17:42:56 -07002092 }
2093 return status;
2094}
2095
Eric Laurente0720872014-03-11 09:30:41 -07002096status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07002097 int *index,
2098 audio_devices_t device)
2099{
2100 if (index == NULL) {
2101 return BAD_VALUE;
2102 }
2103 if (!audio_is_output_device(device)) {
2104 return BAD_VALUE;
2105 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07002106 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07002107 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07002108 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07002109 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
2110 }
François Gaffiedfd74092015-03-19 12:10:59 +01002111 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07002112
François Gaffied1ab2bd2015-12-02 18:20:06 +01002113 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002114 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
2115 return NO_ERROR;
2116}
2117
Eric Laurente0720872014-03-11 09:30:41 -07002118audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07002119 const SortedVector<audio_io_handle_t>& outputs)
2120{
2121 // select one output among several suitable for global effects.
2122 // The priority is as follows:
2123 // 1: An offloaded output. If the effect ends up not being offloadable,
2124 // AudioFlinger will invalidate the track and the offloaded output
2125 // will be closed causing the effect to be moved to a PCM output.
2126 // 2: A deep buffer output
2127 // 3: the first output in the list
2128
2129 if (outputs.size() == 0) {
2130 return 0;
2131 }
2132
2133 audio_io_handle_t outputOffloaded = 0;
2134 audio_io_handle_t outputDeepBuffer = 0;
2135
2136 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002137 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07002138 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07002139 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2140 outputOffloaded = outputs[i];
2141 }
2142 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2143 outputDeepBuffer = outputs[i];
2144 }
2145 }
2146
2147 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
2148 outputOffloaded, outputDeepBuffer);
2149 if (outputOffloaded != 0) {
2150 return outputOffloaded;
2151 }
2152 if (outputDeepBuffer != 0) {
2153 return outputDeepBuffer;
2154 }
2155
2156 return outputs[0];
2157}
2158
Eric Laurente0720872014-03-11 09:30:41 -07002159audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07002160{
2161 // apply simple rule where global effects are attached to the same output as MUSIC streams
2162
Eric Laurent3b73df72014-03-11 09:06:29 -07002163 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07002164 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2165 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
2166
2167 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
2168 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
2169 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
2170
2171 return output;
2172}
2173
Eric Laurente0720872014-03-11 09:30:41 -07002174status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07002175 audio_io_handle_t io,
2176 uint32_t strategy,
2177 int session,
2178 int id)
2179{
2180 ssize_t index = mOutputs.indexOfKey(io);
2181 if (index < 0) {
2182 index = mInputs.indexOfKey(io);
2183 if (index < 0) {
2184 ALOGW("registerEffect() unknown io %d", io);
2185 return INVALID_OPERATION;
2186 }
2187 }
François Gaffie45ed3b02015-03-19 10:35:14 +01002188 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07002189}
2190
Eric Laurentc75307b2015-03-17 15:29:32 -07002191bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2192{
Eric Laurent28d09f02016-03-08 10:43:05 -08002193 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08002194 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
2195 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002196 continue;
2197 }
2198 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2199 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002200 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002201}
2202
2203bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2204{
2205 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2206}
2207
Eric Laurente0720872014-03-11 09:30:41 -07002208bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002209{
2210 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002211 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002212 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002213 return true;
2214 }
2215 }
2216 return false;
2217}
2218
Eric Laurent275e8e92014-11-30 15:14:47 -08002219// Register a list of custom mixes with their attributes and format.
2220// When a mix is registered, corresponding input and output profiles are
2221// added to the remote submix hw module. The profile contains only the
2222// parameters (sampling rate, format...) specified by the mix.
2223// The corresponding input remote submix device is also connected.
2224//
2225// When a remote submix device is connected, the address is checked to select the
2226// appropriate profile and the corresponding input or output stream is opened.
2227//
2228// When capture starts, getInputForAttr() will:
2229// - 1 look for a mix matching the address passed in attribtutes tags if any
2230// - 2 if none found, getDeviceForInputSource() will:
2231// - 2.1 look for a mix matching the attributes source
2232// - 2.2 if none found, default to device selection by policy rules
2233// At this time, the corresponding output remote submix device is also connected
2234// and active playback use cases can be transferred to this mix if needed when reconnecting
2235// after AudioTracks are invalidated
2236//
2237// When playback starts, getOutputForAttr() will:
2238// - 1 look for a mix matching the address passed in attribtutes tags if any
2239// - 2 if none found, look for a mix matching the attributes usage
2240// - 3 if none found, default to device and output selection by policy rules.
2241
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07002242status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08002243{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002244 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2245 status_t res = NO_ERROR;
2246
2247 sp<HwModule> rSubmixModule;
2248 // examine each mix's route type
2249 for (size_t i = 0; i < mixes.size(); i++) {
2250 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2251 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2252 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002253 break;
2254 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002255 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2256 // Loop back through "remote submix"
2257 if (rSubmixModule == 0) {
2258 for (size_t j = 0; i < mHwModules.size(); j++) {
2259 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2260 && mHwModules[j]->mHandle != 0) {
2261 rSubmixModule = mHwModules[j];
2262 break;
2263 }
2264 }
2265 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002266
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002267 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002268
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002269 if (rSubmixModule == 0) {
2270 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2271 res = INVALID_OPERATION;
2272 break;
2273 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002274
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002275 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002276
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002277 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002278 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002279 res = INVALID_OPERATION;
2280 break;
2281 }
2282 audio_config_t outputConfig = mixes[i].mFormat;
2283 audio_config_t inputConfig = mixes[i].mFormat;
2284 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2285 // stereo and let audio flinger do the channel conversion if needed.
2286 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2287 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2288 rSubmixModule->addOutputProfile(address, &outputConfig,
2289 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2290 rSubmixModule->addInputProfile(address, &inputConfig,
2291 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002292
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002293 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2294 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2295 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2296 address.string(), "remote-submix");
2297 } else {
2298 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2299 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2300 address.string(), "remote-submix");
2301 }
2302 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002303 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002304 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002305 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2306 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002307
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002308 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002309 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2310 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2311 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2312 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2313 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2314 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002315 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2316 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002317 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2318 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002319 } else {
2320 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002321 }
2322 break;
2323 }
2324 }
2325
2326 if (res != NO_ERROR) {
2327 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002328 i, device, address.string());
2329 res = INVALID_OPERATION;
2330 break;
2331 } else if (!foundOutput) {
2332 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2333 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002334 res = INVALID_OPERATION;
2335 break;
2336 }
Eric Laurentc722f302014-12-10 11:21:49 -08002337 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002338 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002339 if (res != NO_ERROR) {
2340 unregisterPolicyMixes(mixes);
2341 }
2342 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002343}
2344
2345status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2346{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002347 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002348 status_t res = NO_ERROR;
2349 sp<HwModule> rSubmixModule;
2350 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002351 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002352 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002353
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002354 if (rSubmixModule == 0) {
2355 for (size_t j = 0; i < mHwModules.size(); j++) {
2356 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2357 && mHwModules[j]->mHandle != 0) {
2358 rSubmixModule = mHwModules[j];
2359 break;
2360 }
2361 }
2362 }
2363 if (rSubmixModule == 0) {
2364 res = INVALID_OPERATION;
2365 continue;
2366 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002367
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002368 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002369
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002370 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2371 res = INVALID_OPERATION;
2372 continue;
2373 }
2374
2375 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2376 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2377 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2378 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2379 address.string(), "remote-submix");
2380 }
2381 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2382 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2383 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2384 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2385 address.string(), "remote-submix");
2386 }
2387 rSubmixModule->removeOutputProfile(address);
2388 rSubmixModule->removeInputProfile(address);
2389
2390 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2391 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2392 res = INVALID_OPERATION;
2393 continue;
2394 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002395 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002396 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002397 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002398}
2399
Eric Laurente552edb2014-03-10 17:42:56 -07002400
Eric Laurente0720872014-03-11 09:30:41 -07002401status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002402{
2403 const size_t SIZE = 256;
2404 char buffer[SIZE];
2405 String8 result;
2406
2407 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2408 result.append(buffer);
2409
Eric Laurent87ffa392015-05-22 10:32:38 -07002410 snprintf(buffer, SIZE, " Primary Output: %d\n",
2411 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002412 result.append(buffer);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07002413 std::string stateLiteral;
2414 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
2415 snprintf(buffer, SIZE, " Phone state: %s\n", stateLiteral.c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002416 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002417 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002418 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002419 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002420 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002421 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002422 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002423 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002424 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002425 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002426 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002427 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002428 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002429 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002430 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002431 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2432 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2433 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002434 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2435 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002436 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2437 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002438
François Gaffie2110e042015-03-24 08:41:51 +01002439 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002440
François Gaffie112b0af2015-11-19 16:13:25 +01002441 mAvailableOutputDevices.dump(fd, String8("Available output"));
2442 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002443 mHwModules.dump(fd);
2444 mOutputs.dump(fd);
2445 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002446 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002447 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002448 mAudioPatches.dump(fd);
Mikhail Naganov44344b02016-12-13 11:21:02 -08002449 mPolicyMixes.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002450
2451 return NO_ERROR;
2452}
2453
2454// This function checks for the parameters which can be offloaded.
2455// This can be enhanced depending on the capability of the DSP and policy
2456// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002457bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002458{
2459 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002460 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002461 offloadInfo.sample_rate, offloadInfo.channel_mask,
2462 offloadInfo.format,
2463 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2464 offloadInfo.has_video);
2465
Andy Hung2ddee192015-12-18 17:34:44 -08002466 if (mMasterMono) {
2467 return false; // no offloading if mono is set.
2468 }
2469
Eric Laurente552edb2014-03-10 17:42:56 -07002470 // Check if offload has been disabled
2471 char propValue[PROPERTY_VALUE_MAX];
2472 if (property_get("audio.offload.disable", propValue, "0")) {
2473 if (atoi(propValue) != 0) {
2474 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2475 return false;
2476 }
2477 }
2478
2479 // Check if stream type is music, then only allow offload as of now.
2480 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2481 {
2482 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2483 return false;
2484 }
2485
2486 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002487 const bool allowOffloadWithVideo =
2488 property_get_bool("audio.offload.video", false /* default_value */);
2489 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002490 ALOGV("isOffloadSupported: has_video == true, returning false");
2491 return false;
2492 }
2493
2494 //If duration is less than minimum value defined in property, return false
2495 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2496 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2497 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2498 return false;
2499 }
2500 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2501 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2502 return false;
2503 }
2504
2505 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2506 // creating an offloaded track and tearing it down immediately after start when audioflinger
2507 // detects there is an active non offloadable effect.
2508 // FIXME: We should check the audio session here but we do not have it in this context.
2509 // This may prevent offloading in rare situations where effects are left active by apps
2510 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002511 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002512 return false;
2513 }
2514
2515 // See if there is a profile to support this.
2516 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002517 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002518 offloadInfo.sample_rate,
2519 offloadInfo.format,
2520 offloadInfo.channel_mask,
2521 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002522 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2523 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002524}
2525
Eric Laurent6a94d692014-05-20 11:18:06 -07002526status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2527 audio_port_type_t type,
2528 unsigned int *num_ports,
2529 struct audio_port *ports,
2530 unsigned int *generation)
2531{
2532 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2533 generation == NULL) {
2534 return BAD_VALUE;
2535 }
2536 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2537 if (ports == NULL) {
2538 *num_ports = 0;
2539 }
2540
2541 size_t portsWritten = 0;
2542 size_t portsMax = *num_ports;
2543 *num_ports = 0;
2544 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002545 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2546 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002547 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002548 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2549 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2550 continue;
2551 }
2552 if (portsWritten < portsMax) {
2553 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2554 }
2555 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002556 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002557 }
2558 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002559 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2560 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2561 continue;
2562 }
2563 if (portsWritten < portsMax) {
2564 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2565 }
2566 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002567 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002568 }
2569 }
2570 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2571 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2572 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2573 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2574 }
2575 *num_ports += mInputs.size();
2576 }
2577 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002578 size_t numOutputs = 0;
2579 for (size_t i = 0; i < mOutputs.size(); i++) {
2580 if (!mOutputs[i]->isDuplicated()) {
2581 numOutputs++;
2582 if (portsWritten < portsMax) {
2583 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2584 }
2585 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002586 }
Eric Laurent84c70242014-06-23 08:46:27 -07002587 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002588 }
2589 }
2590 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002591 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002592 return NO_ERROR;
2593}
2594
2595status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2596{
2597 return NO_ERROR;
2598}
2599
Eric Laurent6a94d692014-05-20 11:18:06 -07002600status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2601 audio_patch_handle_t *handle,
2602 uid_t uid)
2603{
2604 ALOGV("createAudioPatch()");
2605
2606 if (handle == NULL || patch == NULL) {
2607 return BAD_VALUE;
2608 }
2609 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2610
Eric Laurent874c42872014-08-08 15:13:39 -07002611 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2612 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2613 return BAD_VALUE;
2614 }
2615 // only one source per audio patch supported for now
2616 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002617 return INVALID_OPERATION;
2618 }
Eric Laurent874c42872014-08-08 15:13:39 -07002619
2620 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002621 return INVALID_OPERATION;
2622 }
Eric Laurent874c42872014-08-08 15:13:39 -07002623 for (size_t i = 0; i < patch->num_sinks; i++) {
2624 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2625 return INVALID_OPERATION;
2626 }
2627 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002628
2629 sp<AudioPatch> patchDesc;
2630 ssize_t index = mAudioPatches.indexOfKey(*handle);
2631
Eric Laurent6a94d692014-05-20 11:18:06 -07002632 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2633 patch->sources[0].role,
2634 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002635#if LOG_NDEBUG == 0
2636 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002637 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002638 patch->sinks[i].role,
2639 patch->sinks[i].type);
2640 }
2641#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002642
2643 if (index >= 0) {
2644 patchDesc = mAudioPatches.valueAt(index);
2645 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2646 mUidCached, patchDesc->mUid, uid);
2647 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2648 return INVALID_OPERATION;
2649 }
2650 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002651 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002652 }
2653
2654 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002655 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002656 if (outputDesc == NULL) {
2657 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2658 return BAD_VALUE;
2659 }
Eric Laurent84c70242014-06-23 08:46:27 -07002660 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2661 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002662 if (patchDesc != 0) {
2663 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2664 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2665 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2666 return BAD_VALUE;
2667 }
2668 }
Eric Laurent874c42872014-08-08 15:13:39 -07002669 DeviceVector devices;
2670 for (size_t i = 0; i < patch->num_sinks; i++) {
2671 // Only support mix to devices connection
2672 // TODO add support for mix to mix connection
2673 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2674 ALOGV("createAudioPatch() source mix but sink is not a device");
2675 return INVALID_OPERATION;
2676 }
2677 sp<DeviceDescriptor> devDesc =
2678 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2679 if (devDesc == 0) {
2680 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2681 return BAD_VALUE;
2682 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002683
François Gaffie53615e22015-03-19 09:24:12 +01002684 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002685 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002686 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002687 NULL, // updatedSamplingRate
2688 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002689 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002690 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002691 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002692 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002693 ALOGV("createAudioPatch() profile not supported for device %08x",
2694 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002695 return INVALID_OPERATION;
2696 }
2697 devices.add(devDesc);
2698 }
2699 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002700 return INVALID_OPERATION;
2701 }
Eric Laurent874c42872014-08-08 15:13:39 -07002702
Eric Laurent6a94d692014-05-20 11:18:06 -07002703 // TODO: reconfigure output format and channels here
2704 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002705 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002706 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002707 index = mAudioPatches.indexOfKey(*handle);
2708 if (index >= 0) {
2709 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2710 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2711 }
2712 patchDesc = mAudioPatches.valueAt(index);
2713 patchDesc->mUid = uid;
2714 ALOGV("createAudioPatch() success");
2715 } else {
2716 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2717 return INVALID_OPERATION;
2718 }
2719 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2720 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2721 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002722 // only one sink supported when connecting an input device to a mix
2723 if (patch->num_sinks > 1) {
2724 return INVALID_OPERATION;
2725 }
François Gaffie53615e22015-03-19 09:24:12 +01002726 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002727 if (inputDesc == NULL) {
2728 return BAD_VALUE;
2729 }
2730 if (patchDesc != 0) {
2731 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2732 return BAD_VALUE;
2733 }
2734 }
2735 sp<DeviceDescriptor> devDesc =
2736 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2737 if (devDesc == 0) {
2738 return BAD_VALUE;
2739 }
2740
François Gaffie53615e22015-03-19 09:24:12 +01002741 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002742 devDesc->mAddress,
2743 patch->sinks[0].sample_rate,
2744 NULL, /*updatedSampleRate*/
2745 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002746 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002747 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002748 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002749 // FIXME for the parameter type,
2750 // and the NONE
2751 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002752 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002753 return INVALID_OPERATION;
2754 }
2755 // TODO: reconfigure output format and channels here
2756 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002757 devDesc->type(), inputDesc->mIoHandle);
2758 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002759 index = mAudioPatches.indexOfKey(*handle);
2760 if (index >= 0) {
2761 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2762 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2763 }
2764 patchDesc = mAudioPatches.valueAt(index);
2765 patchDesc->mUid = uid;
2766 ALOGV("createAudioPatch() success");
2767 } else {
2768 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2769 return INVALID_OPERATION;
2770 }
2771 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2772 // device to device connection
2773 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002774 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002775 return BAD_VALUE;
2776 }
2777 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002778 sp<DeviceDescriptor> srcDeviceDesc =
2779 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002780 if (srcDeviceDesc == 0) {
2781 return BAD_VALUE;
2782 }
Eric Laurent874c42872014-08-08 15:13:39 -07002783
Eric Laurent6a94d692014-05-20 11:18:06 -07002784 //update source and sink with our own data as the data passed in the patch may
2785 // be incomplete.
2786 struct audio_patch newPatch = *patch;
2787 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002788
Eric Laurent874c42872014-08-08 15:13:39 -07002789 for (size_t i = 0; i < patch->num_sinks; i++) {
2790 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2791 ALOGV("createAudioPatch() source device but one sink is not a device");
2792 return INVALID_OPERATION;
2793 }
2794
2795 sp<DeviceDescriptor> sinkDeviceDesc =
2796 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2797 if (sinkDeviceDesc == 0) {
2798 return BAD_VALUE;
2799 }
2800 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2801
Eric Laurent3bcf8592015-04-03 12:13:24 -07002802 // create a software bridge in PatchPanel if:
2803 // - source and sink devices are on differnt HW modules OR
2804 // - audio HAL version is < 3.0
Eric Laurentfb66dd92016-01-28 18:32:03 -08002805 if (!srcDeviceDesc->hasSameHwModuleAs(sinkDeviceDesc) ||
Mikhail Naganov9ee05402016-10-13 15:58:17 -07002806 (srcDeviceDesc->mModule->getHalVersionMajor() < 3)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002807 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002808 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002809 return INVALID_OPERATION;
2810 }
Eric Laurent874c42872014-08-08 15:13:39 -07002811 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002812 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002813 // if the sink device is reachable via an opened output stream, request to go via
2814 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002815 audio_io_handle_t output = selectOutput(outputs,
2816 AUDIO_OUTPUT_FLAG_NONE,
2817 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002818 if (output != AUDIO_IO_HANDLE_NONE) {
2819 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2820 if (outputDesc->isDuplicated()) {
2821 return INVALID_OPERATION;
2822 }
2823 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002824 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002825 newPatch.num_sources = 2;
2826 }
Eric Laurent83b88082014-06-20 18:31:16 -07002827 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002828 }
2829 // TODO: check from routing capabilities in config file and other conflicting patches
2830
2831 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2832 if (index >= 0) {
2833 afPatchHandle = patchDesc->mAfPatchHandle;
2834 }
2835
2836 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2837 &afPatchHandle,
2838 0);
2839 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2840 status, afPatchHandle);
2841 if (status == NO_ERROR) {
2842 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002843 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002844 addAudioPatch(patchDesc->mHandle, patchDesc);
2845 } else {
2846 patchDesc->mPatch = newPatch;
2847 }
2848 patchDesc->mAfPatchHandle = afPatchHandle;
2849 *handle = patchDesc->mHandle;
2850 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002851 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002852 } else {
2853 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2854 status);
2855 return INVALID_OPERATION;
2856 }
2857 } else {
2858 return BAD_VALUE;
2859 }
2860 } else {
2861 return BAD_VALUE;
2862 }
2863 return NO_ERROR;
2864}
2865
2866status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2867 uid_t uid)
2868{
2869 ALOGV("releaseAudioPatch() patch %d", handle);
2870
2871 ssize_t index = mAudioPatches.indexOfKey(handle);
2872
2873 if (index < 0) {
2874 return BAD_VALUE;
2875 }
2876 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2877 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2878 mUidCached, patchDesc->mUid, uid);
2879 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2880 return INVALID_OPERATION;
2881 }
2882
2883 struct audio_patch *patch = &patchDesc->mPatch;
2884 patchDesc->mUid = mUidCached;
2885 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002886 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002887 if (outputDesc == NULL) {
2888 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2889 return BAD_VALUE;
2890 }
2891
Eric Laurentc75307b2015-03-17 15:29:32 -07002892 setOutputDevice(outputDesc,
2893 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002894 true,
2895 0,
2896 NULL);
2897 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2898 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002899 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002900 if (inputDesc == NULL) {
2901 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2902 return BAD_VALUE;
2903 }
2904 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08002905 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07002906 true,
2907 NULL);
2908 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002909 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2910 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2911 status, patchDesc->mAfPatchHandle);
2912 removeAudioPatch(patchDesc->mHandle);
2913 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002914 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002915 } else {
2916 return BAD_VALUE;
2917 }
2918 } else {
2919 return BAD_VALUE;
2920 }
2921 return NO_ERROR;
2922}
2923
2924status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2925 struct audio_patch *patches,
2926 unsigned int *generation)
2927{
François Gaffie53615e22015-03-19 09:24:12 +01002928 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002929 return BAD_VALUE;
2930 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002931 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002932 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002933}
2934
Eric Laurente1715a42014-05-20 11:30:42 -07002935status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002936{
Eric Laurente1715a42014-05-20 11:30:42 -07002937 ALOGV("setAudioPortConfig()");
2938
2939 if (config == NULL) {
2940 return BAD_VALUE;
2941 }
2942 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2943 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002944 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2945 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002946 }
2947
Eric Laurenta121f902014-06-03 13:32:54 -07002948 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002949 if (config->type == AUDIO_PORT_TYPE_MIX) {
2950 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002951 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002952 if (outputDesc == NULL) {
2953 return BAD_VALUE;
2954 }
Eric Laurent84c70242014-06-23 08:46:27 -07002955 ALOG_ASSERT(!outputDesc->isDuplicated(),
2956 "setAudioPortConfig() called on duplicated output %d",
2957 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002958 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002959 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002960 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002961 if (inputDesc == NULL) {
2962 return BAD_VALUE;
2963 }
Eric Laurenta121f902014-06-03 13:32:54 -07002964 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002965 } else {
2966 return BAD_VALUE;
2967 }
2968 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2969 sp<DeviceDescriptor> deviceDesc;
2970 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2971 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2972 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2973 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2974 } else {
2975 return BAD_VALUE;
2976 }
2977 if (deviceDesc == NULL) {
2978 return BAD_VALUE;
2979 }
Eric Laurenta121f902014-06-03 13:32:54 -07002980 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002981 } else {
2982 return BAD_VALUE;
2983 }
2984
Eric Laurenta121f902014-06-03 13:32:54 -07002985 struct audio_port_config backupConfig;
2986 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2987 if (status == NO_ERROR) {
2988 struct audio_port_config newConfig;
2989 audioPortConfig->toAudioPortConfig(&newConfig, config);
2990 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002991 }
Eric Laurenta121f902014-06-03 13:32:54 -07002992 if (status != NO_ERROR) {
2993 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002994 }
Eric Laurente1715a42014-05-20 11:30:42 -07002995
2996 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002997}
2998
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002999void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3000{
Eric Laurentd60560a2015-04-10 11:31:20 -07003001 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003002 clearAudioPatches(uid);
3003 clearSessionRoutes(uid);
3004}
3005
Eric Laurent6a94d692014-05-20 11:18:06 -07003006void AudioPolicyManager::clearAudioPatches(uid_t uid)
3007{
Eric Laurent0add0fd2014-12-04 18:58:14 -08003008 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003009 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3010 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08003011 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07003012 }
3013 }
3014}
3015
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003016void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
3017 audio_io_handle_t ouptutToSkip)
3018{
3019 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
3020 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
3021 for (size_t j = 0; j < mOutputs.size(); j++) {
3022 if (mOutputs.keyAt(j) == ouptutToSkip) {
3023 continue;
3024 }
3025 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3026 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
3027 continue;
3028 }
3029 // If the default device for this strategy is on another output mix,
3030 // invalidate all tracks in this strategy to force re connection.
3031 // Otherwise select new device on the output mix.
3032 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08003033 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003034 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3035 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
3036 }
3037 }
3038 } else {
3039 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
3040 setOutputDevice(outputDesc, newDevice, false);
3041 }
3042 }
3043}
3044
3045void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3046{
3047 // remove output routes associated with this uid
3048 SortedVector<routing_strategy> affectedStrategies;
3049 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
3050 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
3051 if (route->mUid == uid) {
3052 mOutputRoutes.removeItemsAt(i);
3053 if (route->mDeviceDescriptor != 0) {
3054 affectedStrategies.add(getStrategy(route->mStreamType));
3055 }
3056 }
3057 }
3058 // reroute outputs if necessary
3059 for (size_t i = 0; i < affectedStrategies.size(); i++) {
3060 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
3061 }
3062
3063 // remove input routes associated with this uid
3064 SortedVector<audio_source_t> affectedSources;
3065 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
3066 sp<SessionRoute> route = mInputRoutes.valueAt(i);
3067 if (route->mUid == uid) {
3068 mInputRoutes.removeItemsAt(i);
3069 if (route->mDeviceDescriptor != 0) {
3070 affectedSources.add(route->mSource);
3071 }
3072 }
3073 }
3074 // reroute inputs if necessary
3075 SortedVector<audio_io_handle_t> inputsToClose;
3076 for (size_t i = 0; i < mInputs.size(); i++) {
3077 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003078 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003079 inputsToClose.add(inputDesc->mIoHandle);
3080 }
3081 }
3082 for (size_t i = 0; i < inputsToClose.size(); i++) {
3083 closeInput(inputsToClose[i]);
3084 }
3085}
3086
Eric Laurentd60560a2015-04-10 11:31:20 -07003087void AudioPolicyManager::clearAudioSources(uid_t uid)
3088{
3089 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3090 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3091 if (sourceDesc->mUid == uid) {
3092 stopAudioSource(mAudioSources.keyAt(i));
3093 }
3094 }
3095}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003096
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003097status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3098 audio_io_handle_t *ioHandle,
3099 audio_devices_t *device)
3100{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08003101 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3102 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08003103 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003104
François Gaffiedf372692015-03-19 10:43:27 +01003105 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003106}
3107
Eric Laurentd60560a2015-04-10 11:31:20 -07003108status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3109 const audio_attributes_t *attributes,
Glenn Kasten559d4392016-03-29 13:42:57 -07003110 audio_patch_handle_t *handle,
Eric Laurentd60560a2015-04-10 11:31:20 -07003111 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07003112{
Eric Laurentd60560a2015-04-10 11:31:20 -07003113 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
3114 if (source == NULL || attributes == NULL || handle == NULL) {
3115 return BAD_VALUE;
3116 }
3117
Glenn Kasten559d4392016-03-29 13:42:57 -07003118 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurentd60560a2015-04-10 11:31:20 -07003119
3120 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3121 source->type != AUDIO_PORT_TYPE_DEVICE) {
3122 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
3123 return INVALID_OPERATION;
3124 }
3125
3126 sp<DeviceDescriptor> srcDeviceDesc =
3127 mAvailableInputDevices.getDevice(source->ext.device.type,
3128 String8(source->ext.device.address));
3129 if (srcDeviceDesc == 0) {
3130 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3131 return BAD_VALUE;
3132 }
3133 sp<AudioSourceDescriptor> sourceDesc =
3134 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
3135
3136 struct audio_patch dummyPatch;
3137 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3138 sourceDesc->mPatchDesc = patchDesc;
3139
3140 status_t status = connectAudioSource(sourceDesc);
3141 if (status == NO_ERROR) {
3142 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
3143 *handle = sourceDesc->getHandle();
3144 }
3145 return status;
3146}
3147
3148status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3149{
3150 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3151
3152 // make sure we only have one patch per source.
3153 disconnectAudioSource(sourceDesc);
3154
3155 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08003156 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003157 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
3158
3159 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
3160 sp<DeviceDescriptor> sinkDeviceDesc =
3161 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
3162
3163 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3164 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
3165
3166 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
3167 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
Mikhail Naganov9ee05402016-10-13 15:58:17 -07003168 srcDeviceDesc->getAudioPort()->mModule->getHalVersionMajor() >= 3 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07003169 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
3170 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
3171 // create patch between src device and output device
3172 // create Hwoutput and add to mHwOutputs
3173 } else {
3174 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
3175 audio_io_handle_t output =
3176 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
3177 if (output == AUDIO_IO_HANDLE_NONE) {
3178 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
3179 return INVALID_OPERATION;
3180 }
3181 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3182 if (outputDesc->isDuplicated()) {
3183 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
3184 return INVALID_OPERATION;
3185 }
3186 // create a special patch with no sink and two sources:
3187 // - the second source indicates to PatchPanel through which output mix this patch should
3188 // be connected as well as the stream type for volume control
3189 // - the sink is defined by whatever output device is currently selected for the output
3190 // though which this patch is routed.
3191 patch->num_sinks = 0;
3192 patch->num_sources = 2;
3193 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
3194 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
3195 patch->sources[1].ext.mix.usecase.stream = stream;
3196 status_t status = mpClientInterface->createAudioPatch(patch,
3197 &afPatchHandle,
3198 0);
3199 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3200 status, afPatchHandle);
3201 if (status != NO_ERROR) {
3202 ALOGW("%s patch panel could not connect device patch, error %d",
3203 __FUNCTION__, status);
3204 return INVALID_OPERATION;
3205 }
3206 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003207 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003208
3209 if (status != NO_ERROR) {
3210 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3211 return status;
3212 }
3213 sourceDesc->mSwOutput = outputDesc;
3214 if (delayMs != 0) {
3215 usleep(delayMs * 1000);
3216 }
3217 }
3218
3219 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3220 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3221
3222 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003223}
3224
Glenn Kasten559d4392016-03-29 13:42:57 -07003225status_t AudioPolicyManager::stopAudioSource(audio_patch_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003226{
Eric Laurentd60560a2015-04-10 11:31:20 -07003227 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3228 ALOGV("%s handle %d", __FUNCTION__, handle);
3229 if (sourceDesc == 0) {
3230 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3231 return BAD_VALUE;
3232 }
3233 status_t status = disconnectAudioSource(sourceDesc);
3234
3235 mAudioSources.removeItem(handle);
3236 return status;
3237}
3238
Andy Hung2ddee192015-12-18 17:34:44 -08003239status_t AudioPolicyManager::setMasterMono(bool mono)
3240{
3241 if (mMasterMono == mono) {
3242 return NO_ERROR;
3243 }
3244 mMasterMono = mono;
3245 // if enabling mono we close all offloaded devices, which will invalidate the
3246 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3247 // for recreating the new AudioTrack as non-offloaded PCM.
3248 //
3249 // If disabling mono, we leave all tracks as is: we don't know which clients
3250 // and tracks are able to be recreated as offloaded. The next "song" should
3251 // play back offloaded.
3252 if (mMasterMono) {
3253 Vector<audio_io_handle_t> offloaded;
3254 for (size_t i = 0; i < mOutputs.size(); ++i) {
3255 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3256 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3257 offloaded.push(desc->mIoHandle);
3258 }
3259 }
3260 for (size_t i = 0; i < offloaded.size(); ++i) {
3261 closeOutput(offloaded[i]);
3262 }
3263 }
3264 // update master mono for all remaining outputs
3265 for (size_t i = 0; i < mOutputs.size(); ++i) {
3266 updateMono(mOutputs.keyAt(i));
3267 }
3268 return NO_ERROR;
3269}
3270
3271status_t AudioPolicyManager::getMasterMono(bool *mono)
3272{
3273 *mono = mMasterMono;
3274 return NO_ERROR;
3275}
3276
Eric Laurentd60560a2015-04-10 11:31:20 -07003277status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3278{
3279 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3280
3281 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3282 if (patchDesc == 0) {
3283 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3284 sourceDesc->mPatchDesc->mHandle);
3285 return BAD_VALUE;
3286 }
3287 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3288
Eric Laurent28d09f02016-03-08 10:43:05 -08003289 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003290 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3291 if (swOutputDesc != 0) {
3292 stopSource(swOutputDesc, stream, false);
3293 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3294 } else {
3295 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3296 if (hwOutputDesc != 0) {
3297 // release patch between src device and output device
3298 // close Hwoutput and remove from mHwOutputs
3299 } else {
3300 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3301 }
3302 }
3303 return NO_ERROR;
3304}
3305
3306sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3307 audio_io_handle_t output, routing_strategy strategy)
3308{
3309 sp<AudioSourceDescriptor> source;
3310 for (size_t i = 0; i < mAudioSources.size(); i++) {
3311 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3312 routing_strategy sourceStrategy =
3313 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3314 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3315 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3316 source = sourceDesc;
3317 break;
3318 }
3319 }
3320 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003321}
3322
Eric Laurente552edb2014-03-10 17:42:56 -07003323// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003324// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003325// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003326uint32_t AudioPolicyManager::nextAudioPortGeneration()
3327{
3328 return android_atomic_inc(&mAudioPortGeneration);
3329}
3330
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003331#ifdef USE_XML_AUDIO_POLICY_CONF
3332// Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
3333static const char *kConfigLocationList[] =
3334 {"/odm/etc", "/vendor/etc", "/system/etc"};
3335static const int kConfigLocationListSize =
3336 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
3337
3338static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
3339 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
3340 status_t ret;
3341
3342 for (int i = 0; i < kConfigLocationListSize; i++) {
3343 PolicySerializer serializer;
3344 snprintf(audioPolicyXmlConfigFile,
3345 sizeof(audioPolicyXmlConfigFile),
3346 "%s/%s",
3347 kConfigLocationList[i],
3348 AUDIO_POLICY_XML_CONFIG_FILE_NAME);
3349 ret = serializer.deserialize(audioPolicyXmlConfigFile, config);
3350 if (ret == NO_ERROR) {
3351 break;
3352 }
3353 }
3354 return ret;
3355}
3356#endif
3357
Eric Laurente0720872014-03-11 09:30:41 -07003358AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003359 :
3360#ifdef AUDIO_POLICY_TEST
3361 Thread(false),
3362#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003363 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003364 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003365 mAudioPortGeneration(1),
3366 mBeaconMuteRefCount(0),
3367 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003368 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003369 mTtsOutputAvailable(false),
3370 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003371{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003372 mUidCached = getuid();
3373 mpClientInterface = clientInterface;
3374
3375 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3376 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3377 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3378 bool speakerDrcEnabled = false;
3379
3380#ifdef USE_XML_AUDIO_POLICY_CONF
3381 mVolumeCurves = new VolumeCurvesCollection();
3382 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3383 mDefaultOutputDevice, speakerDrcEnabled,
3384 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09003385 if (deserializeAudioPolicyXmlConfig(config) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01003386#else
3387 mVolumeCurves = new StreamDescriptorCollection();
3388 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3389 mDefaultOutputDevice, speakerDrcEnabled);
3390 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3391 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3392#endif
3393 ALOGE("could not load audio policy configuration file, setting defaults");
3394 config.setDefault();
3395 }
3396 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3397 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3398
3399 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003400 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3401 if (!engineInstance) {
3402 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3403 return;
3404 }
3405 // Retrieve the Policy Manager Interface
3406 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3407 if (mEngine == NULL) {
3408 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3409 return;
3410 }
3411 mEngine->setObserver(this);
3412 status_t status = mEngine->initCheck();
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07003413 (void) status;
François Gaffie2110e042015-03-24 08:41:51 +01003414 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3415
Eric Laurent3a4311c2014-03-17 12:00:47 -07003416 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003417 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003418 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3419 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003420 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003421 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003422 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003423 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003424 continue;
3425 }
3426 // open all output streams needed to access attached devices
3427 // except for direct output streams that are only opened when they are actually
3428 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003429 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003430 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3431 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003432 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003433
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003434 if (!outProfile->hasSupportedDevices()) {
3435 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003436 continue;
3437 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003438 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003439 mTtsOutputAvailable = true;
3440 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003441
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003442 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003443 continue;
3444 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003445 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003446 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3447 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003448 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003449 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003450 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003451 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003452 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003453 if ((profileType & outputDeviceTypes) == 0) {
3454 continue;
3455 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003456 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3457 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003458 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3459 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3460 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3461 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003462
3463 outputDesc->mDevice = profileType;
3464 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3465 config.sample_rate = outputDesc->mSamplingRate;
3466 config.channel_mask = outputDesc->mChannelMask;
3467 config.format = outputDesc->mFormat;
3468 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003469 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003470 &output,
3471 &config,
3472 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003473 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003474 &outputDesc->mLatency,
3475 outputDesc->mFlags);
3476
3477 if (status != NO_ERROR) {
3478 ALOGW("Cannot open output stream for device %08x on hw module %s",
3479 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003480 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003481 } else {
3482 outputDesc->mSamplingRate = config.sample_rate;
3483 outputDesc->mChannelMask = config.channel_mask;
3484 outputDesc->mFormat = config.format;
3485
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003486 for (size_t k = 0; k < supportedDevices.size(); k++) {
3487 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003488 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003489 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3490 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003491 }
3492 }
3493 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003494 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003495 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003496 }
3497 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003498 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003499 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003500 true,
3501 0,
3502 NULL,
3503 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003504 }
Eric Laurente552edb2014-03-10 17:42:56 -07003505 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003506 // open input streams needed to access attached devices to validate
3507 // mAvailableInputDevices list
3508 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3509 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003510 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003511
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003512 if (!inProfile->hasSupportedDevices()) {
3513 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003514 continue;
3515 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003516 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003517 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003518 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3519
Eric Laurentd78f1532014-09-16 16:38:20 -07003520 if ((profileType & inputDeviceTypes) == 0) {
3521 continue;
3522 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003523 sp<AudioInputDescriptor> inputDesc =
3524 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003525
Eric Laurentd78f1532014-09-16 16:38:20 -07003526 inputDesc->mDevice = profileType;
3527
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003528 // find the address
3529 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3530 // the inputs vector must be of size 1, but we don't want to crash here
3531 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3532 : String8("");
3533 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3534 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3535
Eric Laurentd78f1532014-09-16 16:38:20 -07003536 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3537 config.sample_rate = inputDesc->mSamplingRate;
3538 config.channel_mask = inputDesc->mChannelMask;
3539 config.format = inputDesc->mFormat;
3540 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003541 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003542 &input,
3543 &config,
3544 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003545 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003546 AUDIO_SOURCE_MIC,
3547 AUDIO_INPUT_FLAG_NONE);
3548
3549 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003550 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3551 for (size_t k = 0; k < supportedDevices.size(); k++) {
3552 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003553 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003554 if (index >= 0) {
3555 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3556 if (!devDesc->isAttached()) {
3557 devDesc->attach(mHwModules[i]);
3558 devDesc->importAudioPort(inProfile);
3559 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003560 }
3561 }
3562 mpClientInterface->closeInput(input);
3563 } else {
3564 ALOGW("Cannot open input stream for device %08x on hw module %s",
3565 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003566 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003567 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003568 }
3569 }
3570 // make sure all attached devices have been allocated a unique ID
3571 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003572 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003573 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003574 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3575 continue;
3576 }
François Gaffie2110e042015-03-24 08:41:51 +01003577 // The device is now validated and can be appended to the available devices of the engine
3578 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3579 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003580 i++;
3581 }
3582 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003583 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003584 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003585 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3586 continue;
3587 }
François Gaffie2110e042015-03-24 08:41:51 +01003588 // The device is now validated and can be appended to the available devices of the engine
3589 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3590 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003591 i++;
3592 }
3593 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003594 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003595 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003596 }
Eric Laurente552edb2014-03-10 17:42:56 -07003597
3598 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3599
3600 updateDevicesAndOutputs();
3601
3602#ifdef AUDIO_POLICY_TEST
3603 if (mPrimaryOutput != 0) {
3604 AudioParameter outputCmd = AudioParameter();
3605 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003606 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003607
3608 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3609 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003610 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3611 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003612 mTestLatencyMs = 0;
3613 mCurOutput = 0;
3614 mDirectOutput = false;
3615 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3616 mTestOutputs[i] = 0;
3617 }
3618
3619 const size_t SIZE = 256;
3620 char buffer[SIZE];
3621 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3622 run(buffer, ANDROID_PRIORITY_AUDIO);
3623 }
3624#endif //AUDIO_POLICY_TEST
3625}
3626
Eric Laurente0720872014-03-11 09:30:41 -07003627AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003628{
3629#ifdef AUDIO_POLICY_TEST
3630 exit();
3631#endif //AUDIO_POLICY_TEST
3632 for (size_t i = 0; i < mOutputs.size(); i++) {
3633 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003634 }
3635 for (size_t i = 0; i < mInputs.size(); i++) {
3636 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003637 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003638 mAvailableOutputDevices.clear();
3639 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003640 mOutputs.clear();
3641 mInputs.clear();
3642 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003643}
3644
Eric Laurente0720872014-03-11 09:30:41 -07003645status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003646{
Eric Laurent87ffa392015-05-22 10:32:38 -07003647 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003648}
3649
3650#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003651bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003652{
3653 ALOGV("entering threadLoop()");
3654 while (!exitPending())
3655 {
3656 String8 command;
3657 int valueInt;
3658 String8 value;
3659
3660 Mutex::Autolock _l(mLock);
3661 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3662
3663 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3664 AudioParameter param = AudioParameter(command);
3665
3666 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3667 valueInt != 0) {
3668 ALOGV("Test command %s received", command.string());
3669 String8 target;
3670 if (param.get(String8("target"), target) != NO_ERROR) {
3671 target = "Manager";
3672 }
3673 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3674 param.remove(String8("test_cmd_policy_output"));
3675 mCurOutput = valueInt;
3676 }
3677 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3678 param.remove(String8("test_cmd_policy_direct"));
3679 if (value == "false") {
3680 mDirectOutput = false;
3681 } else if (value == "true") {
3682 mDirectOutput = true;
3683 }
3684 }
3685 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3686 param.remove(String8("test_cmd_policy_input"));
3687 mTestInput = valueInt;
3688 }
3689
3690 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3691 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003692 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003693 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003694 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003695 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003696 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003697 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003698 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003699 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003700 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003701 if (target == "Manager") {
3702 mTestFormat = format;
3703 } else if (mTestOutputs[mCurOutput] != 0) {
3704 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003705 outputParam.addInt(String8(AudioParameter::keyStreamSupportedFormats), format);
Eric Laurente552edb2014-03-10 17:42:56 -07003706 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3707 }
3708 }
3709 }
3710 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3711 param.remove(String8("test_cmd_policy_channels"));
3712 int channels = 0;
3713
3714 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003715 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003716 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003717 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003718 }
3719 if (channels != 0) {
3720 if (target == "Manager") {
3721 mTestChannels = channels;
3722 } else if (mTestOutputs[mCurOutput] != 0) {
3723 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003724 outputParam.addInt(String8(AudioParameter::keyStreamSupportedChannels), channels);
Eric Laurente552edb2014-03-10 17:42:56 -07003725 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3726 }
3727 }
3728 }
3729 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3730 param.remove(String8("test_cmd_policy_sampleRate"));
3731 if (valueInt >= 0 && valueInt <= 96000) {
3732 int samplingRate = valueInt;
3733 if (target == "Manager") {
3734 mTestSamplingRate = samplingRate;
3735 } else if (mTestOutputs[mCurOutput] != 0) {
3736 AudioParameter outputParam = AudioParameter();
Mikhail Naganov388360c2016-10-17 17:09:41 -07003737 outputParam.addInt(String8(AudioParameter::keyStreamSupportedSamplingRates), samplingRate);
Eric Laurente552edb2014-03-10 17:42:56 -07003738 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3739 }
3740 }
3741 }
3742
3743 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3744 param.remove(String8("test_cmd_policy_reopen"));
3745
Eric Laurentc75307b2015-03-17 15:29:32 -07003746 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003747
Eric Laurentc75307b2015-03-17 15:29:32 -07003748 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003749
Eric Laurentc75307b2015-03-17 15:29:32 -07003750 removeOutput(mPrimaryOutput->mIoHandle);
3751 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3752 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003753 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003754 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3755 config.sample_rate = outputDesc->mSamplingRate;
3756 config.channel_mask = outputDesc->mChannelMask;
3757 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003758 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003759 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003760 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003761 &config,
3762 &outputDesc->mDevice,
3763 String8(""),
3764 &outputDesc->mLatency,
3765 outputDesc->mFlags);
3766 if (status != NO_ERROR) {
3767 ALOGE("Failed to reopen hardware output stream, "
3768 "samplingRate: %d, format %d, channels %d",
3769 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003770 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003771 outputDesc->mSamplingRate = config.sample_rate;
3772 outputDesc->mChannelMask = config.channel_mask;
3773 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003774 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003775 AudioParameter outputCmd = AudioParameter();
3776 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003777 mpClientInterface->setParameters(handle, outputCmd.toString());
3778 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003779 }
3780 }
3781
3782
3783 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3784 }
3785 }
3786 return false;
3787}
3788
Eric Laurente0720872014-03-11 09:30:41 -07003789void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003790{
3791 {
3792 AutoMutex _l(mLock);
3793 requestExit();
3794 mWaitWorkCV.signal();
3795 }
3796 requestExitAndWait();
3797}
3798
Eric Laurente0720872014-03-11 09:30:41 -07003799int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003800{
3801 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3802 if (output == mTestOutputs[i]) return i;
3803 }
3804 return 0;
3805}
3806#endif //AUDIO_POLICY_TEST
3807
3808// ---
3809
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003810void AudioPolicyManager::addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003811{
François Gaffie98cc1912015-03-18 17:52:40 +01003812 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003813 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003814 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003815 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003816}
3817
François Gaffie53615e22015-03-19 09:24:12 +01003818void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3819{
3820 mOutputs.removeItem(output);
3821}
3822
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003823void AudioPolicyManager::addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003824{
François Gaffie98cc1912015-03-18 17:52:40 +01003825 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003826 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003827 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003828}
Eric Laurente552edb2014-03-10 17:42:56 -07003829
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003830void AudioPolicyManager::findIoHandlesByAddress(const sp<SwAudioOutputDescriptor>& desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003831 const audio_devices_t device /*in*/,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003832 const String8& address /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003833 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003834 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003835 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003836 if (devDesc != 0) {
3837 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3838 desc->mIoHandle, address.string());
3839 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003840 }
3841}
3842
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003843status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003844 audio_policy_dev_state_t state,
3845 SortedVector<audio_io_handle_t>& outputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003846 const String8& address)
Eric Laurente552edb2014-03-10 17:42:56 -07003847{
François Gaffie53615e22015-03-19 09:24:12 +01003848 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003849 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003850
3851 if (audio_device_is_digital(device)) {
3852 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003853 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003854 }
Eric Laurente552edb2014-03-10 17:42:56 -07003855
Eric Laurent3b73df72014-03-11 09:06:29 -07003856 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003857 // first list already open outputs that can be routed to this device
3858 for (size_t i = 0; i < mOutputs.size(); i++) {
3859 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003860 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003861 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003862 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3863 outputs.add(mOutputs.keyAt(i));
3864 } else {
3865 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003866 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003867 }
Eric Laurente552edb2014-03-10 17:42:56 -07003868 }
3869 }
3870 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003871 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003872 for (size_t i = 0; i < mHwModules.size(); i++)
3873 {
3874 if (mHwModules[i]->mHandle == 0) {
3875 continue;
3876 }
3877 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3878 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003879 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003880 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003881 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003882 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003883 profiles.add(profile);
3884 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3885 }
Eric Laurente552edb2014-03-10 17:42:56 -07003886 }
3887 }
3888 }
3889
Eric Laurent7b279bb2015-12-14 10:18:23 -08003890 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003891
Eric Laurente552edb2014-03-10 17:42:56 -07003892 if (profiles.isEmpty() && outputs.isEmpty()) {
3893 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3894 return BAD_VALUE;
3895 }
3896
3897 // open outputs for matching profiles if needed. Direct outputs are also opened to
3898 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3899 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003900 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003901
3902 // nothing to do if one output is already opened for this profile
3903 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003904 for (j = 0; j < outputs.size(); j++) {
3905 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003906 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003907 // matching profile: save the sample rates, format and channel masks supported
3908 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003909 if (audio_device_is_digital(device)) {
3910 devDesc->importAudioPort(profile);
3911 }
Eric Laurente552edb2014-03-10 17:42:56 -07003912 break;
3913 }
3914 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003915 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003916 continue;
3917 }
3918
Eric Laurent83b88082014-06-20 18:31:16 -07003919 ALOGV("opening output for device %08x with params %s profile %p",
3920 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003921 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003922 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003923 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3924 config.sample_rate = desc->mSamplingRate;
3925 config.channel_mask = desc->mChannelMask;
3926 config.format = desc->mFormat;
3927 config.offload_info.sample_rate = desc->mSamplingRate;
3928 config.offload_info.channel_mask = desc->mChannelMask;
3929 config.offload_info.format = desc->mFormat;
3930 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003931 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003932 &output,
3933 &config,
3934 &desc->mDevice,
3935 address,
3936 &desc->mLatency,
3937 desc->mFlags);
3938 if (status == NO_ERROR) {
3939 desc->mSamplingRate = config.sample_rate;
3940 desc->mChannelMask = config.channel_mask;
3941 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003942
Eric Laurentd4692962014-05-05 18:13:44 -07003943 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003944 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003945 char *param = audio_device_address_to_parameter(device, address);
3946 mpClientInterface->setParameters(output, String8(param));
3947 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003948 }
Phil Burk00eeb322016-03-31 12:41:00 -07003949 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003950 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003951 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003952 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003953 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003954 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003955 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003956 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003957 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003958 config.offload_info.sample_rate = config.sample_rate;
3959 config.offload_info.channel_mask = config.channel_mask;
3960 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003961 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003962 &output,
3963 &config,
3964 &desc->mDevice,
3965 address,
3966 &desc->mLatency,
3967 desc->mFlags);
3968 if (status == NO_ERROR) {
3969 desc->mSamplingRate = config.sample_rate;
3970 desc->mChannelMask = config.channel_mask;
3971 desc->mFormat = config.format;
3972 } else {
3973 output = AUDIO_IO_HANDLE_NONE;
3974 }
Eric Laurentd4692962014-05-05 18:13:44 -07003975 }
3976
Eric Laurentcf2c0212014-07-25 16:20:43 -07003977 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003978 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003979 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003980 sp<AudioPolicyMix> policyMix;
3981 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003982 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3983 address.string());
3984 }
François Gaffie036e1e92015-03-19 10:16:24 +01003985 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003986 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003987
Eric Laurent87ffa392015-05-22 10:32:38 -07003988 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3989 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003990 // no duplicated output for direct outputs and
3991 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003992 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003993
Eric Laurentd4692962014-05-05 18:13:44 -07003994 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003995 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003996
Eric Laurentd4692962014-05-05 18:13:44 -07003997 //TODO: configure audio effect output stage here
3998
3999 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07004000 duplicatedOutput =
4001 mpClientInterface->openDuplicateOutput(output,
4002 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004003 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004004 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07004005 sp<SwAudioOutputDescriptor> dupOutputDesc =
4006 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4007 dupOutputDesc->mOutput1 = mPrimaryOutput;
4008 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07004009 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
4010 dupOutputDesc->mFormat = desc->mFormat;
4011 dupOutputDesc->mChannelMask = desc->mChannelMask;
4012 dupOutputDesc->mLatency = desc->mLatency;
4013 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07004014 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07004015 } else {
4016 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004017 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07004018 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004019 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004020 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07004021 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004022 }
Eric Laurente552edb2014-03-10 17:42:56 -07004023 }
4024 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004025 } else {
4026 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004027 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07004028 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07004029 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004030 profiles.removeAt(profile_index);
4031 profile_index--;
4032 } else {
4033 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07004034 // Load digital format info only for digital devices
4035 if (audio_device_is_digital(device)) {
4036 devDesc->importAudioPort(profile);
4037 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07004038
François Gaffie53615e22015-03-19 09:24:12 +01004039 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004040 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
4041 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07004042 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004043 NULL/*patch handle*/, address.string());
4044 }
Eric Laurente552edb2014-03-10 17:42:56 -07004045 ALOGV("checkOutputsForDevice(): adding output %d", output);
4046 }
4047 }
4048
4049 if (profiles.isEmpty()) {
4050 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
4051 return BAD_VALUE;
4052 }
Eric Laurentd4692962014-05-05 18:13:44 -07004053 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07004054 // check if one opened output is not needed any more after disconnecting one device
4055 for (size_t i = 0; i < mOutputs.size(); i++) {
4056 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004057 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004058 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01004059 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07004060 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08004061 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004062 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004063 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4064 mOutputs.keyAt(i));
4065 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004066 }
Eric Laurente552edb2014-03-10 17:42:56 -07004067 }
4068 }
Eric Laurentd4692962014-05-05 18:13:44 -07004069 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07004070 for (size_t i = 0; i < mHwModules.size(); i++)
4071 {
4072 if (mHwModules[i]->mHandle == 0) {
4073 continue;
4074 }
4075 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
4076 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004077 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004078 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004079 ALOGV("checkOutputsForDevice(): "
4080 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01004081 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07004082 }
4083 }
4084 }
4085 }
4086 return NO_ERROR;
4087}
4088
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004089status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01004090 audio_policy_dev_state_t state,
4091 SortedVector<audio_io_handle_t>& inputs,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004092 const String8& address)
Eric Laurentd4692962014-05-05 18:13:44 -07004093{
Paul McLean9080a4c2015-06-18 08:24:02 -07004094 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07004095 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07004096
4097 if (audio_device_is_digital(device)) {
4098 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08004099 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07004100 }
4101
Eric Laurentd4692962014-05-05 18:13:44 -07004102 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4103 // first list already open inputs that can be routed to this device
4104 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4105 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004106 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07004107 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
4108 inputs.add(mInputs.keyAt(input_index));
4109 }
4110 }
4111
4112 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07004113 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07004114 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
4115 {
4116 if (mHwModules[module_idx]->mHandle == 0) {
4117 continue;
4118 }
4119 for (size_t profile_index = 0;
4120 profile_index < mHwModules[module_idx]->mInputProfiles.size();
4121 profile_index++)
4122 {
Eric Laurent275e8e92014-11-30 15:14:47 -08004123 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
4124
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004125 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01004126 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004127 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004128 profiles.add(profile);
4129 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
4130 profile_index, module_idx);
4131 }
Eric Laurentd4692962014-05-05 18:13:44 -07004132 }
4133 }
4134 }
4135
4136 if (profiles.isEmpty() && inputs.isEmpty()) {
4137 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4138 return BAD_VALUE;
4139 }
4140
4141 // open inputs for matching profiles if needed. Direct inputs are also opened to
4142 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4143 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4144
Eric Laurent1c333e22014-05-20 10:48:17 -07004145 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07004146 // nothing to do if one input is already opened for this profile
4147 size_t input_index;
4148 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4149 desc = mInputs.valueAt(input_index);
4150 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07004151 if (audio_device_is_digital(device)) {
4152 devDesc->importAudioPort(profile);
4153 }
Eric Laurentd4692962014-05-05 18:13:44 -07004154 break;
4155 }
4156 }
4157 if (input_index != mInputs.size()) {
4158 continue;
4159 }
4160
4161 ALOGV("opening input for device 0x%X with params %s", device, address.string());
4162 desc = new AudioInputDescriptor(profile);
4163 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07004164 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4165 config.sample_rate = desc->mSamplingRate;
4166 config.channel_mask = desc->mChannelMask;
4167 config.format = desc->mFormat;
4168 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07004169 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07004170 &input,
4171 &config,
4172 &desc->mDevice,
4173 address,
4174 AUDIO_SOURCE_MIC,
4175 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07004176
Eric Laurentcf2c0212014-07-25 16:20:43 -07004177 if (status == NO_ERROR) {
4178 desc->mSamplingRate = config.sample_rate;
4179 desc->mChannelMask = config.channel_mask;
4180 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07004181
Eric Laurentd4692962014-05-05 18:13:44 -07004182 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07004183 char *param = audio_device_address_to_parameter(device, address);
4184 mpClientInterface->setParameters(input, String8(param));
4185 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07004186 }
Phil Burk00eeb322016-03-31 12:41:00 -07004187 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01004188 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07004189 ALOGW("checkInputsForDevice() direct input missing param");
4190 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07004191 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07004192 }
4193
4194 if (input != 0) {
4195 addInput(input, desc);
4196 }
4197 } // endif input != 0
4198
Eric Laurentcf2c0212014-07-25 16:20:43 -07004199 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07004200 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07004201 profiles.removeAt(profile_index);
4202 profile_index--;
4203 } else {
4204 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07004205 if (audio_device_is_digital(device)) {
4206 devDesc->importAudioPort(profile);
4207 }
Eric Laurentd4692962014-05-05 18:13:44 -07004208 ALOGV("checkInputsForDevice(): adding input %d", input);
4209 }
4210 } // end scan profiles
4211
4212 if (profiles.isEmpty()) {
4213 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
4214 return BAD_VALUE;
4215 }
4216 } else {
4217 // Disconnect
4218 // check if one opened input is not needed any more after disconnecting one device
4219 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
4220 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004221 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07004222 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
4223 mInputs.keyAt(input_index));
4224 inputs.add(mInputs.keyAt(input_index));
4225 }
4226 }
4227 // Clear any profiles associated with the disconnected device.
4228 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4229 if (mHwModules[module_index]->mHandle == 0) {
4230 continue;
4231 }
4232 for (size_t profile_index = 0;
4233 profile_index < mHwModules[module_index]->mInputProfiles.size();
4234 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004235 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004236 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004237 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004238 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004239 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004240 }
4241 }
4242 }
4243 } // end disconnect
4244
4245 return NO_ERROR;
4246}
4247
4248
Eric Laurente0720872014-03-11 09:30:41 -07004249void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004250{
4251 ALOGV("closeOutput(%d)", output);
4252
Eric Laurentc75307b2015-03-17 15:29:32 -07004253 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004254 if (outputDesc == NULL) {
4255 ALOGW("closeOutput() unknown output %d", output);
4256 return;
4257 }
François Gaffie036e1e92015-03-19 10:16:24 +01004258 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004259
Eric Laurente552edb2014-03-10 17:42:56 -07004260 // look for duplicated outputs connected to the output being removed.
4261 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004262 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004263 if (dupOutputDesc->isDuplicated() &&
4264 (dupOutputDesc->mOutput1 == outputDesc ||
4265 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004266 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004267 if (dupOutputDesc->mOutput1 == outputDesc) {
4268 outputDesc2 = dupOutputDesc->mOutput2;
4269 } else {
4270 outputDesc2 = dupOutputDesc->mOutput1;
4271 }
4272 // As all active tracks on duplicated output will be deleted,
4273 // and as they were also referenced on the other output, the reference
4274 // count for their stream type must be adjusted accordingly on
4275 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004276 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004277 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004278 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
4280 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4281 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4282
4283 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004284 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004285 }
4286 }
4287
Eric Laurent05b90f82014-08-27 15:32:29 -07004288 nextAudioPortGeneration();
4289
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004290 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004291 if (index >= 0) {
4292 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004293 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004294 mAudioPatches.removeItemsAt(index);
4295 mpClientInterface->onAudioPatchListUpdate();
4296 }
4297
Eric Laurente552edb2014-03-10 17:42:56 -07004298 AudioParameter param;
4299 param.add(String8("closing"), String8("true"));
4300 mpClientInterface->setParameters(output, param.toString());
4301
4302 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004303 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004304 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004305}
4306
4307void AudioPolicyManager::closeInput(audio_io_handle_t input)
4308{
4309 ALOGV("closeInput(%d)", input);
4310
4311 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4312 if (inputDesc == NULL) {
4313 ALOGW("closeInput() unknown input %d", input);
4314 return;
4315 }
4316
Eric Laurent6a94d692014-05-20 11:18:06 -07004317 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004318
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004319 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004320 if (index >= 0) {
4321 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
Glenn Kastenfcddb0b2016-07-08 17:19:25 -07004322 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07004323 mAudioPatches.removeItemsAt(index);
4324 mpClientInterface->onAudioPatchListUpdate();
4325 }
4326
4327 mpClientInterface->closeInput(input);
4328 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004329}
4330
Eric Laurentc75307b2015-03-17 15:29:32 -07004331SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4332 audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004333 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004334{
4335 SortedVector<audio_io_handle_t> outputs;
4336
4337 ALOGVV("getOutputsForDevice() device %04x", device);
4338 for (size_t i = 0; i < openOutputs.size(); i++) {
Eric Laurent37ddbb42016-08-10 16:19:14 -07004339 ALOGVV("output %zu isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004340 i, openOutputs.valueAt(i)->isDuplicated(),
4341 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004342 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4343 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4344 outputs.add(openOutputs.keyAt(i));
4345 }
4346 }
4347 return outputs;
4348}
4349
Eric Laurente0720872014-03-11 09:30:41 -07004350bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004351 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004352{
4353 if (outputs1.size() != outputs2.size()) {
4354 return false;
4355 }
4356 for (size_t i = 0; i < outputs1.size(); i++) {
4357 if (outputs1[i] != outputs2[i]) {
4358 return false;
4359 }
4360 }
4361 return true;
4362}
4363
Eric Laurente0720872014-03-11 09:30:41 -07004364void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004365{
4366 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4367 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4368 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4369 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4370
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004371 // also take into account external policy-related changes: add all outputs which are
4372 // associated with policies in the "before" and "after" output vectors
4373 ALOGVV("checkOutputForStrategy(): policy related outputs");
4374 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004375 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004376 if (desc != 0 && desc->mPolicyMix != NULL) {
4377 srcOutputs.add(desc->mIoHandle);
4378 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4379 }
4380 }
4381 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004382 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004383 if (desc != 0 && desc->mPolicyMix != NULL) {
4384 dstOutputs.add(desc->mIoHandle);
4385 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4386 }
4387 }
4388
Eric Laurente552edb2014-03-10 17:42:56 -07004389 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4390 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4391 strategy, srcOutputs[0], dstOutputs[0]);
4392 // mute strategy while moving tracks from one output to another
4393 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004394 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004395 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004396 setStrategyMute(strategy, true, desc);
4397 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004398 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004399 sp<AudioSourceDescriptor> source =
4400 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4401 if (source != 0){
4402 connectAudioSource(source);
4403 }
Eric Laurente552edb2014-03-10 17:42:56 -07004404 }
4405
4406 // Move effects associated to this strategy from previous output to new output
4407 if (strategy == STRATEGY_MEDIA) {
4408 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4409 SortedVector<audio_io_handle_t> moved;
4410 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004411 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4412 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4413 effectDesc->mIo != fxOutput) {
4414 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004415 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4416 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004417 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004418 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004419 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004420 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004421 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004422 }
4423 }
4424 }
4425 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004426 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004427 if (getStrategy((audio_stream_type_t)i) == strategy) {
4428 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004429 }
4430 }
4431 }
4432}
4433
Eric Laurente0720872014-03-11 09:30:41 -07004434void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004435{
François Gaffie2110e042015-03-24 08:41:51 +01004436 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004437 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004438 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004439 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004440 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004441 checkOutputForStrategy(STRATEGY_SONIFICATION);
4442 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004443 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004444 checkOutputForStrategy(STRATEGY_MEDIA);
4445 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004446 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004447}
4448
Eric Laurente0720872014-03-11 09:30:41 -07004449void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004450{
François Gaffie53615e22015-03-19 09:24:12 +01004451 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004452 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004453 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004454 return;
4455 }
4456
Eric Laurent3a4311c2014-03-17 12:00:47 -07004457 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004458 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4459 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4460 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurentf732e072016-08-03 19:30:28 -07004461
4462 // if suspended, restore A2DP output if:
4463 // ((SCO device is NOT connected) ||
4464 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
4465 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004466 //
Eric Laurentf732e072016-08-03 19:30:28 -07004467 // if not suspended, suspend A2DP output if:
4468 // (SCO device is connected) &&
4469 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
4470 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07004471 //
4472 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07004473 if (!isScoConnected ||
4474 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
4475 AUDIO_POLICY_FORCE_BT_SCO) &&
4476 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
4477 AUDIO_POLICY_FORCE_BT_SCO) &&
4478 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01004479 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004480
4481 mpClientInterface->restoreOutput(a2dpOutput);
4482 mA2dpSuspended = false;
4483 }
4484 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07004485 if (isScoConnected &&
4486 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
4487 AUDIO_POLICY_FORCE_BT_SCO) ||
4488 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
4489 AUDIO_POLICY_FORCE_BT_SCO) ||
4490 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01004491 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004492
4493 mpClientInterface->suspendOutput(a2dpOutput);
4494 mA2dpSuspended = true;
4495 }
4496 }
4497}
4498
Eric Laurentc75307b2015-03-17 15:29:32 -07004499audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4500 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004501{
4502 audio_devices_t device = AUDIO_DEVICE_NONE;
4503
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004504 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 if (index >= 0) {
4506 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4507 if (patchDesc->mUid != mUidCached) {
4508 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004509 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004510 return outputDesc->device();
4511 }
4512 }
4513
Eric Laurente552edb2014-03-10 17:42:56 -07004514 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004515 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004516 // use device for strategy enforced audible
4517 // 2: we are in call or the strategy phone is active on the output:
4518 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004519 // 3: the strategy for enforced audible is active but not enforced on the output:
4520 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004521 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004522 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004523 // 5: the strategy accessibility is active on the output:
4524 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004525 // 6: the strategy "respectful" sonification is active on the output:
4526 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004527 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004528 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004529 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004530 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004531 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004532 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004533 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004534 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004535 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4536 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004537 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004538 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004539 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004540 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004541 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004542 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004543 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4544 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004545 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004546 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004547 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004548 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004549 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004550 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004551 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004552 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004553 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004554 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004555 }
4556
Eric Laurent1c333e22014-05-20 10:48:17 -07004557 ALOGV("getNewOutputDevice() selected device %x", device);
4558 return device;
4559}
4560
Eric Laurentfb66dd92016-01-28 18:32:03 -08004561audio_devices_t AudioPolicyManager::getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07004562{
Eric Laurentfb66dd92016-01-28 18:32:03 -08004563 audio_devices_t device = AUDIO_DEVICE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004564
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004565 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004566 if (index >= 0) {
4567 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4568 if (patchDesc->mUid != mUidCached) {
4569 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004570 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004571 return inputDesc->mDevice;
4572 }
4573 }
4574
Eric Laurentfb66dd92016-01-28 18:32:03 -08004575 audio_source_t source = inputDesc->getHighestPrioritySource(true /*activeOnly*/);
4576 if (isInCall()) {
4577 device = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
4578 } else if (source != AUDIO_SOURCE_DEFAULT) {
4579 device = getDeviceAndMixForInputSource(source);
4580 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004581
Eric Laurente552edb2014-03-10 17:42:56 -07004582 return device;
4583}
4584
Eric Laurent794fde22016-03-11 09:50:45 -08004585bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4586 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08004587 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08004588}
4589
Eric Laurente0720872014-03-11 09:30:41 -07004590uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004591 return (uint32_t)getStrategy(stream);
4592}
4593
Eric Laurente0720872014-03-11 09:30:41 -07004594audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004595 // By checking the range of stream before calling getStrategy, we avoid
4596 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4597 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004598 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004599 return AUDIO_DEVICE_NONE;
4600 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004601 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004602 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4603 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004604 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004605 }
Eric Laurent794fde22016-03-11 09:50:45 -08004606 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004607 audio_devices_t curDevices =
Eric Laurent447a87b2016-07-07 17:32:10 -07004608 getDeviceForStrategy((routing_strategy)curStrategy, false /*fromCache*/);
Eric Laurent28d09f02016-03-08 10:43:05 -08004609 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4610 for (size_t i = 0; i < outputs.size(); i++) {
4611 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004612 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004613 curDevices |= outputDesc->device();
4614 }
4615 }
4616 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004617 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004618
4619 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4620 and doesn't really need to.*/
4621 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4622 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4623 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4624 }
Eric Laurente552edb2014-03-10 17:42:56 -07004625 return devices;
4626}
4627
François Gaffie2110e042015-03-24 08:41:51 +01004628routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4629{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004630 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004631 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004632}
4633
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004634uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4635 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004636 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4637 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4638 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004639 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4640 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4641 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004642 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004643 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004644}
4645
Eric Laurente0720872014-03-11 09:30:41 -07004646void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004647 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004648 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004649 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4650 updateDevicesAndOutputs();
4651 break;
4652 default:
4653 break;
4654 }
4655}
4656
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004657uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004658
4659 // skip beacon mute management if a dedicated TTS output is available
4660 if (mTtsOutputAvailable) {
4661 return 0;
4662 }
4663
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004664 switch(event) {
4665 case STARTING_OUTPUT:
4666 mBeaconMuteRefCount++;
4667 break;
4668 case STOPPING_OUTPUT:
4669 if (mBeaconMuteRefCount > 0) {
4670 mBeaconMuteRefCount--;
4671 }
4672 break;
4673 case STARTING_BEACON:
4674 mBeaconPlayingRefCount++;
4675 break;
4676 case STOPPING_BEACON:
4677 if (mBeaconPlayingRefCount > 0) {
4678 mBeaconPlayingRefCount--;
4679 }
4680 break;
4681 }
4682
4683 if (mBeaconMuteRefCount > 0) {
4684 // any playback causes beacon to be muted
4685 return setBeaconMute(true);
4686 } else {
4687 // no other playback: unmute when beacon starts playing, mute when it stops
4688 return setBeaconMute(mBeaconPlayingRefCount == 0);
4689 }
4690}
4691
4692uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4693 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4694 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4695 // keep track of muted state to avoid repeating mute/unmute operations
4696 if (mBeaconMuted != mute) {
4697 // mute/unmute AUDIO_STREAM_TTS on all outputs
4698 ALOGV("\t muting %d", mute);
4699 uint32_t maxLatency = 0;
4700 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004701 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004702 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004703 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004704 0 /*delay*/, AUDIO_DEVICE_NONE);
4705 const uint32_t latency = desc->latency() * 2;
4706 if (latency > maxLatency) {
4707 maxLatency = latency;
4708 }
4709 }
4710 mBeaconMuted = mute;
4711 return maxLatency;
4712 }
4713 return 0;
4714}
4715
Eric Laurente0720872014-03-11 09:30:41 -07004716audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004717 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004718{
Paul McLeanaa981192015-03-21 09:55:15 -07004719 // Routing
4720 // see if we have an explicit route
4721 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4722 // (getStrategy(stream)).
4723 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4724 // and activity count is non-zero
4725 // the device = the device from the descriptor in the RouteMap, and exit.
4726 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4727 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004728 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4729 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004730 return route->mDeviceDescriptor->type();
4731 }
4732 }
4733
Eric Laurente552edb2014-03-10 17:42:56 -07004734 if (fromCache) {
4735 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4736 strategy, mDeviceForStrategy[strategy]);
4737 return mDeviceForStrategy[strategy];
4738 }
François Gaffie2110e042015-03-24 08:41:51 +01004739 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004740}
4741
Eric Laurente0720872014-03-11 09:30:41 -07004742void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004743{
4744 for (int i = 0; i < NUM_STRATEGIES; i++) {
4745 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4746 }
4747 mPreviousOutputs = mOutputs;
4748}
4749
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004750uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004751 audio_devices_t prevDevice,
4752 uint32_t delayMs)
4753{
4754 // mute/unmute strategies using an incompatible device combination
4755 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4756 // if unmuting, unmute only after the specified delay
4757 if (outputDesc->isDuplicated()) {
4758 return 0;
4759 }
4760
4761 uint32_t muteWaitMs = 0;
4762 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004763 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004764
4765 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4766 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004767 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004768 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4769 bool doMute = false;
4770
4771 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4772 doMute = true;
4773 outputDesc->mStrategyMutedByDevice[i] = true;
4774 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4775 doMute = true;
4776 outputDesc->mStrategyMutedByDevice[i] = false;
4777 }
Eric Laurent99401132014-05-07 19:48:15 -07004778 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004779 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004780 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004781 // skip output if it does not share any device with current output
4782 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4783 == AUDIO_DEVICE_NONE) {
4784 continue;
4785 }
Eric Laurent37ddbb42016-08-10 16:19:14 -07004786 ALOGVV("checkDeviceMuteStrategies() %s strategy %zu (curDevice %04x)",
Eric Laurentc75307b2015-03-17 15:29:32 -07004787 mute ? "muting" : "unmuting", i, curDevice);
4788 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004789 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004790 if (mute) {
4791 // FIXME: should not need to double latency if volume could be applied
4792 // immediately by the audioflinger mixer. We must account for the delay
4793 // between now and the next time the audioflinger thread for this output
4794 // will process a buffer (which corresponds to one buffer size,
4795 // usually 1/2 or 1/4 of the latency).
4796 if (muteWaitMs < desc->latency() * 2) {
4797 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004798 }
4799 }
4800 }
4801 }
4802 }
4803 }
4804
Eric Laurent99401132014-05-07 19:48:15 -07004805 // temporary mute output if device selection changes to avoid volume bursts due to
4806 // different per device volumes
4807 if (outputDesc->isActive() && (device != prevDevice)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004808 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
4809 // temporary mute duration is conservatively set to 4 times the reported latency
4810 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
4811 if (muteWaitMs < tempMuteWaitMs) {
4812 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07004813 }
Eric Laurentdc462862016-07-19 12:29:53 -07004814
Eric Laurent99401132014-05-07 19:48:15 -07004815 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004816 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentdc462862016-07-19 12:29:53 -07004817 // make sure that we do not start the temporary mute period too early in case of
4818 // delayed device change
4819 setStrategyMute((routing_strategy)i, true, outputDesc, delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07004820 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurentdc462862016-07-19 12:29:53 -07004821 delayMs + tempMuteDurationMs, device);
Eric Laurent99401132014-05-07 19:48:15 -07004822 }
4823 }
4824 }
4825
Eric Laurente552edb2014-03-10 17:42:56 -07004826 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4827 if (muteWaitMs > delayMs) {
4828 muteWaitMs -= delayMs;
4829 usleep(muteWaitMs * 1000);
4830 return muteWaitMs;
4831 }
4832 return 0;
4833}
4834
Eric Laurentc75307b2015-03-17 15:29:32 -07004835uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004836 audio_devices_t device,
4837 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004838 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004839 audio_patch_handle_t *patchHandle,
4840 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004841{
Eric Laurentc75307b2015-03-17 15:29:32 -07004842 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004843 AudioParameter param;
4844 uint32_t muteWaitMs;
4845
4846 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004847 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4848 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004849 return muteWaitMs;
4850 }
4851 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4852 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004853 if ((device != AUDIO_DEVICE_NONE) &&
4854 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004855 return 0;
4856 }
4857
4858 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004859 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004860
4861 audio_devices_t prevDevice = outputDesc->mDevice;
4862
Paul McLeanaa981192015-03-21 09:55:15 -07004863 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004864
4865 if (device != AUDIO_DEVICE_NONE) {
4866 outputDesc->mDevice = device;
4867 }
4868 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4869
4870 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004871 // the requested device is AUDIO_DEVICE_NONE
4872 // OR the requested device is the same as current device
4873 // AND force is not specified
4874 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004875 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004876 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4877 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004878 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004879 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004880 return muteWaitMs;
4881 }
4882
4883 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004884
Eric Laurente552edb2014-03-10 17:42:56 -07004885 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004886 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004887 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004888 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004889 DeviceVector deviceList;
4890 if ((address == NULL) || (strlen(address) == 0)) {
4891 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4892 } else {
4893 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4894 }
4895
Eric Laurent1c333e22014-05-20 10:48:17 -07004896 if (!deviceList.isEmpty()) {
4897 struct audio_patch patch;
4898 outputDesc->toAudioPortConfig(&patch.sources[0]);
4899 patch.num_sources = 1;
4900 patch.num_sinks = 0;
4901 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4902 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004903 patch.num_sinks++;
4904 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004905 ssize_t index;
4906 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4907 index = mAudioPatches.indexOfKey(*patchHandle);
4908 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004909 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004910 }
4911 sp< AudioPatch> patchDesc;
4912 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4913 if (index >= 0) {
4914 patchDesc = mAudioPatches.valueAt(index);
4915 afPatchHandle = patchDesc->mAfPatchHandle;
4916 }
4917
Eric Laurent1c333e22014-05-20 10:48:17 -07004918 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 &afPatchHandle,
4920 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004921 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4922 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004924 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004926 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 addAudioPatch(patchDesc->mHandle, patchDesc);
4928 } else {
4929 patchDesc->mPatch = patch;
4930 }
4931 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 if (patchHandle) {
4933 *patchHandle = patchDesc->mHandle;
4934 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004935 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004937 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004938 }
4939 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004940
4941 // inform all input as well
4942 for (size_t i = 0; i < mInputs.size(); i++) {
4943 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004944 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004945 AudioParameter inputCmd = AudioParameter();
4946 ALOGV("%s: inform input %d of device:%d", __func__,
4947 inputDescriptor->mIoHandle, device);
4948 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4949 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4950 inputCmd.toString(),
4951 delayMs);
4952 }
4953 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004954 }
Eric Laurente552edb2014-03-10 17:42:56 -07004955
4956 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004957 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004958
4959 return muteWaitMs;
4960}
4961
Eric Laurentc75307b2015-03-17 15:29:32 -07004962status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 int delayMs,
4964 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004965{
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 ssize_t index;
4967 if (patchHandle) {
4968 index = mAudioPatches.indexOfKey(*patchHandle);
4969 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004970 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 }
4972 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004973 return INVALID_OPERATION;
4974 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4976 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004977 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004978 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 removeAudioPatch(patchDesc->mHandle);
4980 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004981 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004982 return status;
4983}
4984
4985status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4986 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 bool force,
4988 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004989{
4990 status_t status = NO_ERROR;
4991
Eric Laurent1f2f2232014-06-02 12:01:23 -07004992 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004993 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4994 inputDesc->mDevice = device;
4995
4996 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4997 if (!deviceList.isEmpty()) {
4998 struct audio_patch patch;
4999 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005000 // AUDIO_SOURCE_HOTWORD is for internal use only:
5001 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005002 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08005003 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005004 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5005 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005006 patch.num_sinks = 1;
5007 //only one input device for now
5008 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005009 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 ssize_t index;
5011 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5012 index = mAudioPatches.indexOfKey(*patchHandle);
5013 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005014 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 }
5016 sp< AudioPatch> patchDesc;
5017 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5018 if (index >= 0) {
5019 patchDesc = mAudioPatches.valueAt(index);
5020 afPatchHandle = patchDesc->mAfPatchHandle;
5021 }
5022
Eric Laurent1c333e22014-05-20 10:48:17 -07005023 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005025 0);
5026 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005028 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01005030 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005031 addAudioPatch(patchDesc->mHandle, patchDesc);
5032 } else {
5033 patchDesc->mPatch = patch;
5034 }
5035 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 if (patchHandle) {
5037 *patchHandle = patchDesc->mHandle;
5038 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005039 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005041 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005042 }
5043 }
5044 }
5045 return status;
5046}
5047
Eric Laurent6a94d692014-05-20 11:18:06 -07005048status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5049 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005050{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005051 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 ssize_t index;
5053 if (patchHandle) {
5054 index = mAudioPatches.indexOfKey(*patchHandle);
5055 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005056 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005057 }
5058 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005059 return INVALID_OPERATION;
5060 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005061 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5062 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005063 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07005064 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 removeAudioPatch(patchDesc->mHandle);
5066 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005067 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005068 return status;
5069}
5070
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08005071sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005072 const String8& address,
François Gaffie53615e22015-03-19 09:24:12 +01005073 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07005074 audio_format_t& format,
5075 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01005076 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005077{
5078 // Choose an input profile based on the requested capture parameters: select the first available
5079 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07005080 //
5081 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5082 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07005083
5084 for (size_t i = 0; i < mHwModules.size(); i++)
5085 {
5086 if (mHwModules[i]->mHandle == 0) {
5087 continue;
5088 }
5089 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5090 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005091 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005092 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005093 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005094 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07005095 format,
5096 &format /*updatedFormat*/,
5097 channelMask,
5098 &channelMask /*updatedChannelMask*/,
5099 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005100
Eric Laurente552edb2014-03-10 17:42:56 -07005101 return profile;
5102 }
5103 }
5104 }
5105 return NULL;
5106}
5107
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005108
5109audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01005110 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005111{
François Gaffie036e1e92015-03-19 10:16:24 +01005112 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
5113 audio_devices_t selectedDeviceFromMix =
5114 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08005115
François Gaffie036e1e92015-03-19 10:16:24 +01005116 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
5117 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005118 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005119 return getDeviceForInputSource(inputSource);
5120}
5121
5122audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5123{
Paul McLean466dc8e2015-04-17 13:15:36 -06005124 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
5125 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005126 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06005127 return route->mDeviceDescriptor->type();
5128 }
5129 }
5130
5131 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07005132}
5133
Eric Laurente0720872014-03-11 09:30:41 -07005134float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005135 int index,
5136 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005137{
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005138 float volumeDB = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07005139
5140 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5141 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5142 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5143 // the ringtone volume
5144 if ((stream == AUDIO_STREAM_ACCESSIBILITY)
5145 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState())
5146 && isStreamActive(AUDIO_STREAM_RING, 0)) {
5147 const float ringVolumeDB = computeVolume(AUDIO_STREAM_RING, index, device);
5148 return ringVolumeDB - 4 > volumeDB ? ringVolumeDB - 4 : volumeDB;
5149 }
5150
Eric Laurente552edb2014-03-10 17:42:56 -07005151 // if a headset is connected, apply the following rules to ring tones and notifications
5152 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005153 // - always attenuate notifications volume by 6dB
5154 // - attenuate ring tones volume by 6dB unless music is not playing and
5155 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07005156 // - if music is playing, always limit the volume to current music volume,
5157 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005158 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005159 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5160 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5161 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5162 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5163 ((stream_strategy == STRATEGY_SONIFICATION)
5164 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005165 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005166 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01005167 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01005168 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005169 // when the phone is ringing we must consider that music could have been paused just before
5170 // by the music application and behave as if music was active if the last music track was
5171 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005172 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005173 mLimitRingtoneVolume) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005174 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005175 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005176 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005177 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
5178 musicDevice),
5179 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07005180 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5181 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005182 if (volumeDB > minVolDB) {
5183 volumeDB = minVolDB;
Eric Laurentffbc80f2015-03-18 18:30:19 -07005184 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07005185 }
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005186 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5187 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5188 // on A2DP, also ensure notification volume is not too low compared to media when
5189 // intended to be played
5190 if ((volumeDB > -96.0f) &&
5191 (musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDB)) {
5192 ALOGV("computeVolume increasing volume for stream=%d device=0x%X from %f to %f",
5193 stream, device,
5194 volumeDB, musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5195 volumeDB = musicVolDB - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5196 }
5197 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07005198 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5199 stream_strategy != STRATEGY_SONIFICATION) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005200 volumeDB += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07005201 }
5202 }
5203
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07005204 return volumeDB;
Eric Laurente552edb2014-03-10 17:42:56 -07005205}
5206
Eric Laurente0720872014-03-11 09:30:41 -07005207status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005208 int index,
5209 const sp<AudioOutputDescriptor>& outputDesc,
5210 audio_devices_t device,
5211 int delayMs,
5212 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005213{
Eric Laurente552edb2014-03-10 17:42:56 -07005214 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07005215 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005216 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07005217 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005218 return NO_ERROR;
5219 }
François Gaffie2110e042015-03-24 08:41:51 +01005220 audio_policy_forced_cfg_t forceUseForComm =
5221 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07005222 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01005223 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5224 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005225 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01005226 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07005227 return INVALID_OPERATION;
5228 }
5229
Eric Laurentc75307b2015-03-17 15:29:32 -07005230 if (device == AUDIO_DEVICE_NONE) {
5231 device = outputDesc->device();
5232 }
Eric Laurent275e8e92014-11-30 15:14:47 -08005233
Eric Laurentffbc80f2015-03-18 18:30:19 -07005234 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07005235 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07005236 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08005237 }
Eric Laurentc75307b2015-03-17 15:29:32 -07005238
Eric Laurentffbc80f2015-03-18 18:30:19 -07005239 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07005240
Eric Laurent3b73df72014-03-11 09:06:29 -07005241 if (stream == AUDIO_STREAM_VOICE_CALL ||
5242 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005243 float voiceVolume;
5244 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005245 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005246 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005247 } else {
5248 voiceVolume = 1.0;
5249 }
5250
Eric Laurent18fba842016-03-31 14:41:26 -07005251 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07005252 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5253 mLastVoiceVolume = voiceVolume;
5254 }
5255 }
5256
5257 return NO_ERROR;
5258}
5259
Eric Laurentc75307b2015-03-17 15:29:32 -07005260void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5261 audio_devices_t device,
5262 int delayMs,
5263 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005264{
Eric Laurentc75307b2015-03-17 15:29:32 -07005265 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005266
Eric Laurent794fde22016-03-11 09:50:45 -08005267 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005268 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005269 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005270 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005271 device,
5272 delayMs,
5273 force);
5274 }
5275}
5276
Eric Laurente0720872014-03-11 09:30:41 -07005277void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005278 bool on,
5279 const sp<AudioOutputDescriptor>& outputDesc,
5280 int delayMs,
5281 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005282{
Eric Laurent72249d52015-06-08 11:12:15 -07005283 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5284 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005285 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005286 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005287 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005288 }
5289 }
5290}
5291
Eric Laurente0720872014-03-11 09:30:41 -07005292void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005293 bool on,
5294 const sp<AudioOutputDescriptor>& outputDesc,
5295 int delayMs,
5296 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005297{
Eric Laurente552edb2014-03-10 17:42:56 -07005298 if (device == AUDIO_DEVICE_NONE) {
5299 device = outputDesc->device();
5300 }
5301
Eric Laurentc75307b2015-03-17 15:29:32 -07005302 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5303 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005304
5305 if (on) {
5306 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005307 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005308 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005309 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005310 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005311 }
5312 }
5313 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5314 outputDesc->mMuteCount[stream]++;
5315 } else {
5316 if (outputDesc->mMuteCount[stream] == 0) {
5317 ALOGV("setStreamMute() unmuting non muted stream!");
5318 return;
5319 }
5320 if (--outputDesc->mMuteCount[stream] == 0) {
5321 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005322 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005323 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005324 device,
5325 delayMs);
5326 }
5327 }
5328}
5329
Eric Laurente0720872014-03-11 09:30:41 -07005330void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005331 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005332{
Eric Laurent87ffa392015-05-22 10:32:38 -07005333 if(!hasPrimaryOutput()) {
5334 return;
5335 }
5336
Eric Laurente552edb2014-03-10 17:42:56 -07005337 // if the stream pertains to sonification strategy and we are in call we must
5338 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5339 // in the device used for phone strategy and play the tone if the selected device does not
5340 // interfere with the device used for phone strategy
5341 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5342 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005343 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005344 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5345 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005346 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005347 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5348 stream, starting, outputDesc->mDevice, stateChange);
5349 if (outputDesc->mRefCount[stream]) {
5350 int muteCount = 1;
5351 if (stateChange) {
5352 muteCount = outputDesc->mRefCount[stream];
5353 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005354 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005355 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5356 for (int i = 0; i < muteCount; i++) {
5357 setStreamMute(stream, starting, mPrimaryOutput);
5358 }
5359 } else {
5360 ALOGV("handleIncallSonification() high visibility");
5361 if (outputDesc->device() &
5362 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5363 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5364 for (int i = 0; i < muteCount; i++) {
5365 setStreamMute(stream, starting, mPrimaryOutput);
5366 }
5367 }
5368 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005369 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5370 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005371 } else {
5372 mpClientInterface->stopTone();
5373 }
5374 }
5375 }
5376 }
5377}
5378
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005379audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5380{
5381 // flags to stream type mapping
5382 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5383 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5384 }
5385 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5386 return AUDIO_STREAM_BLUETOOTH_SCO;
5387 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005388 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5389 return AUDIO_STREAM_TTS;
5390 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005391
5392 // usage to stream type mapping
5393 switch (attr->usage) {
5394 case AUDIO_USAGE_MEDIA:
5395 case AUDIO_USAGE_GAME:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005396 case AUDIO_USAGE_ASSISTANT:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005397 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5398 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005399 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5400 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005401 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5402 return AUDIO_STREAM_SYSTEM;
5403 case AUDIO_USAGE_VOICE_COMMUNICATION:
5404 return AUDIO_STREAM_VOICE_CALL;
5405
5406 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5407 return AUDIO_STREAM_DTMF;
5408
5409 case AUDIO_USAGE_ALARM:
5410 return AUDIO_STREAM_ALARM;
5411 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5412 return AUDIO_STREAM_RING;
5413
5414 case AUDIO_USAGE_NOTIFICATION:
5415 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5416 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5417 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5418 case AUDIO_USAGE_NOTIFICATION_EVENT:
5419 return AUDIO_STREAM_NOTIFICATION;
5420
5421 case AUDIO_USAGE_UNKNOWN:
5422 default:
5423 return AUDIO_STREAM_MUSIC;
5424 }
5425}
Eric Laurente83b55d2014-11-14 10:06:21 -08005426
François Gaffie53615e22015-03-19 09:24:12 +01005427bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5428{
Eric Laurente83b55d2014-11-14 10:06:21 -08005429 // has flags that map to a strategy?
5430 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5431 return true;
5432 }
5433
5434 // has known usage?
5435 switch (paa->usage) {
5436 case AUDIO_USAGE_UNKNOWN:
5437 case AUDIO_USAGE_MEDIA:
5438 case AUDIO_USAGE_VOICE_COMMUNICATION:
5439 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5440 case AUDIO_USAGE_ALARM:
5441 case AUDIO_USAGE_NOTIFICATION:
5442 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5443 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5444 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5445 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5446 case AUDIO_USAGE_NOTIFICATION_EVENT:
5447 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5448 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5449 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5450 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005451 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08005452 case AUDIO_USAGE_ASSISTANT:
Eric Laurente83b55d2014-11-14 10:06:21 -08005453 break;
5454 default:
5455 return false;
5456 }
5457 return true;
5458}
5459
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07005460bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiead3183e2015-03-18 16:55:35 +01005461 routing_strategy strategy, uint32_t inPastMs,
5462 nsecs_t sysTime) const
5463{
5464 if ((sysTime == 0) && (inPastMs != 0)) {
5465 sysTime = systemTime();
5466 }
Eric Laurent794fde22016-03-11 09:50:45 -08005467 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005468 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5469 (NUM_STRATEGIES == strategy)) &&
5470 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5471 return true;
5472 }
5473 }
5474 return false;
5475}
5476
François Gaffie2110e042015-03-24 08:41:51 +01005477audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5478{
5479 return mEngine->getForceUse(usage);
5480}
5481
5482bool AudioPolicyManager::isInCall()
5483{
5484 return isStateInCall(mEngine->getPhoneState());
5485}
5486
5487bool AudioPolicyManager::isStateInCall(int state)
5488{
5489 return is_state_in_call(state);
5490}
5491
Eric Laurentd60560a2015-04-10 11:31:20 -07005492void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5493{
5494 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5495 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5496 if (sourceDesc->mDevice->equals(deviceDesc)) {
5497 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5498 stopAudioSource(sourceDesc->getHandle());
5499 }
5500 }
5501
5502 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5503 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5504 bool release = false;
5505 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5506 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5507 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5508 source->ext.device.type == deviceDesc->type()) {
5509 release = true;
5510 }
5511 }
5512 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5513 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5514 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5515 sink->ext.device.type == deviceDesc->type()) {
5516 release = true;
5517 }
5518 }
5519 if (release) {
5520 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5521 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5522 }
5523 }
5524}
5525
Phil Burk09bc4612016-02-24 15:58:15 -08005526// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005527void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5528 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005529 // TODO Set this based on Config properties.
5530 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005531
5532 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5533 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005534 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005535
5536 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005537 bool supportsAC3 = false;
5538 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005539 bool supportsIEC61937 = false;
5540 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5541 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005542 switch (format) {
5543 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005544 supportsAC3 = true;
5545 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005546 case AUDIO_FORMAT_E_AC3:
5547 case AUDIO_FORMAT_DTS:
5548 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005549 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005550 break;
5551 case AUDIO_FORMAT_IEC61937:
5552 supportsIEC61937 = true;
5553 break;
5554 default:
5555 break;
5556 }
5557 }
Phil Burk09bc4612016-02-24 15:58:15 -08005558
5559 // Modify formats based on surround preferences.
5560 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005561 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5562 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5563 // Remove surround sound related formats.
5564 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5565 audio_format_t format = formats[formatIndex];
5566 switch(format) {
5567 case AUDIO_FORMAT_AC3:
5568 case AUDIO_FORMAT_E_AC3:
5569 case AUDIO_FORMAT_DTS:
5570 case AUDIO_FORMAT_DTS_HD:
5571 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005572 formats.removeAt(formatIndex);
5573 break;
5574 default:
5575 formatIndex++; // keep it
5576 break;
5577 }
Phil Burk09bc4612016-02-24 15:58:15 -08005578 }
Phil Burk07ac1142016-03-25 13:39:29 -07005579 supportsAC3 = false;
5580 supportsOtherSurround = false;
5581 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005582 }
Phil Burk07ac1142016-03-25 13:39:29 -07005583 } else { // AUTO or ALWAYS
5584 // Most TVs support AC3 even if they do not report it in the EDID.
5585 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5586 && !supportsAC3) {
5587 formats.add(AUDIO_FORMAT_AC3);
5588 supportsAC3 = true;
5589 }
5590
5591 // If ALWAYS, add support for raw surround formats if all are missing.
5592 // This assumes that if any of these formats are reported by the HAL
5593 // then the report is valid and should not be modified.
5594 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5595 && !supportsOtherSurround) {
5596 formats.add(AUDIO_FORMAT_E_AC3);
5597 formats.add(AUDIO_FORMAT_DTS);
5598 formats.add(AUDIO_FORMAT_DTS_HD);
5599 supportsOtherSurround = true;
5600 }
5601
5602 // Add support for IEC61937 if any raw surround supported.
5603 // The HAL could do this but add it here, just in case.
5604 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5605 formats.add(AUDIO_FORMAT_IEC61937);
5606 supportsIEC61937 = true;
5607 }
Phil Burk09bc4612016-02-24 15:58:15 -08005608 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005609}
5610
5611// Modify the list of channel masks supported.
5612void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5613 ChannelsVector &channelMasks = *channelMasksPtr;
5614 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5615 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5616
5617 // If NEVER, then remove support for channelMasks > stereo.
5618 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5619 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5620 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5621 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5622 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5623 channelMasks.removeAt(maskIndex);
5624 } else {
5625 maskIndex++;
5626 }
5627 }
5628 // If ALWAYS, then make sure we at least support 5.1
5629 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5630 bool supports5dot1 = false;
5631 // Are there any channel masks that can be considered "surround"?
5632 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5633 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5634 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5635 supports5dot1 = true;
5636 break;
5637 }
5638 }
5639 // If not then add 5.1 support.
5640 if (!supports5dot1) {
5641 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5642 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5643 }
Phil Burk09bc4612016-02-24 15:58:15 -08005644 }
5645}
5646
Phil Burk00eeb322016-03-31 12:41:00 -07005647void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5648 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005649 AudioProfileVector &profiles)
5650{
5651 String8 reply;
Phil Burk0709b0a2016-03-31 12:54:57 -07005652
François Gaffie112b0af2015-11-19 16:13:25 +01005653 // Format MUST be checked first to update the list of AudioProfile
5654 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005655 reply = mpClientInterface->getParameters(
5656 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Phil Burk0709b0a2016-03-31 12:54:57 -07005657 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005658 AudioParameter repliedParameters(reply);
5659 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005660 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005661 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5662 return;
5663 }
Phil Burk09bc4612016-02-24 15:58:15 -08005664 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005665 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005666 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005667 }
Phil Burk09bc4612016-02-24 15:58:15 -08005668 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005669 }
5670 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5671
Eric Laurent20eb3a42016-01-26 18:39:17 -08005672 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005673 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005674 ChannelsVector channelMasks;
5675 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005676 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07005677 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01005678
5679 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07005680 reply = mpClientInterface->getParameters(
5681 ioHandle,
5682 requestedParameters.toString() + ";" +
5683 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01005684 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005685 AudioParameter repliedParameters(reply);
5686 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005687 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005688 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005689 }
5690 }
5691 if (profiles.hasDynamicChannelsFor(format)) {
5692 reply = mpClientInterface->getParameters(ioHandle,
5693 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07005694 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01005695 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005696 AudioParameter repliedParameters(reply);
5697 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07005698 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08005699 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005700 if (device == AUDIO_DEVICE_OUT_HDMI) {
5701 filterSurroundChannelMasks(&channelMasks);
5702 }
François Gaffie112b0af2015-11-19 16:13:25 +01005703 }
5704 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005705 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005706 }
5707}
Eric Laurentd60560a2015-04-10 11:31:20 -07005708
Eric Laurente552edb2014-03-10 17:42:56 -07005709}; // namespace android