blob: 21ce8c9c1679972715ae1d09841b33638641f276 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
François Gaffief4ad6e52015-11-19 16:59:57 +010027#define AUDIO_POLICY_XML_CONFIG_FILE "/system/etc/audio_policy_configuration.xml"
28
Eric Laurentd4692962014-05-05 18:13:44 -070029#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070030#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070031
François Gaffie2110e042015-03-24 08:41:51 +010032#include <AudioPolicyManagerInterface.h>
33#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070034#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070035#include <utils/Log.h>
36#include <hardware/audio.h>
37#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070038#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080039#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070040#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070041#include "AudioPolicyManager.h"
François Gaffied1ab2bd2015-12-02 18:20:06 +010042#ifndef USE_XML_AUDIO_POLICY_CONF
François Gaffie53615e22015-03-19 09:24:12 +010043#include <ConfigParsingUtils.h>
François Gaffied1ab2bd2015-12-02 18:20:06 +010044#include <StreamDescriptor.h>
François Gaffief4ad6e52015-11-19 16:59:57 +010045#endif
François Gaffied1ab2bd2015-12-02 18:20:06 +010046#include <Serializer.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010047#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010048#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070049
Eric Laurent3b73df72014-03-11 09:06:29 -070050namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070051
52// ----------------------------------------------------------------------------
53// AudioPolicyInterface implementation
54// ----------------------------------------------------------------------------
55
Eric Laurente0720872014-03-11 09:30:41 -070056status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080057 audio_policy_dev_state_t state,
58 const char *device_address,
59 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070060{
Paul McLeane743a472015-01-28 11:07:31 -080061 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080062}
63
64status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080065 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080066 const char *device_address,
67 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080068{
Paul McLeane743a472015-01-28 11:07:31 -080069 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
70- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070071
72 // connect/disconnect only 1 device at a time
73 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
74
François Gaffie53615e22015-03-19 09:24:12 +010075 sp<DeviceDescriptor> devDesc =
76 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080077
Eric Laurente552edb2014-03-10 17:42:56 -070078 // handle output devices
79 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070080 SortedVector <audio_io_handle_t> outputs;
81
Eric Laurent3a4311c2014-03-17 12:00:47 -070082 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
83
Eric Laurente552edb2014-03-10 17:42:56 -070084 // save a copy of the opened output descriptors before any output is opened or closed
85 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
86 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -070087 switch (state)
88 {
89 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -080090 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -070092 ALOGW("setDeviceConnectionState() device already connected: %x", device);
93 return INVALID_OPERATION;
94 }
95 ALOGV("setDeviceConnectionState() connecting device %x", device);
96
Eric Laurente552edb2014-03-10 17:42:56 -070097 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 index = mAvailableOutputDevices.add(devDesc);
99 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +0100100 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700101 if (module == 0) {
102 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
103 device);
104 mAvailableOutputDevices.remove(devDesc);
105 return INVALID_OPERATION;
106 }
Paul McLeane743a472015-01-28 11:07:31 -0800107 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700108 } else {
109 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700110 }
111
Eric Laurenta1d525f2015-01-29 13:36:45 -0800112 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700113 mAvailableOutputDevices.remove(devDesc);
114 return INVALID_OPERATION;
115 }
François Gaffie2110e042015-03-24 08:41:51 +0100116 // Propagate device availability to Engine
117 mEngine->setDeviceConnectionState(devDesc, state);
118
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700119 // outputs should never be empty here
120 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
121 "checkOutputsForDevice() returned no outputs but status OK");
122 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
123 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800124
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800125 // Send connect to HALs
Eric Laurent3ae5f312015-02-03 17:12:08 -0800126 AudioParameter param = AudioParameter(devDesc->mAddress);
127 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
128 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
129
130 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700131 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700132 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700133 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700134 ALOGW("setDeviceConnectionState() device not connected: %x", device);
135 return INVALID_OPERATION;
136 }
137
Paul McLean5c477aa2014-08-20 16:47:57 -0700138 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
139
Paul McLeane743a472015-01-28 11:07:31 -0800140 // Send Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800141 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700142 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
143 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
144
Eric Laurente552edb2014-03-10 17:42:56 -0700145 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700147
Eric Laurenta1d525f2015-01-29 13:36:45 -0800148 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100149
150 // Propagate device availability to Engine
151 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700152 } break;
153
154 default:
155 ALOGE("setDeviceConnectionState() invalid state: %x", state);
156 return BAD_VALUE;
157 }
158
Eric Laurent3a4311c2014-03-17 12:00:47 -0700159 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
160 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700161 checkA2dpSuspend();
162 checkOutputForAllStrategies();
163 // outputs must be closed after checkOutputForAllStrategies() is executed
164 if (!outputs.isEmpty()) {
165 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700166 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700167 // close unused outputs after device disconnection or direct outputs that have been
168 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700169 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700170 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
171 (desc->mDirectOpenCount == 0))) {
172 closeOutput(outputs[i]);
173 }
174 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700175 // check again after closing A2DP output to reset mA2dpSuspended if needed
176 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700177 }
178
179 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700180 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700181 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
182 updateCallRouting(newDevice);
183 }
Eric Laurente552edb2014-03-10 17:42:56 -0700184 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700185 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
186 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
187 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700188 // do not force device change on duplicated output because if device is 0, it will
189 // also force a device 0 for the two outputs it is duplicated to which may override
190 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700191 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100192 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700193 // always force when disconnecting (a non-duplicated device)
194 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700195 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700196 }
Eric Laurente552edb2014-03-10 17:42:56 -0700197 }
198
Eric Laurentd60560a2015-04-10 11:31:20 -0700199 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
200 cleanUpForDevice(devDesc);
201 }
202
Eric Laurent72aa32f2014-05-30 18:51:48 -0700203 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700204 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700205 } // end if is output device
206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // handle input devices
208 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700209 SortedVector <audio_io_handle_t> inputs;
210
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700212 switch (state)
213 {
214 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700217 ALOGW("setDeviceConnectionState() device already connected: %d", device);
218 return INVALID_OPERATION;
219 }
François Gaffie53615e22015-03-19 09:24:12 +0100220 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700221 if (module == NULL) {
222 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
223 device);
224 return INVALID_OPERATION;
225 }
Paul McLean9080a4c2015-06-18 08:24:02 -0700226 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700227 return INVALID_OPERATION;
228 }
229
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 index = mAvailableInputDevices.add(devDesc);
231 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800232 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 } else {
234 return NO_MEMORY;
235 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236
237 // Set connect to HALs
238 AudioParameter param = AudioParameter(devDesc->mAddress);
239 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
240 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
241
François Gaffie2110e042015-03-24 08:41:51 +0100242 // Propagate device availability to Engine
243 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700244 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700245
246 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700247 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700249 ALOGW("setDeviceConnectionState() device not connected: %d", device);
250 return INVALID_OPERATION;
251 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700252
253 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
254
255 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800256 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700257 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
258 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
259
Paul McLean9080a4c2015-06-18 08:24:02 -0700260 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700261 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700262
François Gaffie2110e042015-03-24 08:41:51 +0100263 // Propagate device availability to Engine
264 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700265 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700266
267 default:
268 ALOGE("setDeviceConnectionState() invalid state: %x", state);
269 return BAD_VALUE;
270 }
271
Eric Laurentd4692962014-05-05 18:13:44 -0700272 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700273
Eric Laurent87ffa392015-05-22 10:32:38 -0700274 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700275 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
276 updateCallRouting(newDevice);
277 }
278
Eric Laurentd60560a2015-04-10 11:31:20 -0700279 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
280 cleanUpForDevice(devDesc);
281 }
282
Eric Laurentb52c1522014-05-20 11:27:36 -0700283 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700285 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700286
287 ALOGW("setDeviceConnectionState() invalid device: %x", device);
288 return BAD_VALUE;
289}
290
Eric Laurente0720872014-03-11 09:30:41 -0700291audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100292 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700293{
Eric Laurent634b7142016-04-20 13:48:02 -0700294 sp<DeviceDescriptor> devDesc =
295 mHwModules.getDeviceDescriptor(device, device_address, "",
296 (strlen(device_address) != 0)/*matchAddress*/);
297
298 if (devDesc == 0) {
299 ALOGW("getDeviceConnectionState() undeclared device, type %08x, address: %s",
300 device, device_address);
301 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
302 }
François Gaffie53615e22015-03-19 09:24:12 +0100303
Eric Laurent3a4311c2014-03-17 12:00:47 -0700304 DeviceVector *deviceVector;
305
Eric Laurente552edb2014-03-10 17:42:56 -0700306 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700307 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700308 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700309 deviceVector = &mAvailableInputDevices;
310 } else {
311 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
312 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700313 }
Eric Laurent634b7142016-04-20 13:48:02 -0700314
315 return (deviceVector->getDevice(device, String8(device_address)) != 0) ?
316 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800317}
318
Eric Laurentc2730ba2014-07-20 15:47:07 -0700319void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
320{
321 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700322 status_t status;
323 audio_patch_handle_t afPatchHandle;
324 DeviceVector deviceList;
325
Eric Laurent87ffa392015-05-22 10:32:38 -0700326 if(!hasPrimaryOutput()) {
327 return;
328 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800329 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
331
332 // release existing RX patch if any
333 if (mCallRxPatch != 0) {
334 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
335 mCallRxPatch.clear();
336 }
337 // release TX patch if any
338 if (mCallTxPatch != 0) {
339 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
340 mCallTxPatch.clear();
341 }
342
343 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
344 // via setOutputDevice() on primary output.
345 // Otherwise, create two audio patches for TX and RX path.
346 if (availablePrimaryOutputDevices() & rxDevice) {
347 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
348 // If the TX device is also on the primary HW module, setOutputDevice() will take care
349 // of it due to legacy implementation. If not, create a patch.
350 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
351 == AUDIO_DEVICE_NONE) {
352 createTxPatch = true;
353 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700354 } else { // create RX path audio patch
355 struct audio_patch patch;
356
357 patch.num_sources = 1;
358 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700359 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
360 ALOG_ASSERT(!deviceList.isEmpty(),
361 "updateCallRouting() selected device not in output device list");
362 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
363 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
364 ALOG_ASSERT(!deviceList.isEmpty(),
365 "updateCallRouting() no telephony RX device");
366 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
367
368 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
369 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
370
371 // request to reuse existing output stream if one is already opened to reach the RX device
372 SortedVector<audio_io_handle_t> outputs =
373 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700374 audio_io_handle_t output = selectOutput(outputs,
375 AUDIO_OUTPUT_FLAG_NONE,
376 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700377 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700378 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700379 ALOG_ASSERT(!outputDesc->isDuplicated(),
380 "updateCallRouting() RX device output is duplicated");
381 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700382 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700383 patch.num_sources = 2;
384 }
385
386 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
387 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
388 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
389 status);
390 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100391 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700392 mCallRxPatch->mAfPatchHandle = afPatchHandle;
393 mCallRxPatch->mUid = mUidCached;
394 }
395 createTxPatch = true;
396 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700397 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700398 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700399
Eric Laurentc2730ba2014-07-20 15:47:07 -0700400 patch.num_sources = 1;
401 patch.num_sinks = 1;
402 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
403 ALOG_ASSERT(!deviceList.isEmpty(),
404 "updateCallRouting() selected device not in input device list");
405 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
406 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
407 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
408 ALOG_ASSERT(!deviceList.isEmpty(),
409 "updateCallRouting() no telephony TX device");
410 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
411 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
412
413 SortedVector<audio_io_handle_t> outputs =
414 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700415 audio_io_handle_t output = selectOutput(outputs,
416 AUDIO_OUTPUT_FLAG_NONE,
417 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700418 // request to reuse existing output stream if one is already opened to reach the TX
419 // path output device
420 if (output != AUDIO_IO_HANDLE_NONE) {
421 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
422 ALOG_ASSERT(!outputDesc->isDuplicated(),
423 "updateCallRouting() RX device output is duplicated");
424 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700425 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700426 patch.num_sources = 2;
427 }
428
Eric Laurentc0a889f2015-10-14 14:36:34 -0700429 // terminate active capture if on the same HW module as the call TX source device
430 // FIXME: would be better to refine to only inputs whose profile connects to the
431 // call TX device but this information is not in the audio patch and logic here must be
432 // symmetric to the one in startInput()
Eric Laurent232f26f2016-02-17 18:06:27 -0800433 audio_io_handle_t activeInput = mInputs.getActiveInput();
434 if (activeInput != 0) {
435 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
436 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
437 //FIXME: consider all active sessions
438 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
439 audio_session_t activeSession = activeSessions.keyAt(0);
440 stopInput(activeInput, activeSession);
441 releaseInput(activeInput, activeSession);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700442 }
443 }
444
Eric Laurentc2730ba2014-07-20 15:47:07 -0700445 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
446 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
447 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
448 status);
449 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100450 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700451 mCallTxPatch->mAfPatchHandle = afPatchHandle;
452 mCallTxPatch->mUid = mUidCached;
453 }
454 }
455}
456
Eric Laurente0720872014-03-11 09:30:41 -0700457void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700458{
459 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100460 // store previous phone state for management of sonification strategy below
461 int oldState = mEngine->getPhoneState();
462
463 if (mEngine->setPhoneState(state) != NO_ERROR) {
464 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700465 return;
466 }
François Gaffie2110e042015-03-24 08:41:51 +0100467 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700468 // if leaving call state, handle special case of active streams
469 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700470 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700471 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800472 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700473 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700474 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800475
Eric Laurent63dea1d2015-07-02 17:10:28 -0700476 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800477 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700478 }
479
François Gaffie2110e042015-03-24 08:41:51 +0100480 /**
481 * Switching to or from incall state or switching between telephony and VoIP lead to force
482 * routing command.
483 */
484 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
485 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700486
487 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700488 checkA2dpSuspend();
489 checkOutputForAllStrategies();
490 updateDevicesAndOutputs();
491
Eric Laurente552edb2014-03-10 17:42:56 -0700492 int delayMs = 0;
493 if (isStateInCall(state)) {
494 nsecs_t sysTime = systemTime();
495 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700496 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700497 // mute media and sonification strategies and delay device switch by the largest
498 // latency of any output where either strategy is active.
499 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100500 if ((isStrategyActive(desc, STRATEGY_MEDIA,
501 SONIFICATION_HEADSET_MUSIC_DELAY,
502 sysTime) ||
503 isStrategyActive(desc, STRATEGY_SONIFICATION,
504 SONIFICATION_HEADSET_MUSIC_DELAY,
505 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700506 (delayMs < (int)desc->latency()*2)) {
507 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700508 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700509 setStrategyMute(STRATEGY_MEDIA, true, desc);
510 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700511 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700512 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
513 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700514 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
515 }
516 }
517
Eric Laurent87ffa392015-05-22 10:32:38 -0700518 if (hasPrimaryOutput()) {
519 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
520 // the device returned is not necessarily reachable via this output
521 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
522 // force routing command to audio hardware when ending call
523 // even if no device change is needed
524 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
525 rxDevice = mPrimaryOutput->device();
526 }
Eric Laurente552edb2014-03-10 17:42:56 -0700527
Eric Laurent87ffa392015-05-22 10:32:38 -0700528 if (state == AUDIO_MODE_IN_CALL) {
529 updateCallRouting(rxDevice, delayMs);
530 } else if (oldState == AUDIO_MODE_IN_CALL) {
531 if (mCallRxPatch != 0) {
532 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
533 mCallRxPatch.clear();
534 }
535 if (mCallTxPatch != 0) {
536 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
537 mCallTxPatch.clear();
538 }
539 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
540 } else {
541 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700542 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700543 }
Eric Laurente552edb2014-03-10 17:42:56 -0700544 // if entering in call state, handle special case of active streams
545 // pertaining to sonification strategy see handleIncallSonification()
546 if (isStateInCall(state)) {
547 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800548 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700549 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700550 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700551
552 // force reevaluating accessibility routing when call starts
553 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700554 }
555
556 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700557 if (state == AUDIO_MODE_RINGTONE &&
558 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700559 mLimitRingtoneVolume = true;
560 } else {
561 mLimitRingtoneVolume = false;
562 }
563}
564
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700565audio_mode_t AudioPolicyManager::getPhoneState() {
566 return mEngine->getPhoneState();
567}
568
Eric Laurente0720872014-03-11 09:30:41 -0700569void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700570 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700571{
François Gaffie2110e042015-03-24 08:41:51 +0100572 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700573
François Gaffie2110e042015-03-24 08:41:51 +0100574 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
575 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
576 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700577 }
François Gaffie2110e042015-03-24 08:41:51 +0100578 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
579 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
580 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700581
582 // check for device and output changes triggered by new force usage
583 checkA2dpSuspend();
584 checkOutputForAllStrategies();
585 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800586
Eric Laurent87ffa392015-05-22 10:32:38 -0700587 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700588 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
589 updateCallRouting(newDevice);
590 }
Eric Laurente552edb2014-03-10 17:42:56 -0700591 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700592 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
593 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
594 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
595 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700596 }
Eric Laurente552edb2014-03-10 17:42:56 -0700597 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700598 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
600 }
601
Eric Laurent232f26f2016-02-17 18:06:27 -0800602 audio_io_handle_t activeInput = mInputs.getActiveInput();
603 if (activeInput != 0) {
604 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
605 audio_devices_t newDevice = getNewInputDevice(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700606 // Force new input selection if the new device can not be reached via current input
Eric Laurent232f26f2016-02-17 18:06:27 -0800607 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
608 setInputDevice(activeInput, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700609 } else {
Eric Laurent232f26f2016-02-17 18:06:27 -0800610 closeInput(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700611 }
Eric Laurente552edb2014-03-10 17:42:56 -0700612 }
Eric Laurente552edb2014-03-10 17:42:56 -0700613}
614
Eric Laurente0720872014-03-11 09:30:41 -0700615void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700616{
617 ALOGV("setSystemProperty() property %s, value %s", property, value);
618}
619
620// Find a direct output profile compatible with the parameters passed, even if the input flags do
621// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800622sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700623 audio_devices_t device,
624 uint32_t samplingRate,
625 audio_format_t format,
626 audio_channel_mask_t channelMask,
627 audio_output_flags_t flags)
628{
Eric Laurent861a6282015-05-18 15:40:16 -0700629 // only retain flags that will drive the direct output profile selection
630 // if explicitly requested
631 static const uint32_t kRelevantFlags =
632 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
633 flags =
634 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
635
636 sp<IOProfile> profile;
637
Eric Laurente552edb2014-03-10 17:42:56 -0700638 for (size_t i = 0; i < mHwModules.size(); i++) {
639 if (mHwModules[i]->mHandle == 0) {
640 continue;
641 }
642 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700643 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
644 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700645 samplingRate, NULL /*updatedSamplingRate*/,
646 format, NULL /*updatedFormat*/,
647 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700648 flags)) {
649 continue;
650 }
651 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100652 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700653 continue;
654 }
655 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100656 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700657 continue;
658 }
659 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100660 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700661 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700662 }
Eric Laurente552edb2014-03-10 17:42:56 -0700663 }
664 }
Eric Laurent861a6282015-05-18 15:40:16 -0700665 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700666}
667
Eric Laurente0720872014-03-11 09:30:41 -0700668audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100669 uint32_t samplingRate,
670 audio_format_t format,
671 audio_channel_mask_t channelMask,
672 audio_output_flags_t flags,
673 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700674{
Eric Laurent3b73df72014-03-11 09:06:29 -0700675 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700676 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
677 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
678 device, stream, samplingRate, format, channelMask, flags);
679
Eric Laurente83b55d2014-11-14 10:06:21 -0800680 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
681 stream, samplingRate,format, channelMask,
682 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700683}
684
Eric Laurente83b55d2014-11-14 10:06:21 -0800685status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
686 audio_io_handle_t *output,
687 audio_session_t session,
688 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700689 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800690 uint32_t samplingRate,
691 audio_format_t format,
692 audio_channel_mask_t channelMask,
693 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700694 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800695 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700696{
Eric Laurente83b55d2014-11-14 10:06:21 -0800697 audio_attributes_t attributes;
698 if (attr != NULL) {
699 if (!isValidAttributes(attr)) {
700 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
701 attr->usage, attr->content_type, attr->flags,
702 attr->tags);
703 return BAD_VALUE;
704 }
705 attributes = *attr;
706 } else {
707 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
708 ALOGE("getOutputForAttr(): invalid stream type");
709 return BAD_VALUE;
710 }
711 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700712 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700713 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800714 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100715 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800716 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100717 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800718 }
François Gaffie036e1e92015-03-19 10:16:24 +0100719 *stream = streamTypefromAttributesInt(&attributes);
720 *output = desc->mIoHandle;
721 ALOGV("getOutputForAttr() returns output %d", *output);
722 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800723 }
724 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
725 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
726 return BAD_VALUE;
727 }
728
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700729 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
730 " session %d selectedDeviceId %d",
731 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
732 session, selectedDeviceId);
733
734 *stream = streamTypefromAttributesInt(&attributes);
735
736 // Explicit routing?
737 sp<DeviceDescriptor> deviceDesc;
738 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
739 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
740 deviceDesc = mAvailableOutputDevices[i];
741 break;
742 }
743 }
744 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700745
Eric Laurente83b55d2014-11-14 10:06:21 -0800746 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700747 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700748
Eric Laurente83b55d2014-11-14 10:06:21 -0800749 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700750 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
751 }
752
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700753 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700754 device, samplingRate, format, channelMask, flags);
755
Eric Laurente83b55d2014-11-14 10:06:21 -0800756 *output = getOutputForDevice(device, session, *stream,
757 samplingRate, format, channelMask,
758 flags, offloadInfo);
759 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700760 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800761 return INVALID_OPERATION;
762 }
Paul McLeanaa981192015-03-21 09:55:15 -0700763
Eric Laurente83b55d2014-11-14 10:06:21 -0800764 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700765}
766
767audio_io_handle_t AudioPolicyManager::getOutputForDevice(
768 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800769 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700770 audio_stream_type_t stream,
771 uint32_t samplingRate,
772 audio_format_t format,
773 audio_channel_mask_t channelMask,
774 audio_output_flags_t flags,
775 const audio_offload_info_t *offloadInfo)
776{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700777 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700778 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700779 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700780
Eric Laurente552edb2014-03-10 17:42:56 -0700781#ifdef AUDIO_POLICY_TEST
782 if (mCurOutput != 0) {
783 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
784 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
785
786 if (mTestOutputs[mCurOutput] == 0) {
787 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700788 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
789 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700790 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700791 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700792 outputDesc->mFlags =
793 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700794 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700795 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
796 config.sample_rate = mTestSamplingRate;
797 config.channel_mask = mTestChannels;
798 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700799 if (offloadInfo != NULL) {
800 config.offload_info = *offloadInfo;
801 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700802 status = mpClientInterface->openOutput(0,
803 &mTestOutputs[mCurOutput],
804 &config,
805 &outputDesc->mDevice,
806 String8(""),
807 &outputDesc->mLatency,
808 outputDesc->mFlags);
809 if (status == NO_ERROR) {
810 outputDesc->mSamplingRate = config.sample_rate;
811 outputDesc->mFormat = config.format;
812 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700813 AudioParameter outputCmd = AudioParameter();
814 outputCmd.addInt(String8("set_id"),mCurOutput);
815 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
816 addOutput(mTestOutputs[mCurOutput], outputDesc);
817 }
818 }
819 return mTestOutputs[mCurOutput];
820 }
821#endif //AUDIO_POLICY_TEST
822
823 // open a direct output if required by specified parameters
824 //force direct flag if offload flag is set: offloading implies a direct output stream
825 // and all common behaviors are driven by checking only the direct flag
826 // this should normally be set appropriately in the policy configuration file
827 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700828 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700829 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700830 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
831 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
832 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800833 // only allow deep buffering for music stream type
834 if (stream != AUDIO_STREAM_MUSIC) {
835 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700836 } else if (/* stream == AUDIO_STREAM_MUSIC && */
837 flags == AUDIO_OUTPUT_FLAG_NONE &&
838 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
839 // use DEEP_BUFFER as default output for music stream type
840 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800841 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700842 if (stream == AUDIO_STREAM_TTS) {
843 flags = AUDIO_OUTPUT_FLAG_TTS;
844 }
Eric Laurente552edb2014-03-10 17:42:56 -0700845
Eric Laurentb732cf52014-09-24 19:08:21 -0700846 sp<IOProfile> profile;
847
848 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700849 // and not explicitly requested
850 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800851 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700852 audio_channel_count_from_out_mask(channelMask) <= 2) {
853 goto non_direct_output;
854 }
855
Andy Hung2ddee192015-12-18 17:34:44 -0800856 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
857 // This prevents creating an offloaded track and tearing it down immediately after start
858 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700859 // FIXME: We should check the audio session here but we do not have it in this context.
860 // This may prevent offloading in rare situations where effects are left active by apps
861 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700862
Eric Laurente552edb2014-03-10 17:42:56 -0700863 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800864 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700865 profile = getProfileForDirectOutput(device,
866 samplingRate,
867 format,
868 channelMask,
869 (audio_output_flags_t)flags);
870 }
871
Eric Laurent1c333e22014-05-20 10:48:17 -0700872 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700873 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700874
875 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
878 outputDesc = desc;
879 // reuse direct output if currently open and configured with same parameters
880 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800881 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700882 (channelMask == outputDesc->mChannelMask)) {
883 outputDesc->mDirectOpenCount++;
884 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
885 return mOutputs.keyAt(i);
886 }
887 }
888 }
889 // close direct output if currently open and configured with different parameters
890 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700891 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700892 }
Eric Laurent861a6282015-05-18 15:40:16 -0700893
894 // if the selected profile is offloaded and no offload info was specified,
895 // create a default one
896 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100897 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700898 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
899 defaultOffloadInfo.sample_rate = samplingRate;
900 defaultOffloadInfo.channel_mask = channelMask;
901 defaultOffloadInfo.format = format;
902 defaultOffloadInfo.stream_type = stream;
903 defaultOffloadInfo.bit_rate = 0;
904 defaultOffloadInfo.duration_us = -1;
905 defaultOffloadInfo.has_video = true; // conservative
906 defaultOffloadInfo.is_streaming = true; // likely
907 offloadInfo = &defaultOffloadInfo;
908 }
909
Eric Laurentc75307b2015-03-17 15:29:32 -0700910 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700911 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700912 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700913 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700914 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
915 config.sample_rate = samplingRate;
916 config.channel_mask = channelMask;
917 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700918 if (offloadInfo != NULL) {
919 config.offload_info = *offloadInfo;
920 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700921 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700922 &output,
923 &config,
924 &outputDesc->mDevice,
925 String8(""),
926 &outputDesc->mLatency,
927 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700928
929 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700930 if (status != NO_ERROR ||
931 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800932 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700933 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700934 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
935 "format %d %d, channelMask %04x %04x", output, samplingRate,
936 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
937 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700938 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700939 mpClientInterface->closeOutput(output);
940 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800941 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800942 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800943 goto non_direct_output;
944 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700945 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700946 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700947 outputDesc->mSamplingRate = config.sample_rate;
948 outputDesc->mChannelMask = config.channel_mask;
949 outputDesc->mFormat = config.format;
950 outputDesc->mRefCount[stream] = 0;
951 outputDesc->mStopTime[stream] = 0;
952 outputDesc->mDirectOpenCount = 1;
953
Eric Laurente552edb2014-03-10 17:42:56 -0700954 audio_io_handle_t srcOutput = getOutputForEffect();
955 addOutput(output, outputDesc);
956 audio_io_handle_t dstOutput = getOutputForEffect();
957 if (dstOutput == output) {
958 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
959 }
960 mPreviousOutputs = mOutputs;
961 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700962 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700963 return output;
964 }
965
Eric Laurentb732cf52014-09-24 19:08:21 -0700966non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700967
968 // A request for HW A/V sync cannot fallback to a mixed output because time
969 // stamps are embedded in audio data
970 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
971 return AUDIO_IO_HANDLE_NONE;
972 }
973
Eric Laurente552edb2014-03-10 17:42:56 -0700974 // ignoring channel mask due to downmix capability in mixer
975
976 // open a non direct output
977
978 // for non direct outputs, only PCM is supported
979 if (audio_is_linear_pcm(format)) {
980 // get which output is suitable for the specified stream. The actual
981 // routing change will happen when startOutput() will be called
982 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
983
Eric Laurent8838a382014-09-08 16:44:28 -0700984 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
985 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
986 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
988 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
989 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
990
Paul McLeanaa981192015-03-21 09:55:15 -0700991 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700992
993 return output;
994}
995
Eric Laurente0720872014-03-11 09:30:41 -0700996audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700997 audio_output_flags_t flags,
998 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700999{
1000 // select one output among several that provide a path to a particular device or set of
1001 // devices (the list was previously build by getOutputsForDevice()).
1002 // The priority is as follows:
1003 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -08001004 // 2: the output with the bit depth the closest to the requested one
1005 // 3: the primary output
1006 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001007
1008 if (outputs.size() == 0) {
1009 return 0;
1010 }
1011 if (outputs.size() == 1) {
1012 return outputs[0];
1013 }
1014
1015 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001016 audio_io_handle_t outputForFlags = 0;
1017 audio_io_handle_t outputForPrimary = 0;
1018 audio_io_handle_t outputForFormat = 0;
1019 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1020 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001021
1022 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001023 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001024 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001025 // if a valid format is specified, skip output if not compatible
1026 if (format != AUDIO_FORMAT_INVALID) {
1027 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001028 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001029 continue;
1030 }
1031 } else if (!audio_is_linear_pcm(format)) {
1032 continue;
1033 }
Eric Laurente6930022016-02-11 10:20:40 -08001034 if (AudioPort::isBetterFormatMatch(
1035 outputDesc->mFormat, bestFormat, format)) {
1036 outputForFormat = outputs[i];
1037 bestFormat = outputDesc->mFormat;
1038 }
Eric Laurent8838a382014-09-08 16:44:28 -07001039 }
1040
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001041 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001042 if (commonFlags >= maxCommonFlags) {
1043 if (commonFlags == maxCommonFlags) {
1044 if (AudioPort::isBetterFormatMatch(
1045 outputDesc->mFormat, bestFormatForFlags, format)) {
1046 outputForFlags = outputs[i];
1047 bestFormatForFlags = outputDesc->mFormat;
1048 }
1049 } else {
1050 outputForFlags = outputs[i];
1051 maxCommonFlags = commonFlags;
1052 bestFormatForFlags = outputDesc->mFormat;
1053 }
Eric Laurente552edb2014-03-10 17:42:56 -07001054 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1055 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001056 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001057 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001058 }
1059 }
1060 }
1061
Eric Laurente6930022016-02-11 10:20:40 -08001062 if (outputForFlags != 0) {
1063 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001064 }
Eric Laurente6930022016-02-11 10:20:40 -08001065 if (outputForFormat != 0) {
1066 return outputForFormat;
1067 }
1068 if (outputForPrimary != 0) {
1069 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001070 }
1071
1072 return outputs[0];
1073}
1074
Eric Laurente0720872014-03-11 09:30:41 -07001075status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001076 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001077 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001078{
Paul McLeanaa981192015-03-21 09:55:15 -07001079 ALOGV("startOutput() output %d, stream %d, session %d",
1080 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001081 ssize_t index = mOutputs.indexOfKey(output);
1082 if (index < 0) {
1083 ALOGW("startOutput() unknown output %d", output);
1084 return BAD_VALUE;
1085 }
1086
Eric Laurentc75307b2015-03-17 15:29:32 -07001087 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1088
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001089 // Routing?
1090 mOutputRoutes.incRouteActivity(session);
1091
Eric Laurentc75307b2015-03-17 15:29:32 -07001092 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001093 AudioMix *policyMix = NULL;
1094 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001095 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001096 policyMix = outputDesc->mPolicyMix;
1097 address = policyMix->mDeviceAddress.string();
1098 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1099 newDevice = policyMix->mDeviceType;
1100 } else {
1101 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1102 }
Eric Laurent493404d2015-04-21 15:07:36 -07001103 } else if (mOutputRoutes.hasRouteChanged(session)) {
1104 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001105 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001106 } else {
1107 newDevice = AUDIO_DEVICE_NONE;
1108 }
1109
1110 uint32_t delayMs = 0;
1111
Eric Laurentc40d9692016-04-13 19:14:13 -07001112 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001113
1114 if (status != NO_ERROR) {
1115 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001116 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001117 }
1118 // Automatically enable the remote submix input when output is started on a re routing mix
1119 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001120 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1121 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001122 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1123 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001124 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001125 "remote-submix");
1126 }
1127
1128 if (delayMs != 0) {
1129 usleep(delayMs * 1000);
1130 }
1131
1132 return status;
1133}
1134
1135status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1136 audio_stream_type_t stream,
1137 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001138 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001139 uint32_t *delayMs)
1140{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001141 // cannot start playback of STREAM_TTS if any other output is being used
1142 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001143
1144 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001145 if (stream == AUDIO_STREAM_TTS) {
1146 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001147 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001148 return INVALID_OPERATION;
1149 } else {
1150 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1151 }
1152 } else {
1153 // some playback other than beacon starts
1154 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1155 }
1156
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001157 // check active before incrementing usage count
1158 bool force = !outputDesc->isActive();
1159
Eric Laurente552edb2014-03-10 17:42:56 -07001160 // increment usage count for this stream on the requested output:
1161 // NOTE that the usage count is the same for duplicated output and hardware output which is
1162 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1163 outputDesc->changeRefCount(stream, 1);
1164
Eric Laurent493404d2015-04-21 15:07:36 -07001165 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001166 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001167 if (device == AUDIO_DEVICE_NONE) {
1168 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001169 }
Eric Laurente552edb2014-03-10 17:42:56 -07001170 routing_strategy strategy = getStrategy(stream);
1171 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001172 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1173 (beaconMuteLatency > 0);
1174 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001175 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001176 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001177 if (desc != outputDesc) {
1178 // force a device change if any other output is managed by the same hw
1179 // module and has a current device selection that differs from selected device.
1180 // In this case, the audio HAL must receive the new device selection so that it can
1181 // change the device currently selected by the other active output.
1182 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001183 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001184 force = true;
1185 }
1186 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001187 // a notification so that audio focus effect can propagate, or that a mute/unmute
1188 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001189 uint32_t latency = desc->latency();
1190 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1191 waitMs = latency;
1192 }
1193 }
1194 }
Eric Laurentc40d9692016-04-13 19:14:13 -07001195 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001196
1197 // handle special case for sonification while in call
1198 if (isInCall()) {
1199 handleIncallSonification(stream, true, false);
1200 }
1201
1202 // apply volume rules for current stream and device if necessary
1203 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001204 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001205 outputDesc,
1206 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001207
1208 // update the outputs if starting an output with a stream that can affect notification
1209 // routing
1210 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001211
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001212 // force reevaluating accessibility routing when ringtone or alarm starts
1213 if (strategy == STRATEGY_SONIFICATION) {
1214 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1215 }
Eric Laurente552edb2014-03-10 17:42:56 -07001216 }
1217 return NO_ERROR;
1218}
1219
1220
Eric Laurente0720872014-03-11 09:30:41 -07001221status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001222 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001223 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001224{
1225 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1226 ssize_t index = mOutputs.indexOfKey(output);
1227 if (index < 0) {
1228 ALOGW("stopOutput() unknown output %d", output);
1229 return BAD_VALUE;
1230 }
1231
Eric Laurentc75307b2015-03-17 15:29:32 -07001232 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001233
Eric Laurentc75307b2015-03-17 15:29:32 -07001234 if (outputDesc->mRefCount[stream] == 1) {
1235 // Automatically disable the remote submix input when output is stopped on a
1236 // re routing mix of type MIX_TYPE_RECORDERS
1237 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1238 outputDesc->mPolicyMix != NULL &&
1239 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1240 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1241 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001242 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001243 "remote-submix");
1244 }
1245 }
1246
1247 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001248 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001249 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001250 int activityCount = mOutputRoutes.decRouteActivity(session);
1251 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1252
1253 if (forceDeviceUpdate) {
1254 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1255 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001256 }
1257
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001258 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001259}
1260
1261status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001262 audio_stream_type_t stream,
1263 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001264{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001265 // always handle stream stop, check which stream type is stopping
1266 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1267
Eric Laurente552edb2014-03-10 17:42:56 -07001268 // handle special case for sonification while in call
1269 if (isInCall()) {
1270 handleIncallSonification(stream, false, false);
1271 }
1272
1273 if (outputDesc->mRefCount[stream] > 0) {
1274 // decrement usage count of this stream on the output
1275 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001276
Eric Laurente552edb2014-03-10 17:42:56 -07001277 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001278 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001279 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001280 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001281 // delay the device switch by twice the latency because stopOutput() is executed when
1282 // the track stop() command is received and at that time the audio track buffer can
1283 // still contain data that needs to be drained. The latency only covers the audio HAL
1284 // and kernel buffers. Also the latency does not always include additional delay in the
1285 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001286 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001287
1288 // force restoring the device selection on other active outputs if it differs from the
1289 // one being selected for this output
1290 for (size_t i = 0; i < mOutputs.size(); i++) {
1291 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001292 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001293 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001294 desc->isActive() &&
1295 outputDesc->sharesHwModuleWith(desc) &&
1296 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001297 setOutputDevice(desc,
1298 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001299 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001300 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001301 }
1302 }
1303 // update the outputs if stopping one with a stream that can affect notification routing
1304 handleNotificationRoutingForStream(stream);
1305 }
1306 return NO_ERROR;
1307 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001308 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001309 return INVALID_OPERATION;
1310 }
1311}
1312
Eric Laurente83b55d2014-11-14 10:06:21 -08001313void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001314 audio_stream_type_t stream __unused,
1315 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001316{
1317 ALOGV("releaseOutput() %d", output);
1318 ssize_t index = mOutputs.indexOfKey(output);
1319 if (index < 0) {
1320 ALOGW("releaseOutput() releasing unknown output %d", output);
1321 return;
1322 }
1323
1324#ifdef AUDIO_POLICY_TEST
1325 int testIndex = testOutputIndex(output);
1326 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001327 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001328 if (outputDesc->isActive()) {
1329 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001330 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001331 mTestOutputs[testIndex] = 0;
1332 }
1333 return;
1334 }
1335#endif //AUDIO_POLICY_TEST
1336
Paul McLeanaa981192015-03-21 09:55:15 -07001337 // Routing
1338 mOutputRoutes.removeRoute(session);
1339
Eric Laurentc75307b2015-03-17 15:29:32 -07001340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001341 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001342 if (desc->mDirectOpenCount <= 0) {
1343 ALOGW("releaseOutput() invalid open count %d for output %d",
1344 desc->mDirectOpenCount, output);
1345 return;
1346 }
1347 if (--desc->mDirectOpenCount == 0) {
1348 closeOutput(output);
1349 // If effects where present on the output, audioflinger moved them to the primary
1350 // output by default: move them back to the appropriate output.
1351 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001352 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001353 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1354 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001355 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001356 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001357 }
1358 }
1359}
1360
1361
Eric Laurentcaf7f482014-11-25 17:50:47 -08001362status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1363 audio_io_handle_t *input,
1364 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001365 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001366 uint32_t samplingRate,
1367 audio_format_t format,
1368 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001369 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001370 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001371 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001372{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001373 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1374 "session %d, flags %#x",
1375 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001376
Eric Laurentcaf7f482014-11-25 17:50:47 -08001377 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001378 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001379 audio_devices_t device;
1380 // handle legacy remote submix case where the address was not always specified
1381 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001382 audio_source_t inputSource = attr->source;
1383 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001384 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001385
Eric Laurentc447ded2015-01-06 08:47:05 -08001386 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1387 inputSource = AUDIO_SOURCE_MIC;
1388 }
1389 halInputSource = inputSource;
1390
Paul McLean466dc8e2015-04-17 13:15:36 -06001391 // Explicit routing?
1392 sp<DeviceDescriptor> deviceDesc;
1393 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1394 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1395 deviceDesc = mAvailableInputDevices[i];
1396 break;
1397 }
1398 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001399 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001400
Eric Laurentc447ded2015-01-06 08:47:05 -08001401 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001402 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001403 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001404 if (ret != NO_ERROR) {
1405 return ret;
1406 }
1407 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001408 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1409 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001410 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001411 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001412 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001413 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001414 return BAD_VALUE;
1415 }
Eric Laurentc722f302014-12-10 11:21:49 -08001416 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001417 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001418 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1419 // there is an external policy, but this input is attached to a mix of recorders,
1420 // meaning it receives audio injected into the framework, so the recorder doesn't
1421 // know about it and is therefore considered "legacy"
1422 *inputType = API_INPUT_LEGACY;
1423 } else {
1424 // recording a mix of players defined by an external policy, we're rerouting for
1425 // an external policy
1426 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1427 }
Eric Laurentc722f302014-12-10 11:21:49 -08001428 } else if (audio_is_remote_submix_device(device)) {
1429 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001430 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001431 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1432 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001433 } else {
1434 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001435 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001436
Eric Laurent599c7582015-12-07 18:05:55 -08001437 }
1438
1439 *input = getInputForDevice(device, address, session, uid, inputSource,
1440 samplingRate, format, channelMask, flags,
1441 policyMix);
1442 if (*input == AUDIO_IO_HANDLE_NONE) {
1443 mInputRoutes.removeRoute(session);
1444 return INVALID_OPERATION;
1445 }
1446 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1447 return NO_ERROR;
1448}
1449
1450
1451audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1452 String8 address,
1453 audio_session_t session,
1454 uid_t uid,
1455 audio_source_t inputSource,
1456 uint32_t samplingRate,
1457 audio_format_t format,
1458 audio_channel_mask_t channelMask,
1459 audio_input_flags_t flags,
1460 AudioMix *policyMix)
1461{
1462 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1463 audio_source_t halInputSource = inputSource;
1464 bool isSoundTrigger = false;
1465
1466 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1467 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1468 if (index >= 0) {
1469 input = mSoundTriggerSessions.valueFor(session);
1470 isSoundTrigger = true;
1471 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1472 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1473 } else {
1474 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001475 }
1476 }
1477
Andy Hungf129b032015-04-07 13:45:50 -07001478 // find a compatible input profile (not necessarily identical in parameters)
1479 sp<IOProfile> profile;
1480 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001481 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001482 audio_format_t profileFormat = format;
1483 audio_channel_mask_t profileChannelMask = channelMask;
1484 audio_input_flags_t profileFlags = flags;
1485 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001486 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001487 profileSamplingRate, profileFormat, profileChannelMask,
1488 profileFlags);
1489 if (profile != 0) {
1490 break; // success
1491 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1492 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1493 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001494 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1495 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001496 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001497 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001498 }
Eric Laurente552edb2014-03-10 17:42:56 -07001499 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001500 // Pick input sampling rate if not specified by client
1501 if (samplingRate == 0) {
1502 samplingRate = profileSamplingRate;
1503 }
Eric Laurente552edb2014-03-10 17:42:56 -07001504
Eric Laurent322b4d22015-04-03 15:57:54 -07001505 if (profile->getModuleHandle() == 0) {
1506 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001507 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001508 }
1509
Eric Laurent599c7582015-12-07 18:05:55 -08001510 sp<AudioSession> audioSession = new AudioSession(session,
1511 inputSource,
1512 format,
1513 samplingRate,
1514 channelMask,
1515 flags,
1516 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001517 isSoundTrigger,
1518 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001519
Eric Laurent232f26f2016-02-17 18:06:27 -08001520// TODO enable input reuse
1521#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001522 // reuse an open input if possible
1523 for (size_t i = 0; i < mInputs.size(); i++) {
1524 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent232f26f2016-02-17 18:06:27 -08001525 // reuse input if it shares the same profile and same sound trigger attribute
1526 if (profile == desc->mProfile &&
1527 isSoundTrigger == desc->isSoundTrigger()) {
Eric Laurent599c7582015-12-07 18:05:55 -08001528
1529 sp<AudioSession> as = desc->getAudioSession(session);
1530 if (as != 0) {
1531 // do not allow unmatching properties on same session
1532 if (as->matches(audioSession)) {
1533 as->changeOpenCount(1);
1534 } else {
1535 ALOGW("getInputForDevice() record with different attributes"
1536 " exists for session %d", session);
Eric Laurent232f26f2016-02-17 18:06:27 -08001537 return input;
Eric Laurent599c7582015-12-07 18:05:55 -08001538 }
1539 } else {
1540 desc->addAudioSession(session, audioSession);
1541 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001542 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1543 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001544 }
1545 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001546#endif
Eric Laurent599c7582015-12-07 18:05:55 -08001547
Eric Laurentcf2c0212014-07-25 16:20:43 -07001548 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001549 config.sample_rate = profileSamplingRate;
1550 config.channel_mask = profileChannelMask;
1551 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001552
Eric Laurent322b4d22015-04-03 15:57:54 -07001553 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001554 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001555 &config,
1556 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001557 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001558 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001559 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001560
1561 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001562 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001563 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001564 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001565 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001566 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1567 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001568 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001569 if (input != AUDIO_IO_HANDLE_NONE) {
1570 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001571 }
Eric Laurent599c7582015-12-07 18:05:55 -08001572 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001573 }
1574
Eric Laurent1f2f2232014-06-02 12:01:23 -07001575 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001576 inputDesc->mSamplingRate = profileSamplingRate;
1577 inputDesc->mFormat = profileFormat;
1578 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001579 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001580 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001581 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001582
Eric Laurent599c7582015-12-07 18:05:55 -08001583 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001584 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001585
Eric Laurent599c7582015-12-07 18:05:55 -08001586 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001587}
1588
Eric Laurent4dc68062014-07-28 17:26:49 -07001589status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurent232f26f2016-02-17 18:06:27 -08001590 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001591{
1592 ALOGV("startInput() input %d", input);
1593 ssize_t index = mInputs.indexOfKey(input);
1594 if (index < 0) {
1595 ALOGW("startInput() unknown input %d", input);
1596 return BAD_VALUE;
1597 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001598 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001599
Eric Laurent599c7582015-12-07 18:05:55 -08001600 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1601 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001602 ALOGW("startInput() unknown session %d on input %d", session, input);
1603 return BAD_VALUE;
1604 }
1605
Eric Laurent232f26f2016-02-17 18:06:27 -08001606 // virtual input devices are compatible with other input devices
1607 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001608
Eric Laurent232f26f2016-02-17 18:06:27 -08001609 // for a non-virtual input device, check if there is another (non-virtual) active input
1610 audio_io_handle_t activeInput = mInputs.getActiveInput();
1611 if (activeInput != 0 && activeInput != input) {
Eric Laurente552edb2014-03-10 17:42:56 -07001612
Eric Laurent232f26f2016-02-17 18:06:27 -08001613 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1614 // otherwise the active input continues and the new input cannot be started.
1615 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1616 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
1617 !activeDesc->hasPreemptedSession(session)) {
1618 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1619 //FIXME: consider all active sessions
1620 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1621 audio_session_t activeSession = activeSessions.keyAt(0);
1622 SortedVector<audio_session_t> sessions =
1623 activeDesc->getPreemptedSessions();
1624 sessions.add(activeSession);
1625 inputDesc->setPreemptedSessions(sessions);
1626 stopInput(activeInput, activeSession);
1627 releaseInput(activeInput, activeSession);
1628 } else {
1629 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1630 return INVALID_OPERATION;
1631 }
1632 }
1633
1634 // Do not allow capture if an active voice call is using a software patch and
1635 // the call TX source device is on the same HW module.
1636 // FIXME: would be better to refine to only inputs whose profile connects to the
1637 // call TX device but this information is not in the audio patch
1638 if (mCallTxPatch != 0 &&
1639 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1640 return INVALID_OPERATION;
1641 }
1642 }
Eric Laurent313d1e72016-01-29 09:56:57 -08001643
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001644 // Routing?
1645 mInputRoutes.incRouteActivity(session);
1646
Eric Laurent232f26f2016-02-17 18:06:27 -08001647 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1648 // if input maps to a dynamic policy with an activity listener, notify of state change
1649 if ((inputDesc->mPolicyMix != NULL)
1650 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001651 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001652 MIX_STATE_MIXING);
1653 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001654
Eric Laurent232f26f2016-02-17 18:06:27 -08001655 if (mInputs.activeInputsCount() == 0) {
1656 SoundTrigger::setCaptureState(true);
1657 }
1658 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001659
Eric Laurent232f26f2016-02-17 18:06:27 -08001660 // automatically enable the remote submix output when input is started if not
1661 // used by a policy mix of type MIX_TYPE_RECORDERS
1662 // For remote submix (a virtual device), we open only one input per capture request.
1663 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1664 String8 address = String8("");
1665 if (inputDesc->mPolicyMix == NULL) {
1666 address = String8("0");
1667 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001668 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurentc722f302014-12-10 11:21:49 -08001669 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001670 if (address != "") {
1671 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1672 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1673 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001674 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001675 }
Eric Laurente552edb2014-03-10 17:42:56 -07001676 }
1677
Eric Laurent599c7582015-12-07 18:05:55 -08001678 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001679
Eric Laurent232f26f2016-02-17 18:06:27 -08001680 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001681 return NO_ERROR;
1682}
1683
Eric Laurent4dc68062014-07-28 17:26:49 -07001684status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1685 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001686{
1687 ALOGV("stopInput() input %d", input);
1688 ssize_t index = mInputs.indexOfKey(input);
1689 if (index < 0) {
1690 ALOGW("stopInput() unknown input %d", input);
1691 return BAD_VALUE;
1692 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001693 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001694
Eric Laurent599c7582015-12-07 18:05:55 -08001695 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001696 if (index < 0) {
1697 ALOGW("stopInput() unknown session %d on input %d", session, input);
1698 return BAD_VALUE;
1699 }
1700
Eric Laurent599c7582015-12-07 18:05:55 -08001701 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001702 ALOGW("stopInput() input %d already stopped", input);
1703 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001704 }
1705
Eric Laurent599c7582015-12-07 18:05:55 -08001706 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001707
1708 // Routing?
1709 mInputRoutes.decRouteActivity(session);
1710
Eric Laurent232f26f2016-02-17 18:06:27 -08001711 if (!inputDesc->isActive()) {
1712 // if input maps to a dynamic policy with an activity listener, notify of state change
1713 if ((inputDesc->mPolicyMix != NULL)
1714 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001715 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001716 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001717 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001718
1719 // automatically disable the remote submix output when input is stopped if not
1720 // used by a policy mix of type MIX_TYPE_RECORDERS
1721 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1722 String8 address = String8("");
1723 if (inputDesc->mPolicyMix == NULL) {
1724 address = String8("0");
1725 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001726 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurent232f26f2016-02-17 18:06:27 -08001727 }
1728 if (address != "") {
1729 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1730 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1731 address, "remote-submix");
1732 }
1733 }
1734
1735 resetInputDevice(input);
1736
1737 if (mInputs.activeInputsCount() == 0) {
1738 SoundTrigger::setCaptureState(false);
1739 }
1740 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001741 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001742 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001743}
1744
Eric Laurent4dc68062014-07-28 17:26:49 -07001745void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1746 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001747{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001748
Eric Laurente552edb2014-03-10 17:42:56 -07001749 ALOGV("releaseInput() %d", input);
1750 ssize_t index = mInputs.indexOfKey(input);
1751 if (index < 0) {
1752 ALOGW("releaseInput() releasing unknown input %d", input);
1753 return;
1754 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001755
1756 // Routing
1757 mInputRoutes.removeRoute(session);
1758
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001759 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1760 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001761
Eric Laurent599c7582015-12-07 18:05:55 -08001762 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001763 if (index < 0) {
1764 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1765 return;
1766 }
Eric Laurent599c7582015-12-07 18:05:55 -08001767
1768 if (audioSession->openCount() == 0) {
1769 ALOGW("releaseInput() invalid open count %d on session %d",
1770 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001771 return;
1772 }
Eric Laurent599c7582015-12-07 18:05:55 -08001773
1774 if (audioSession->changeOpenCount(-1) == 0) {
1775 inputDesc->removeAudioSession(session);
1776 }
1777
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001778 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001779 ALOGV("releaseInput() exit > 0");
1780 return;
1781 }
1782
Eric Laurent05b90f82014-08-27 15:32:29 -07001783 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001784 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001785 ALOGV("releaseInput() exit");
1786}
1787
Eric Laurentd4692962014-05-05 18:13:44 -07001788void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001789 bool patchRemoved = false;
1790
Eric Laurentd4692962014-05-05 18:13:44 -07001791 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001792 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001793 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001794 if (patch_index >= 0) {
1795 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1796 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1797 mAudioPatches.removeItemsAt(patch_index);
1798 patchRemoved = true;
1799 }
Eric Laurentd4692962014-05-05 18:13:44 -07001800 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1801 }
1802 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001803 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001804 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001805
1806 if (patchRemoved) {
1807 mpClientInterface->onAudioPatchListUpdate();
1808 }
Eric Laurentd4692962014-05-05 18:13:44 -07001809}
1810
Eric Laurente0720872014-03-11 09:30:41 -07001811void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001812 int indexMin,
1813 int indexMax)
1814{
1815 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001816 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001817
1818 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001819 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1820 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001821 continue;
1822 }
1823 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001824 }
Eric Laurente552edb2014-03-10 17:42:56 -07001825}
1826
Eric Laurente0720872014-03-11 09:30:41 -07001827status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001828 int index,
1829 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001830{
1831
François Gaffied1ab2bd2015-12-02 18:20:06 +01001832 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1833 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001834 return BAD_VALUE;
1835 }
1836 if (!audio_is_output_device(device)) {
1837 return BAD_VALUE;
1838 }
1839
1840 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001841 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001842
Eric Laurent1fd372e2016-04-06 14:23:53 -07001843 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001844 stream, device, index);
1845
Eric Laurent28d09f02016-03-08 10:43:05 -08001846 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001847 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1848 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001849 continue;
1850 }
1851 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1852 }
Eric Laurente552edb2014-03-10 17:42:56 -07001853
Eric Laurent1fd372e2016-04-06 14:23:53 -07001854 // update volume on all outputs and streams matching the following:
1855 // - The requested stream (or a stream matching for volume control) is active on the output
1856 // - The device (or devices) selected by the strategy corresponding to this stream includes
1857 // the requested device
1858 // - For non default requested device, currently selected device on the output is either the
1859 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001860 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1861 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001862 status_t status = NO_ERROR;
1863 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001864 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1865 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001866 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1867 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001868 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001869 }
Eric Laurentd3926fe2016-04-15 18:10:07 -07001870 if (!(desc->isStreamActive((audio_stream_type_t)curStream) ||
1871 (isInCall() && (curStream == AUDIO_STREAM_VOICE_CALL)))) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001872 continue;
1873 }
Eric Laurent794fde22016-03-11 09:50:45 -08001874 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08001875 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/);
Eric Laurent1fd372e2016-04-06 14:23:53 -07001876 if ((curStreamDevice & device) == 0) {
1877 continue;
1878 }
1879 bool applyDefault = false;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001880 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001881 curStreamDevice |= device;
1882 } else if (!mVolumeCurves->hasVolumeIndexForDevice(
1883 stream, Volume::getDeviceForVolume(curStreamDevice))) {
1884 applyDefault = true;
1885 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001886
Eric Laurent1fd372e2016-04-06 14:23:53 -07001887 if (applyDefault || ((curDevice & curStreamDevice) != 0)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001888 status_t volStatus =
1889 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice);
1890 if (volStatus != NO_ERROR) {
1891 status = volStatus;
1892 }
1893 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001894 }
Eric Laurente552edb2014-03-10 17:42:56 -07001895 }
1896 return status;
1897}
1898
Eric Laurente0720872014-03-11 09:30:41 -07001899status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001900 int *index,
1901 audio_devices_t device)
1902{
1903 if (index == NULL) {
1904 return BAD_VALUE;
1905 }
1906 if (!audio_is_output_device(device)) {
1907 return BAD_VALUE;
1908 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07001909 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07001910 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07001911 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07001912 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1913 }
François Gaffiedfd74092015-03-19 12:10:59 +01001914 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001915
François Gaffied1ab2bd2015-12-02 18:20:06 +01001916 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07001917 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1918 return NO_ERROR;
1919}
1920
Eric Laurente0720872014-03-11 09:30:41 -07001921audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001922 const SortedVector<audio_io_handle_t>& outputs)
1923{
1924 // select one output among several suitable for global effects.
1925 // The priority is as follows:
1926 // 1: An offloaded output. If the effect ends up not being offloadable,
1927 // AudioFlinger will invalidate the track and the offloaded output
1928 // will be closed causing the effect to be moved to a PCM output.
1929 // 2: A deep buffer output
1930 // 3: the first output in the list
1931
1932 if (outputs.size() == 0) {
1933 return 0;
1934 }
1935
1936 audio_io_handle_t outputOffloaded = 0;
1937 audio_io_handle_t outputDeepBuffer = 0;
1938
1939 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001940 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001941 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001942 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1943 outputOffloaded = outputs[i];
1944 }
1945 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1946 outputDeepBuffer = outputs[i];
1947 }
1948 }
1949
1950 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1951 outputOffloaded, outputDeepBuffer);
1952 if (outputOffloaded != 0) {
1953 return outputOffloaded;
1954 }
1955 if (outputDeepBuffer != 0) {
1956 return outputDeepBuffer;
1957 }
1958
1959 return outputs[0];
1960}
1961
Eric Laurente0720872014-03-11 09:30:41 -07001962audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001963{
1964 // apply simple rule where global effects are attached to the same output as MUSIC streams
1965
Eric Laurent3b73df72014-03-11 09:06:29 -07001966 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001967 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1968 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1969
1970 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1971 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1972 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1973
1974 return output;
1975}
1976
Eric Laurente0720872014-03-11 09:30:41 -07001977status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001978 audio_io_handle_t io,
1979 uint32_t strategy,
1980 int session,
1981 int id)
1982{
1983 ssize_t index = mOutputs.indexOfKey(io);
1984 if (index < 0) {
1985 index = mInputs.indexOfKey(io);
1986 if (index < 0) {
1987 ALOGW("registerEffect() unknown io %d", io);
1988 return INVALID_OPERATION;
1989 }
1990 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001991 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001992}
1993
Eric Laurentc75307b2015-03-17 15:29:32 -07001994bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1995{
Eric Laurent28d09f02016-03-08 10:43:05 -08001996 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08001997 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
1998 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001999 continue;
2000 }
2001 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
2002 }
Eric Laurent28d09f02016-03-08 10:43:05 -08002003 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07002004}
2005
2006bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2007{
2008 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
2009}
2010
Eric Laurente0720872014-03-11 09:30:41 -07002011bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002012{
2013 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002014 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002015 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002016 return true;
2017 }
2018 }
2019 return false;
2020}
2021
Eric Laurent275e8e92014-11-30 15:14:47 -08002022// Register a list of custom mixes with their attributes and format.
2023// When a mix is registered, corresponding input and output profiles are
2024// added to the remote submix hw module. The profile contains only the
2025// parameters (sampling rate, format...) specified by the mix.
2026// The corresponding input remote submix device is also connected.
2027//
2028// When a remote submix device is connected, the address is checked to select the
2029// appropriate profile and the corresponding input or output stream is opened.
2030//
2031// When capture starts, getInputForAttr() will:
2032// - 1 look for a mix matching the address passed in attribtutes tags if any
2033// - 2 if none found, getDeviceForInputSource() will:
2034// - 2.1 look for a mix matching the attributes source
2035// - 2.2 if none found, default to device selection by policy rules
2036// At this time, the corresponding output remote submix device is also connected
2037// and active playback use cases can be transferred to this mix if needed when reconnecting
2038// after AudioTracks are invalidated
2039//
2040// When playback starts, getOutputForAttr() will:
2041// - 1 look for a mix matching the address passed in attribtutes tags if any
2042// - 2 if none found, look for a mix matching the attributes usage
2043// - 3 if none found, default to device and output selection by policy rules.
2044
2045status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2046{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002047 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2048 status_t res = NO_ERROR;
2049
2050 sp<HwModule> rSubmixModule;
2051 // examine each mix's route type
2052 for (size_t i = 0; i < mixes.size(); i++) {
2053 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2054 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2055 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002056 break;
2057 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002058 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2059 // Loop back through "remote submix"
2060 if (rSubmixModule == 0) {
2061 for (size_t j = 0; i < mHwModules.size(); j++) {
2062 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2063 && mHwModules[j]->mHandle != 0) {
2064 rSubmixModule = mHwModules[j];
2065 break;
2066 }
2067 }
2068 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002069
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002070 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002071
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002072 if (rSubmixModule == 0) {
2073 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2074 res = INVALID_OPERATION;
2075 break;
2076 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002077
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002078 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002079
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002080 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002081 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002082 res = INVALID_OPERATION;
2083 break;
2084 }
2085 audio_config_t outputConfig = mixes[i].mFormat;
2086 audio_config_t inputConfig = mixes[i].mFormat;
2087 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2088 // stereo and let audio flinger do the channel conversion if needed.
2089 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2090 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2091 rSubmixModule->addOutputProfile(address, &outputConfig,
2092 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2093 rSubmixModule->addInputProfile(address, &inputConfig,
2094 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002095
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002096 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2097 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2098 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2099 address.string(), "remote-submix");
2100 } else {
2101 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2102 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2103 address.string(), "remote-submix");
2104 }
2105 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002106 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002107 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002108 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2109 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002110
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002111 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002112 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2113 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2114 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2115 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2116 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2117 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002118 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2119 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002120 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2121 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002122 } else {
2123 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002124 }
2125 break;
2126 }
2127 }
2128
2129 if (res != NO_ERROR) {
2130 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002131 i, device, address.string());
2132 res = INVALID_OPERATION;
2133 break;
2134 } else if (!foundOutput) {
2135 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2136 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002137 res = INVALID_OPERATION;
2138 break;
2139 }
Eric Laurentc722f302014-12-10 11:21:49 -08002140 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002141 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002142 if (res != NO_ERROR) {
2143 unregisterPolicyMixes(mixes);
2144 }
2145 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002146}
2147
2148status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2149{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002150 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002151 status_t res = NO_ERROR;
2152 sp<HwModule> rSubmixModule;
2153 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002154 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002155 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002156
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002157 if (rSubmixModule == 0) {
2158 for (size_t j = 0; i < mHwModules.size(); j++) {
2159 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2160 && mHwModules[j]->mHandle != 0) {
2161 rSubmixModule = mHwModules[j];
2162 break;
2163 }
2164 }
2165 }
2166 if (rSubmixModule == 0) {
2167 res = INVALID_OPERATION;
2168 continue;
2169 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002170
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002171 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002172
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002173 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2174 res = INVALID_OPERATION;
2175 continue;
2176 }
2177
2178 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2179 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2180 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2181 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2182 address.string(), "remote-submix");
2183 }
2184 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2185 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2186 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2187 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2188 address.string(), "remote-submix");
2189 }
2190 rSubmixModule->removeOutputProfile(address);
2191 rSubmixModule->removeInputProfile(address);
2192
2193 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2194 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2195 res = INVALID_OPERATION;
2196 continue;
2197 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002198 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002199 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002200 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002201}
2202
Eric Laurente552edb2014-03-10 17:42:56 -07002203
Eric Laurente0720872014-03-11 09:30:41 -07002204status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002205{
2206 const size_t SIZE = 256;
2207 char buffer[SIZE];
2208 String8 result;
2209
2210 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2211 result.append(buffer);
2212
Eric Laurent87ffa392015-05-22 10:32:38 -07002213 snprintf(buffer, SIZE, " Primary Output: %d\n",
2214 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002215 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002216 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002217 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002218 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002219 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002220 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002221 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002222 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002223 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002224 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002225 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002226 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002227 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002228 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002229 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002230 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002231 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002232 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2233 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2234 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002235 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2236 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002237 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2238 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002239
François Gaffie2110e042015-03-24 08:41:51 +01002240 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002241
François Gaffie112b0af2015-11-19 16:13:25 +01002242 mAvailableOutputDevices.dump(fd, String8("Available output"));
2243 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002244 mHwModules.dump(fd);
2245 mOutputs.dump(fd);
2246 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002247 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002248 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002249 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002250
2251 return NO_ERROR;
2252}
2253
2254// This function checks for the parameters which can be offloaded.
2255// This can be enhanced depending on the capability of the DSP and policy
2256// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002257bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002258{
2259 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002260 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002261 offloadInfo.sample_rate, offloadInfo.channel_mask,
2262 offloadInfo.format,
2263 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2264 offloadInfo.has_video);
2265
Andy Hung2ddee192015-12-18 17:34:44 -08002266 if (mMasterMono) {
2267 return false; // no offloading if mono is set.
2268 }
2269
Eric Laurente552edb2014-03-10 17:42:56 -07002270 // Check if offload has been disabled
2271 char propValue[PROPERTY_VALUE_MAX];
2272 if (property_get("audio.offload.disable", propValue, "0")) {
2273 if (atoi(propValue) != 0) {
2274 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2275 return false;
2276 }
2277 }
2278
2279 // Check if stream type is music, then only allow offload as of now.
2280 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2281 {
2282 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2283 return false;
2284 }
2285
2286 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002287 const bool allowOffloadWithVideo =
2288 property_get_bool("audio.offload.video", false /* default_value */);
2289 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002290 ALOGV("isOffloadSupported: has_video == true, returning false");
2291 return false;
2292 }
2293
2294 //If duration is less than minimum value defined in property, return false
2295 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2296 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2297 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2298 return false;
2299 }
2300 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2301 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2302 return false;
2303 }
2304
2305 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2306 // creating an offloaded track and tearing it down immediately after start when audioflinger
2307 // detects there is an active non offloadable effect.
2308 // FIXME: We should check the audio session here but we do not have it in this context.
2309 // This may prevent offloading in rare situations where effects are left active by apps
2310 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002311 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002312 return false;
2313 }
2314
2315 // See if there is a profile to support this.
2316 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002317 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002318 offloadInfo.sample_rate,
2319 offloadInfo.format,
2320 offloadInfo.channel_mask,
2321 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002322 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2323 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002324}
2325
Eric Laurent6a94d692014-05-20 11:18:06 -07002326status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2327 audio_port_type_t type,
2328 unsigned int *num_ports,
2329 struct audio_port *ports,
2330 unsigned int *generation)
2331{
2332 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2333 generation == NULL) {
2334 return BAD_VALUE;
2335 }
2336 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2337 if (ports == NULL) {
2338 *num_ports = 0;
2339 }
2340
2341 size_t portsWritten = 0;
2342 size_t portsMax = *num_ports;
2343 *num_ports = 0;
2344 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002345 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2346 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002347 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002348 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2349 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2350 continue;
2351 }
2352 if (portsWritten < portsMax) {
2353 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2354 }
2355 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002356 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002357 }
2358 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002359 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2360 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2361 continue;
2362 }
2363 if (portsWritten < portsMax) {
2364 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2365 }
2366 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002367 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002368 }
2369 }
2370 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2371 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2372 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2373 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2374 }
2375 *num_ports += mInputs.size();
2376 }
2377 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002378 size_t numOutputs = 0;
2379 for (size_t i = 0; i < mOutputs.size(); i++) {
2380 if (!mOutputs[i]->isDuplicated()) {
2381 numOutputs++;
2382 if (portsWritten < portsMax) {
2383 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2384 }
2385 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002386 }
Eric Laurent84c70242014-06-23 08:46:27 -07002387 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002388 }
2389 }
2390 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002391 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002392 return NO_ERROR;
2393}
2394
2395status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2396{
2397 return NO_ERROR;
2398}
2399
Eric Laurent6a94d692014-05-20 11:18:06 -07002400status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2401 audio_patch_handle_t *handle,
2402 uid_t uid)
2403{
2404 ALOGV("createAudioPatch()");
2405
2406 if (handle == NULL || patch == NULL) {
2407 return BAD_VALUE;
2408 }
2409 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2410
Eric Laurent874c42872014-08-08 15:13:39 -07002411 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2412 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2413 return BAD_VALUE;
2414 }
2415 // only one source per audio patch supported for now
2416 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002417 return INVALID_OPERATION;
2418 }
Eric Laurent874c42872014-08-08 15:13:39 -07002419
2420 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002421 return INVALID_OPERATION;
2422 }
Eric Laurent874c42872014-08-08 15:13:39 -07002423 for (size_t i = 0; i < patch->num_sinks; i++) {
2424 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2425 return INVALID_OPERATION;
2426 }
2427 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002428
2429 sp<AudioPatch> patchDesc;
2430 ssize_t index = mAudioPatches.indexOfKey(*handle);
2431
Eric Laurent6a94d692014-05-20 11:18:06 -07002432 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2433 patch->sources[0].role,
2434 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002435#if LOG_NDEBUG == 0
2436 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002437 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002438 patch->sinks[i].role,
2439 patch->sinks[i].type);
2440 }
2441#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002442
2443 if (index >= 0) {
2444 patchDesc = mAudioPatches.valueAt(index);
2445 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2446 mUidCached, patchDesc->mUid, uid);
2447 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2448 return INVALID_OPERATION;
2449 }
2450 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002451 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002452 }
2453
2454 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002455 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002456 if (outputDesc == NULL) {
2457 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2458 return BAD_VALUE;
2459 }
Eric Laurent84c70242014-06-23 08:46:27 -07002460 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2461 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002462 if (patchDesc != 0) {
2463 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2464 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2465 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2466 return BAD_VALUE;
2467 }
2468 }
Eric Laurent874c42872014-08-08 15:13:39 -07002469 DeviceVector devices;
2470 for (size_t i = 0; i < patch->num_sinks; i++) {
2471 // Only support mix to devices connection
2472 // TODO add support for mix to mix connection
2473 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2474 ALOGV("createAudioPatch() source mix but sink is not a device");
2475 return INVALID_OPERATION;
2476 }
2477 sp<DeviceDescriptor> devDesc =
2478 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2479 if (devDesc == 0) {
2480 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2481 return BAD_VALUE;
2482 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002483
François Gaffie53615e22015-03-19 09:24:12 +01002484 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002485 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002486 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002487 NULL, // updatedSamplingRate
2488 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002489 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002490 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002491 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002492 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002493 ALOGV("createAudioPatch() profile not supported for device %08x",
2494 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002495 return INVALID_OPERATION;
2496 }
2497 devices.add(devDesc);
2498 }
2499 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002500 return INVALID_OPERATION;
2501 }
Eric Laurent874c42872014-08-08 15:13:39 -07002502
Eric Laurent6a94d692014-05-20 11:18:06 -07002503 // TODO: reconfigure output format and channels here
2504 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002505 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002506 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002507 index = mAudioPatches.indexOfKey(*handle);
2508 if (index >= 0) {
2509 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2510 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2511 }
2512 patchDesc = mAudioPatches.valueAt(index);
2513 patchDesc->mUid = uid;
2514 ALOGV("createAudioPatch() success");
2515 } else {
2516 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2517 return INVALID_OPERATION;
2518 }
2519 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2520 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2521 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002522 // only one sink supported when connecting an input device to a mix
2523 if (patch->num_sinks > 1) {
2524 return INVALID_OPERATION;
2525 }
François Gaffie53615e22015-03-19 09:24:12 +01002526 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002527 if (inputDesc == NULL) {
2528 return BAD_VALUE;
2529 }
2530 if (patchDesc != 0) {
2531 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2532 return BAD_VALUE;
2533 }
2534 }
2535 sp<DeviceDescriptor> devDesc =
2536 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2537 if (devDesc == 0) {
2538 return BAD_VALUE;
2539 }
2540
François Gaffie53615e22015-03-19 09:24:12 +01002541 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002542 devDesc->mAddress,
2543 patch->sinks[0].sample_rate,
2544 NULL, /*updatedSampleRate*/
2545 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002546 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002547 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002548 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002549 // FIXME for the parameter type,
2550 // and the NONE
2551 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002552 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002553 return INVALID_OPERATION;
2554 }
2555 // TODO: reconfigure output format and channels here
2556 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002557 devDesc->type(), inputDesc->mIoHandle);
2558 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002559 index = mAudioPatches.indexOfKey(*handle);
2560 if (index >= 0) {
2561 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2562 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2563 }
2564 patchDesc = mAudioPatches.valueAt(index);
2565 patchDesc->mUid = uid;
2566 ALOGV("createAudioPatch() success");
2567 } else {
2568 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2569 return INVALID_OPERATION;
2570 }
2571 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2572 // device to device connection
2573 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002574 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002575 return BAD_VALUE;
2576 }
2577 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002578 sp<DeviceDescriptor> srcDeviceDesc =
2579 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002580 if (srcDeviceDesc == 0) {
2581 return BAD_VALUE;
2582 }
Eric Laurent874c42872014-08-08 15:13:39 -07002583
Eric Laurent6a94d692014-05-20 11:18:06 -07002584 //update source and sink with our own data as the data passed in the patch may
2585 // be incomplete.
2586 struct audio_patch newPatch = *patch;
2587 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002588
Eric Laurent874c42872014-08-08 15:13:39 -07002589 for (size_t i = 0; i < patch->num_sinks; i++) {
2590 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2591 ALOGV("createAudioPatch() source device but one sink is not a device");
2592 return INVALID_OPERATION;
2593 }
2594
2595 sp<DeviceDescriptor> sinkDeviceDesc =
2596 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2597 if (sinkDeviceDesc == 0) {
2598 return BAD_VALUE;
2599 }
2600 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2601
Eric Laurent3bcf8592015-04-03 12:13:24 -07002602 // create a software bridge in PatchPanel if:
2603 // - source and sink devices are on differnt HW modules OR
2604 // - audio HAL version is < 3.0
Eric Laurent232f26f2016-02-17 18:06:27 -08002605 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002606 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002607 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002608 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002609 return INVALID_OPERATION;
2610 }
Eric Laurent874c42872014-08-08 15:13:39 -07002611 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002612 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002613 // if the sink device is reachable via an opened output stream, request to go via
2614 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002615 audio_io_handle_t output = selectOutput(outputs,
2616 AUDIO_OUTPUT_FLAG_NONE,
2617 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002618 if (output != AUDIO_IO_HANDLE_NONE) {
2619 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2620 if (outputDesc->isDuplicated()) {
2621 return INVALID_OPERATION;
2622 }
2623 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002624 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002625 newPatch.num_sources = 2;
2626 }
Eric Laurent83b88082014-06-20 18:31:16 -07002627 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002628 }
2629 // TODO: check from routing capabilities in config file and other conflicting patches
2630
2631 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2632 if (index >= 0) {
2633 afPatchHandle = patchDesc->mAfPatchHandle;
2634 }
2635
2636 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2637 &afPatchHandle,
2638 0);
2639 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2640 status, afPatchHandle);
2641 if (status == NO_ERROR) {
2642 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002643 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002644 addAudioPatch(patchDesc->mHandle, patchDesc);
2645 } else {
2646 patchDesc->mPatch = newPatch;
2647 }
2648 patchDesc->mAfPatchHandle = afPatchHandle;
2649 *handle = patchDesc->mHandle;
2650 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002651 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002652 } else {
2653 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2654 status);
2655 return INVALID_OPERATION;
2656 }
2657 } else {
2658 return BAD_VALUE;
2659 }
2660 } else {
2661 return BAD_VALUE;
2662 }
2663 return NO_ERROR;
2664}
2665
2666status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2667 uid_t uid)
2668{
2669 ALOGV("releaseAudioPatch() patch %d", handle);
2670
2671 ssize_t index = mAudioPatches.indexOfKey(handle);
2672
2673 if (index < 0) {
2674 return BAD_VALUE;
2675 }
2676 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2677 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2678 mUidCached, patchDesc->mUid, uid);
2679 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2680 return INVALID_OPERATION;
2681 }
2682
2683 struct audio_patch *patch = &patchDesc->mPatch;
2684 patchDesc->mUid = mUidCached;
2685 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002687 if (outputDesc == NULL) {
2688 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2689 return BAD_VALUE;
2690 }
2691
Eric Laurentc75307b2015-03-17 15:29:32 -07002692 setOutputDevice(outputDesc,
2693 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002694 true,
2695 0,
2696 NULL);
2697 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2698 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002699 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002700 if (inputDesc == NULL) {
2701 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2702 return BAD_VALUE;
2703 }
2704 setInputDevice(inputDesc->mIoHandle,
Eric Laurent232f26f2016-02-17 18:06:27 -08002705 getNewInputDevice(inputDesc->mIoHandle),
Eric Laurent6a94d692014-05-20 11:18:06 -07002706 true,
2707 NULL);
2708 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2709 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2710 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2711 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2712 status, patchDesc->mAfPatchHandle);
2713 removeAudioPatch(patchDesc->mHandle);
2714 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002715 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002716 } else {
2717 return BAD_VALUE;
2718 }
2719 } else {
2720 return BAD_VALUE;
2721 }
2722 return NO_ERROR;
2723}
2724
2725status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2726 struct audio_patch *patches,
2727 unsigned int *generation)
2728{
François Gaffie53615e22015-03-19 09:24:12 +01002729 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002730 return BAD_VALUE;
2731 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002732 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002733 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002734}
2735
Eric Laurente1715a42014-05-20 11:30:42 -07002736status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002737{
Eric Laurente1715a42014-05-20 11:30:42 -07002738 ALOGV("setAudioPortConfig()");
2739
2740 if (config == NULL) {
2741 return BAD_VALUE;
2742 }
2743 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2744 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002745 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2746 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002747 }
2748
Eric Laurenta121f902014-06-03 13:32:54 -07002749 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002750 if (config->type == AUDIO_PORT_TYPE_MIX) {
2751 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002752 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002753 if (outputDesc == NULL) {
2754 return BAD_VALUE;
2755 }
Eric Laurent84c70242014-06-23 08:46:27 -07002756 ALOG_ASSERT(!outputDesc->isDuplicated(),
2757 "setAudioPortConfig() called on duplicated output %d",
2758 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002759 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002760 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002761 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002762 if (inputDesc == NULL) {
2763 return BAD_VALUE;
2764 }
Eric Laurenta121f902014-06-03 13:32:54 -07002765 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002766 } else {
2767 return BAD_VALUE;
2768 }
2769 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2770 sp<DeviceDescriptor> deviceDesc;
2771 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2772 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2773 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2774 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2775 } else {
2776 return BAD_VALUE;
2777 }
2778 if (deviceDesc == NULL) {
2779 return BAD_VALUE;
2780 }
Eric Laurenta121f902014-06-03 13:32:54 -07002781 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002782 } else {
2783 return BAD_VALUE;
2784 }
2785
Eric Laurenta121f902014-06-03 13:32:54 -07002786 struct audio_port_config backupConfig;
2787 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2788 if (status == NO_ERROR) {
2789 struct audio_port_config newConfig;
2790 audioPortConfig->toAudioPortConfig(&newConfig, config);
2791 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002792 }
Eric Laurenta121f902014-06-03 13:32:54 -07002793 if (status != NO_ERROR) {
2794 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002795 }
Eric Laurente1715a42014-05-20 11:30:42 -07002796
2797 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002798}
2799
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002800void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2801{
Eric Laurentd60560a2015-04-10 11:31:20 -07002802 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002803 clearAudioPatches(uid);
2804 clearSessionRoutes(uid);
2805}
2806
Eric Laurent6a94d692014-05-20 11:18:06 -07002807void AudioPolicyManager::clearAudioPatches(uid_t uid)
2808{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002809 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002810 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2811 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002812 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002813 }
2814 }
2815}
2816
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002817void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2818 audio_io_handle_t ouptutToSkip)
2819{
2820 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2821 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2822 for (size_t j = 0; j < mOutputs.size(); j++) {
2823 if (mOutputs.keyAt(j) == ouptutToSkip) {
2824 continue;
2825 }
2826 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2827 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2828 continue;
2829 }
2830 // If the default device for this strategy is on another output mix,
2831 // invalidate all tracks in this strategy to force re connection.
2832 // Otherwise select new device on the output mix.
2833 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002834 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002835 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2836 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2837 }
2838 }
2839 } else {
2840 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2841 setOutputDevice(outputDesc, newDevice, false);
2842 }
2843 }
2844}
2845
2846void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2847{
2848 // remove output routes associated with this uid
2849 SortedVector<routing_strategy> affectedStrategies;
2850 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2851 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2852 if (route->mUid == uid) {
2853 mOutputRoutes.removeItemsAt(i);
2854 if (route->mDeviceDescriptor != 0) {
2855 affectedStrategies.add(getStrategy(route->mStreamType));
2856 }
2857 }
2858 }
2859 // reroute outputs if necessary
2860 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2861 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2862 }
2863
2864 // remove input routes associated with this uid
2865 SortedVector<audio_source_t> affectedSources;
2866 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2867 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2868 if (route->mUid == uid) {
2869 mInputRoutes.removeItemsAt(i);
2870 if (route->mDeviceDescriptor != 0) {
2871 affectedSources.add(route->mSource);
2872 }
2873 }
2874 }
2875 // reroute inputs if necessary
2876 SortedVector<audio_io_handle_t> inputsToClose;
2877 for (size_t i = 0; i < mInputs.size(); i++) {
2878 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002879 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002880 inputsToClose.add(inputDesc->mIoHandle);
2881 }
2882 }
2883 for (size_t i = 0; i < inputsToClose.size(); i++) {
2884 closeInput(inputsToClose[i]);
2885 }
2886}
2887
Eric Laurentd60560a2015-04-10 11:31:20 -07002888void AudioPolicyManager::clearAudioSources(uid_t uid)
2889{
2890 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2891 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2892 if (sourceDesc->mUid == uid) {
2893 stopAudioSource(mAudioSources.keyAt(i));
2894 }
2895 }
2896}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002897
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002898status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2899 audio_io_handle_t *ioHandle,
2900 audio_devices_t *device)
2901{
Glenn Kasteneeecb982016-02-26 10:44:04 -08002902 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2903 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002904 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002905
François Gaffiedf372692015-03-19 10:43:27 +01002906 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002907}
2908
Eric Laurentd60560a2015-04-10 11:31:20 -07002909status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2910 const audio_attributes_t *attributes,
2911 audio_io_handle_t *handle,
2912 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002913{
Eric Laurentd60560a2015-04-10 11:31:20 -07002914 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2915 if (source == NULL || attributes == NULL || handle == NULL) {
2916 return BAD_VALUE;
2917 }
2918
2919 *handle = AUDIO_IO_HANDLE_NONE;
2920
2921 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2922 source->type != AUDIO_PORT_TYPE_DEVICE) {
2923 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2924 return INVALID_OPERATION;
2925 }
2926
2927 sp<DeviceDescriptor> srcDeviceDesc =
2928 mAvailableInputDevices.getDevice(source->ext.device.type,
2929 String8(source->ext.device.address));
2930 if (srcDeviceDesc == 0) {
2931 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2932 return BAD_VALUE;
2933 }
2934 sp<AudioSourceDescriptor> sourceDesc =
2935 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2936
2937 struct audio_patch dummyPatch;
2938 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2939 sourceDesc->mPatchDesc = patchDesc;
2940
2941 status_t status = connectAudioSource(sourceDesc);
2942 if (status == NO_ERROR) {
2943 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2944 *handle = sourceDesc->getHandle();
2945 }
2946 return status;
2947}
2948
2949status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2950{
2951 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2952
2953 // make sure we only have one patch per source.
2954 disconnectAudioSource(sourceDesc);
2955
2956 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08002957 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07002958 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2959
2960 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2961 sp<DeviceDescriptor> sinkDeviceDesc =
2962 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2963
2964 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2965 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2966
2967 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2968 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002969 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002970 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2971 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2972 // create patch between src device and output device
2973 // create Hwoutput and add to mHwOutputs
2974 } else {
2975 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2976 audio_io_handle_t output =
2977 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2978 if (output == AUDIO_IO_HANDLE_NONE) {
2979 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2980 return INVALID_OPERATION;
2981 }
2982 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2983 if (outputDesc->isDuplicated()) {
2984 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2985 return INVALID_OPERATION;
2986 }
2987 // create a special patch with no sink and two sources:
2988 // - the second source indicates to PatchPanel through which output mix this patch should
2989 // be connected as well as the stream type for volume control
2990 // - the sink is defined by whatever output device is currently selected for the output
2991 // though which this patch is routed.
2992 patch->num_sinks = 0;
2993 patch->num_sources = 2;
2994 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2995 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2996 patch->sources[1].ext.mix.usecase.stream = stream;
2997 status_t status = mpClientInterface->createAudioPatch(patch,
2998 &afPatchHandle,
2999 0);
3000 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3001 status, afPatchHandle);
3002 if (status != NO_ERROR) {
3003 ALOGW("%s patch panel could not connect device patch, error %d",
3004 __FUNCTION__, status);
3005 return INVALID_OPERATION;
3006 }
3007 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07003008 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07003009
3010 if (status != NO_ERROR) {
3011 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3012 return status;
3013 }
3014 sourceDesc->mSwOutput = outputDesc;
3015 if (delayMs != 0) {
3016 usleep(delayMs * 1000);
3017 }
3018 }
3019
3020 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3021 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3022
3023 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003024}
3025
Eric Laurent493404d2015-04-21 15:07:36 -07003026status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003027{
Eric Laurentd60560a2015-04-10 11:31:20 -07003028 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3029 ALOGV("%s handle %d", __FUNCTION__, handle);
3030 if (sourceDesc == 0) {
3031 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3032 return BAD_VALUE;
3033 }
3034 status_t status = disconnectAudioSource(sourceDesc);
3035
3036 mAudioSources.removeItem(handle);
3037 return status;
3038}
3039
Andy Hung2ddee192015-12-18 17:34:44 -08003040status_t AudioPolicyManager::setMasterMono(bool mono)
3041{
3042 if (mMasterMono == mono) {
3043 return NO_ERROR;
3044 }
3045 mMasterMono = mono;
3046 // if enabling mono we close all offloaded devices, which will invalidate the
3047 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3048 // for recreating the new AudioTrack as non-offloaded PCM.
3049 //
3050 // If disabling mono, we leave all tracks as is: we don't know which clients
3051 // and tracks are able to be recreated as offloaded. The next "song" should
3052 // play back offloaded.
3053 if (mMasterMono) {
3054 Vector<audio_io_handle_t> offloaded;
3055 for (size_t i = 0; i < mOutputs.size(); ++i) {
3056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3057 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3058 offloaded.push(desc->mIoHandle);
3059 }
3060 }
3061 for (size_t i = 0; i < offloaded.size(); ++i) {
3062 closeOutput(offloaded[i]);
3063 }
3064 }
3065 // update master mono for all remaining outputs
3066 for (size_t i = 0; i < mOutputs.size(); ++i) {
3067 updateMono(mOutputs.keyAt(i));
3068 }
3069 return NO_ERROR;
3070}
3071
3072status_t AudioPolicyManager::getMasterMono(bool *mono)
3073{
3074 *mono = mMasterMono;
3075 return NO_ERROR;
3076}
3077
Eric Laurentd60560a2015-04-10 11:31:20 -07003078status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3079{
3080 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3081
3082 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3083 if (patchDesc == 0) {
3084 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3085 sourceDesc->mPatchDesc->mHandle);
3086 return BAD_VALUE;
3087 }
3088 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3089
Eric Laurent28d09f02016-03-08 10:43:05 -08003090 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003091 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3092 if (swOutputDesc != 0) {
3093 stopSource(swOutputDesc, stream, false);
3094 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3095 } else {
3096 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3097 if (hwOutputDesc != 0) {
3098 // release patch between src device and output device
3099 // close Hwoutput and remove from mHwOutputs
3100 } else {
3101 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3102 }
3103 }
3104 return NO_ERROR;
3105}
3106
3107sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3108 audio_io_handle_t output, routing_strategy strategy)
3109{
3110 sp<AudioSourceDescriptor> source;
3111 for (size_t i = 0; i < mAudioSources.size(); i++) {
3112 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3113 routing_strategy sourceStrategy =
3114 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3115 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3116 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3117 source = sourceDesc;
3118 break;
3119 }
3120 }
3121 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003122}
3123
Eric Laurente552edb2014-03-10 17:42:56 -07003124// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003125// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003126// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003127uint32_t AudioPolicyManager::nextAudioPortGeneration()
3128{
3129 return android_atomic_inc(&mAudioPortGeneration);
3130}
3131
Eric Laurente0720872014-03-11 09:30:41 -07003132AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003133 :
3134#ifdef AUDIO_POLICY_TEST
3135 Thread(false),
3136#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003137 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003138 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003139 mAudioPortGeneration(1),
3140 mBeaconMuteRefCount(0),
3141 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003142 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003143 mTtsOutputAvailable(false),
3144 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003145{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003146 mUidCached = getuid();
3147 mpClientInterface = clientInterface;
3148
3149 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3150 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3151 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3152 bool speakerDrcEnabled = false;
3153
3154#ifdef USE_XML_AUDIO_POLICY_CONF
3155 mVolumeCurves = new VolumeCurvesCollection();
3156 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3157 mDefaultOutputDevice, speakerDrcEnabled,
3158 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3159 PolicySerializer serializer;
3160 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3161#else
3162 mVolumeCurves = new StreamDescriptorCollection();
3163 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3164 mDefaultOutputDevice, speakerDrcEnabled);
3165 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3166 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3167#endif
3168 ALOGE("could not load audio policy configuration file, setting defaults");
3169 config.setDefault();
3170 }
3171 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3172 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3173
3174 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003175 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3176 if (!engineInstance) {
3177 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3178 return;
3179 }
3180 // Retrieve the Policy Manager Interface
3181 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3182 if (mEngine == NULL) {
3183 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3184 return;
3185 }
3186 mEngine->setObserver(this);
3187 status_t status = mEngine->initCheck();
3188 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3189
Eric Laurent3a4311c2014-03-17 12:00:47 -07003190 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003191 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003192 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3193 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003194 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003195 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003196 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003197 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003198 continue;
3199 }
3200 // open all output streams needed to access attached devices
3201 // except for direct output streams that are only opened when they are actually
3202 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003203 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003204 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3205 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003206 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003207
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003208 if (!outProfile->hasSupportedDevices()) {
3209 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003210 continue;
3211 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003212 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003213 mTtsOutputAvailable = true;
3214 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003215
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003216 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003217 continue;
3218 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003219 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003220 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3221 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003222 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003223 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003224 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003225 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003226 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003227 if ((profileType & outputDeviceTypes) == 0) {
3228 continue;
3229 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003230 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3231 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003232 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3233 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3234 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3235 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003236
3237 outputDesc->mDevice = profileType;
3238 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3239 config.sample_rate = outputDesc->mSamplingRate;
3240 config.channel_mask = outputDesc->mChannelMask;
3241 config.format = outputDesc->mFormat;
3242 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003243 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003244 &output,
3245 &config,
3246 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003247 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003248 &outputDesc->mLatency,
3249 outputDesc->mFlags);
3250
3251 if (status != NO_ERROR) {
3252 ALOGW("Cannot open output stream for device %08x on hw module %s",
3253 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003254 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003255 } else {
3256 outputDesc->mSamplingRate = config.sample_rate;
3257 outputDesc->mChannelMask = config.channel_mask;
3258 outputDesc->mFormat = config.format;
3259
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003260 for (size_t k = 0; k < supportedDevices.size(); k++) {
3261 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003262 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003263 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3264 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003265 }
3266 }
3267 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003268 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003269 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003270 }
3271 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003272 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003273 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003274 true,
3275 0,
3276 NULL,
3277 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003278 }
Eric Laurente552edb2014-03-10 17:42:56 -07003279 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003280 // open input streams needed to access attached devices to validate
3281 // mAvailableInputDevices list
3282 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3283 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003284 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003285
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003286 if (!inProfile->hasSupportedDevices()) {
3287 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003288 continue;
3289 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003290 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003291 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003292 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3293
Eric Laurentd78f1532014-09-16 16:38:20 -07003294 if ((profileType & inputDeviceTypes) == 0) {
3295 continue;
3296 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003297 sp<AudioInputDescriptor> inputDesc =
3298 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003299
Eric Laurentd78f1532014-09-16 16:38:20 -07003300 inputDesc->mDevice = profileType;
3301
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003302 // find the address
3303 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3304 // the inputs vector must be of size 1, but we don't want to crash here
3305 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3306 : String8("");
3307 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3308 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3309
Eric Laurentd78f1532014-09-16 16:38:20 -07003310 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3311 config.sample_rate = inputDesc->mSamplingRate;
3312 config.channel_mask = inputDesc->mChannelMask;
3313 config.format = inputDesc->mFormat;
3314 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003315 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003316 &input,
3317 &config,
3318 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003319 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003320 AUDIO_SOURCE_MIC,
3321 AUDIO_INPUT_FLAG_NONE);
3322
3323 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003324 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3325 for (size_t k = 0; k < supportedDevices.size(); k++) {
3326 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003327 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003328 if (index >= 0) {
3329 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3330 if (!devDesc->isAttached()) {
3331 devDesc->attach(mHwModules[i]);
3332 devDesc->importAudioPort(inProfile);
3333 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003334 }
3335 }
3336 mpClientInterface->closeInput(input);
3337 } else {
3338 ALOGW("Cannot open input stream for device %08x on hw module %s",
3339 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003340 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003341 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003342 }
3343 }
3344 // make sure all attached devices have been allocated a unique ID
3345 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003346 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003347 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003348 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3349 continue;
3350 }
François Gaffie2110e042015-03-24 08:41:51 +01003351 // The device is now validated and can be appended to the available devices of the engine
3352 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3353 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003354 i++;
3355 }
3356 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003357 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003358 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003359 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3360 continue;
3361 }
François Gaffie2110e042015-03-24 08:41:51 +01003362 // The device is now validated and can be appended to the available devices of the engine
3363 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3364 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003365 i++;
3366 }
3367 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003368 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003369 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003370 }
Eric Laurente552edb2014-03-10 17:42:56 -07003371
3372 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3373
3374 updateDevicesAndOutputs();
3375
3376#ifdef AUDIO_POLICY_TEST
3377 if (mPrimaryOutput != 0) {
3378 AudioParameter outputCmd = AudioParameter();
3379 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003380 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003381
3382 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3383 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003384 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3385 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003386 mTestLatencyMs = 0;
3387 mCurOutput = 0;
3388 mDirectOutput = false;
3389 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3390 mTestOutputs[i] = 0;
3391 }
3392
3393 const size_t SIZE = 256;
3394 char buffer[SIZE];
3395 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3396 run(buffer, ANDROID_PRIORITY_AUDIO);
3397 }
3398#endif //AUDIO_POLICY_TEST
3399}
3400
Eric Laurente0720872014-03-11 09:30:41 -07003401AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003402{
3403#ifdef AUDIO_POLICY_TEST
3404 exit();
3405#endif //AUDIO_POLICY_TEST
3406 for (size_t i = 0; i < mOutputs.size(); i++) {
3407 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003408 }
3409 for (size_t i = 0; i < mInputs.size(); i++) {
3410 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003411 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003412 mAvailableOutputDevices.clear();
3413 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003414 mOutputs.clear();
3415 mInputs.clear();
3416 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003417}
3418
Eric Laurente0720872014-03-11 09:30:41 -07003419status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003420{
Eric Laurent87ffa392015-05-22 10:32:38 -07003421 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003422}
3423
3424#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003425bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003426{
3427 ALOGV("entering threadLoop()");
3428 while (!exitPending())
3429 {
3430 String8 command;
3431 int valueInt;
3432 String8 value;
3433
3434 Mutex::Autolock _l(mLock);
3435 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3436
3437 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3438 AudioParameter param = AudioParameter(command);
3439
3440 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3441 valueInt != 0) {
3442 ALOGV("Test command %s received", command.string());
3443 String8 target;
3444 if (param.get(String8("target"), target) != NO_ERROR) {
3445 target = "Manager";
3446 }
3447 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3448 param.remove(String8("test_cmd_policy_output"));
3449 mCurOutput = valueInt;
3450 }
3451 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3452 param.remove(String8("test_cmd_policy_direct"));
3453 if (value == "false") {
3454 mDirectOutput = false;
3455 } else if (value == "true") {
3456 mDirectOutput = true;
3457 }
3458 }
3459 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3460 param.remove(String8("test_cmd_policy_input"));
3461 mTestInput = valueInt;
3462 }
3463
3464 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3465 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003466 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003467 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003468 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003469 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003470 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003471 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003472 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003473 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003474 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003475 if (target == "Manager") {
3476 mTestFormat = format;
3477 } else if (mTestOutputs[mCurOutput] != 0) {
3478 AudioParameter outputParam = AudioParameter();
3479 outputParam.addInt(String8("format"), format);
3480 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3481 }
3482 }
3483 }
3484 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3485 param.remove(String8("test_cmd_policy_channels"));
3486 int channels = 0;
3487
3488 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003489 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003490 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003491 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003492 }
3493 if (channels != 0) {
3494 if (target == "Manager") {
3495 mTestChannels = channels;
3496 } else if (mTestOutputs[mCurOutput] != 0) {
3497 AudioParameter outputParam = AudioParameter();
3498 outputParam.addInt(String8("channels"), channels);
3499 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3500 }
3501 }
3502 }
3503 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3504 param.remove(String8("test_cmd_policy_sampleRate"));
3505 if (valueInt >= 0 && valueInt <= 96000) {
3506 int samplingRate = valueInt;
3507 if (target == "Manager") {
3508 mTestSamplingRate = samplingRate;
3509 } else if (mTestOutputs[mCurOutput] != 0) {
3510 AudioParameter outputParam = AudioParameter();
3511 outputParam.addInt(String8("sampling_rate"), samplingRate);
3512 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3513 }
3514 }
3515 }
3516
3517 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3518 param.remove(String8("test_cmd_policy_reopen"));
3519
Eric Laurentc75307b2015-03-17 15:29:32 -07003520 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003521
Eric Laurentc75307b2015-03-17 15:29:32 -07003522 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003523
Eric Laurentc75307b2015-03-17 15:29:32 -07003524 removeOutput(mPrimaryOutput->mIoHandle);
3525 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3526 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003527 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003528 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3529 config.sample_rate = outputDesc->mSamplingRate;
3530 config.channel_mask = outputDesc->mChannelMask;
3531 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003532 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003533 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003534 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003535 &config,
3536 &outputDesc->mDevice,
3537 String8(""),
3538 &outputDesc->mLatency,
3539 outputDesc->mFlags);
3540 if (status != NO_ERROR) {
3541 ALOGE("Failed to reopen hardware output stream, "
3542 "samplingRate: %d, format %d, channels %d",
3543 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003544 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003545 outputDesc->mSamplingRate = config.sample_rate;
3546 outputDesc->mChannelMask = config.channel_mask;
3547 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003548 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003549 AudioParameter outputCmd = AudioParameter();
3550 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003551 mpClientInterface->setParameters(handle, outputCmd.toString());
3552 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003553 }
3554 }
3555
3556
3557 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3558 }
3559 }
3560 return false;
3561}
3562
Eric Laurente0720872014-03-11 09:30:41 -07003563void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003564{
3565 {
3566 AutoMutex _l(mLock);
3567 requestExit();
3568 mWaitWorkCV.signal();
3569 }
3570 requestExitAndWait();
3571}
3572
Eric Laurente0720872014-03-11 09:30:41 -07003573int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003574{
3575 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3576 if (output == mTestOutputs[i]) return i;
3577 }
3578 return 0;
3579}
3580#endif //AUDIO_POLICY_TEST
3581
3582// ---
3583
Eric Laurentc75307b2015-03-17 15:29:32 -07003584void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003585{
François Gaffie98cc1912015-03-18 17:52:40 +01003586 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003587 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003588 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003589 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003590}
3591
François Gaffie53615e22015-03-19 09:24:12 +01003592void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3593{
3594 mOutputs.removeItem(output);
3595}
3596
Eric Laurent1f2f2232014-06-02 12:01:23 -07003597void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003598{
François Gaffie98cc1912015-03-18 17:52:40 +01003599 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003600 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003601 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003602}
Eric Laurente552edb2014-03-10 17:42:56 -07003603
Eric Laurentc75307b2015-03-17 15:29:32 -07003604void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003605 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003606 const String8 address /*in*/,
3607 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003608 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003609 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003610 if (devDesc != 0) {
3611 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3612 desc->mIoHandle, address.string());
3613 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003614 }
3615}
3616
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003617status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003618 audio_policy_dev_state_t state,
3619 SortedVector<audio_io_handle_t>& outputs,
3620 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003621{
François Gaffie53615e22015-03-19 09:24:12 +01003622 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003623 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003624
3625 if (audio_device_is_digital(device)) {
3626 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003627 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003628 }
Eric Laurente552edb2014-03-10 17:42:56 -07003629
Eric Laurent3b73df72014-03-11 09:06:29 -07003630 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003631 // first list already open outputs that can be routed to this device
3632 for (size_t i = 0; i < mOutputs.size(); i++) {
3633 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003634 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003635 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003636 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3637 outputs.add(mOutputs.keyAt(i));
3638 } else {
3639 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003640 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003641 }
Eric Laurente552edb2014-03-10 17:42:56 -07003642 }
3643 }
3644 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003645 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003646 for (size_t i = 0; i < mHwModules.size(); i++)
3647 {
3648 if (mHwModules[i]->mHandle == 0) {
3649 continue;
3650 }
3651 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3652 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003653 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003654 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003655 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003656 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003657 profiles.add(profile);
3658 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3659 }
Eric Laurente552edb2014-03-10 17:42:56 -07003660 }
3661 }
3662 }
3663
Eric Laurent7b279bb2015-12-14 10:18:23 -08003664 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003665
Eric Laurente552edb2014-03-10 17:42:56 -07003666 if (profiles.isEmpty() && outputs.isEmpty()) {
3667 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3668 return BAD_VALUE;
3669 }
3670
3671 // open outputs for matching profiles if needed. Direct outputs are also opened to
3672 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3673 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003674 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003675
3676 // nothing to do if one output is already opened for this profile
3677 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003678 for (j = 0; j < outputs.size(); j++) {
3679 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003680 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003681 // matching profile: save the sample rates, format and channel masks supported
3682 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003683 if (audio_device_is_digital(device)) {
3684 devDesc->importAudioPort(profile);
3685 }
Eric Laurente552edb2014-03-10 17:42:56 -07003686 break;
3687 }
3688 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003689 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003690 continue;
3691 }
3692
Eric Laurent83b88082014-06-20 18:31:16 -07003693 ALOGV("opening output for device %08x with params %s profile %p",
3694 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003695 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003696 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003697 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3698 config.sample_rate = desc->mSamplingRate;
3699 config.channel_mask = desc->mChannelMask;
3700 config.format = desc->mFormat;
3701 config.offload_info.sample_rate = desc->mSamplingRate;
3702 config.offload_info.channel_mask = desc->mChannelMask;
3703 config.offload_info.format = desc->mFormat;
3704 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003705 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003706 &output,
3707 &config,
3708 &desc->mDevice,
3709 address,
3710 &desc->mLatency,
3711 desc->mFlags);
3712 if (status == NO_ERROR) {
3713 desc->mSamplingRate = config.sample_rate;
3714 desc->mChannelMask = config.channel_mask;
3715 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003716
Eric Laurentd4692962014-05-05 18:13:44 -07003717 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003718 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003719 char *param = audio_device_address_to_parameter(device, address);
3720 mpClientInterface->setParameters(output, String8(param));
3721 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003722 }
Phil Burk00eeb322016-03-31 12:41:00 -07003723 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003724 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003725 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003726 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003727 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003728 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003729 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003730 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003731 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003732 config.offload_info.sample_rate = config.sample_rate;
3733 config.offload_info.channel_mask = config.channel_mask;
3734 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003735 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003736 &output,
3737 &config,
3738 &desc->mDevice,
3739 address,
3740 &desc->mLatency,
3741 desc->mFlags);
3742 if (status == NO_ERROR) {
3743 desc->mSamplingRate = config.sample_rate;
3744 desc->mChannelMask = config.channel_mask;
3745 desc->mFormat = config.format;
3746 } else {
3747 output = AUDIO_IO_HANDLE_NONE;
3748 }
Eric Laurentd4692962014-05-05 18:13:44 -07003749 }
3750
Eric Laurentcf2c0212014-07-25 16:20:43 -07003751 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003752 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003753 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003754 sp<AudioPolicyMix> policyMix;
3755 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003756 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3757 address.string());
3758 }
François Gaffie036e1e92015-03-19 10:16:24 +01003759 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003760 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003761
Eric Laurent87ffa392015-05-22 10:32:38 -07003762 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3763 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003764 // no duplicated output for direct outputs and
3765 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003766 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003767
Eric Laurentd4692962014-05-05 18:13:44 -07003768 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003769 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003770
Eric Laurentd4692962014-05-05 18:13:44 -07003771 //TODO: configure audio effect output stage here
3772
3773 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003774 duplicatedOutput =
3775 mpClientInterface->openDuplicateOutput(output,
3776 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003777 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003778 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003779 sp<SwAudioOutputDescriptor> dupOutputDesc =
3780 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3781 dupOutputDesc->mOutput1 = mPrimaryOutput;
3782 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003783 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3784 dupOutputDesc->mFormat = desc->mFormat;
3785 dupOutputDesc->mChannelMask = desc->mChannelMask;
3786 dupOutputDesc->mLatency = desc->mLatency;
3787 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003788 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003789 } else {
3790 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003791 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003792 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003793 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003794 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003795 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003796 }
Eric Laurente552edb2014-03-10 17:42:56 -07003797 }
3798 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003799 } else {
3800 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003801 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003802 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003803 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003804 profiles.removeAt(profile_index);
3805 profile_index--;
3806 } else {
3807 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003808 // Load digital format info only for digital devices
3809 if (audio_device_is_digital(device)) {
3810 devDesc->importAudioPort(profile);
3811 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003812
François Gaffie53615e22015-03-19 09:24:12 +01003813 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003814 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3815 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003816 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003817 NULL/*patch handle*/, address.string());
3818 }
Eric Laurente552edb2014-03-10 17:42:56 -07003819 ALOGV("checkOutputsForDevice(): adding output %d", output);
3820 }
3821 }
3822
3823 if (profiles.isEmpty()) {
3824 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3825 return BAD_VALUE;
3826 }
Eric Laurentd4692962014-05-05 18:13:44 -07003827 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003828 // check if one opened output is not needed any more after disconnecting one device
3829 for (size_t i = 0; i < mOutputs.size(); i++) {
3830 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003831 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003832 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003833 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003834 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003835 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003836 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003837 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3838 mOutputs.keyAt(i));
3839 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003840 }
Eric Laurente552edb2014-03-10 17:42:56 -07003841 }
3842 }
Eric Laurentd4692962014-05-05 18:13:44 -07003843 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003844 for (size_t i = 0; i < mHwModules.size(); i++)
3845 {
3846 if (mHwModules[i]->mHandle == 0) {
3847 continue;
3848 }
3849 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3850 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003851 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003852 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003853 ALOGV("checkOutputsForDevice(): "
3854 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003855 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003856 }
3857 }
3858 }
3859 }
3860 return NO_ERROR;
3861}
3862
Paul McLean9080a4c2015-06-18 08:24:02 -07003863status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003864 audio_policy_dev_state_t state,
3865 SortedVector<audio_io_handle_t>& inputs,
3866 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003867{
Paul McLean9080a4c2015-06-18 08:24:02 -07003868 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003869 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003870
3871 if (audio_device_is_digital(device)) {
3872 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003873 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003874 }
3875
Eric Laurentd4692962014-05-05 18:13:44 -07003876 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3877 // first list already open inputs that can be routed to this device
3878 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3879 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003880 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003881 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3882 inputs.add(mInputs.keyAt(input_index));
3883 }
3884 }
3885
3886 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003887 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003888 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3889 {
3890 if (mHwModules[module_idx]->mHandle == 0) {
3891 continue;
3892 }
3893 for (size_t profile_index = 0;
3894 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3895 profile_index++)
3896 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003897 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3898
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003899 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003900 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003901 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003902 profiles.add(profile);
3903 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3904 profile_index, module_idx);
3905 }
Eric Laurentd4692962014-05-05 18:13:44 -07003906 }
3907 }
3908 }
3909
3910 if (profiles.isEmpty() && inputs.isEmpty()) {
3911 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3912 return BAD_VALUE;
3913 }
3914
3915 // open inputs for matching profiles if needed. Direct inputs are also opened to
3916 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3917 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3918
Eric Laurent1c333e22014-05-20 10:48:17 -07003919 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003920 // nothing to do if one input is already opened for this profile
3921 size_t input_index;
3922 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3923 desc = mInputs.valueAt(input_index);
3924 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003925 if (audio_device_is_digital(device)) {
3926 devDesc->importAudioPort(profile);
3927 }
Eric Laurentd4692962014-05-05 18:13:44 -07003928 break;
3929 }
3930 }
3931 if (input_index != mInputs.size()) {
3932 continue;
3933 }
3934
3935 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3936 desc = new AudioInputDescriptor(profile);
3937 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003938 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3939 config.sample_rate = desc->mSamplingRate;
3940 config.channel_mask = desc->mChannelMask;
3941 config.format = desc->mFormat;
3942 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003943 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003944 &input,
3945 &config,
3946 &desc->mDevice,
3947 address,
3948 AUDIO_SOURCE_MIC,
3949 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003950
Eric Laurentcf2c0212014-07-25 16:20:43 -07003951 if (status == NO_ERROR) {
3952 desc->mSamplingRate = config.sample_rate;
3953 desc->mChannelMask = config.channel_mask;
3954 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003955
Eric Laurentd4692962014-05-05 18:13:44 -07003956 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003957 char *param = audio_device_address_to_parameter(device, address);
3958 mpClientInterface->setParameters(input, String8(param));
3959 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003960 }
Phil Burk00eeb322016-03-31 12:41:00 -07003961 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003962 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003963 ALOGW("checkInputsForDevice() direct input missing param");
3964 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003965 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003966 }
3967
3968 if (input != 0) {
3969 addInput(input, desc);
3970 }
3971 } // endif input != 0
3972
Eric Laurentcf2c0212014-07-25 16:20:43 -07003973 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003974 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003975 profiles.removeAt(profile_index);
3976 profile_index--;
3977 } else {
3978 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003979 if (audio_device_is_digital(device)) {
3980 devDesc->importAudioPort(profile);
3981 }
Eric Laurentd4692962014-05-05 18:13:44 -07003982 ALOGV("checkInputsForDevice(): adding input %d", input);
3983 }
3984 } // end scan profiles
3985
3986 if (profiles.isEmpty()) {
3987 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3988 return BAD_VALUE;
3989 }
3990 } else {
3991 // Disconnect
3992 // check if one opened input is not needed any more after disconnecting one device
3993 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3994 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003995 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003996 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3997 mInputs.keyAt(input_index));
3998 inputs.add(mInputs.keyAt(input_index));
3999 }
4000 }
4001 // Clear any profiles associated with the disconnected device.
4002 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
4003 if (mHwModules[module_index]->mHandle == 0) {
4004 continue;
4005 }
4006 for (size_t profile_index = 0;
4007 profile_index < mHwModules[module_index]->mInputProfiles.size();
4008 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004009 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01004010 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004011 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004012 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004013 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004014 }
4015 }
4016 }
4017 } // end disconnect
4018
4019 return NO_ERROR;
4020}
4021
4022
Eric Laurente0720872014-03-11 09:30:41 -07004023void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004024{
4025 ALOGV("closeOutput(%d)", output);
4026
Eric Laurentc75307b2015-03-17 15:29:32 -07004027 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004028 if (outputDesc == NULL) {
4029 ALOGW("closeOutput() unknown output %d", output);
4030 return;
4031 }
François Gaffie036e1e92015-03-19 10:16:24 +01004032 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004033
Eric Laurente552edb2014-03-10 17:42:56 -07004034 // look for duplicated outputs connected to the output being removed.
4035 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004036 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004037 if (dupOutputDesc->isDuplicated() &&
4038 (dupOutputDesc->mOutput1 == outputDesc ||
4039 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004040 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004041 if (dupOutputDesc->mOutput1 == outputDesc) {
4042 outputDesc2 = dupOutputDesc->mOutput2;
4043 } else {
4044 outputDesc2 = dupOutputDesc->mOutput1;
4045 }
4046 // As all active tracks on duplicated output will be deleted,
4047 // and as they were also referenced on the other output, the reference
4048 // count for their stream type must be adjusted accordingly on
4049 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004050 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004051 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004052 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004053 }
4054 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4055 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4056
4057 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004058 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004059 }
4060 }
4061
Eric Laurent05b90f82014-08-27 15:32:29 -07004062 nextAudioPortGeneration();
4063
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004064 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004065 if (index >= 0) {
4066 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4067 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4068 mAudioPatches.removeItemsAt(index);
4069 mpClientInterface->onAudioPatchListUpdate();
4070 }
4071
Eric Laurente552edb2014-03-10 17:42:56 -07004072 AudioParameter param;
4073 param.add(String8("closing"), String8("true"));
4074 mpClientInterface->setParameters(output, param.toString());
4075
4076 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004077 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004078 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004079}
4080
4081void AudioPolicyManager::closeInput(audio_io_handle_t input)
4082{
4083 ALOGV("closeInput(%d)", input);
4084
4085 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4086 if (inputDesc == NULL) {
4087 ALOGW("closeInput() unknown input %d", input);
4088 return;
4089 }
4090
Eric Laurent6a94d692014-05-20 11:18:06 -07004091 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004092
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004093 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004094 if (index >= 0) {
4095 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4096 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4097 mAudioPatches.removeItemsAt(index);
4098 mpClientInterface->onAudioPatchListUpdate();
4099 }
4100
4101 mpClientInterface->closeInput(input);
4102 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004103}
4104
Eric Laurentc75307b2015-03-17 15:29:32 -07004105SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4106 audio_devices_t device,
4107 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004108{
4109 SortedVector<audio_io_handle_t> outputs;
4110
4111 ALOGVV("getOutputsForDevice() device %04x", device);
4112 for (size_t i = 0; i < openOutputs.size(); i++) {
4113 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004114 i, openOutputs.valueAt(i)->isDuplicated(),
4115 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004116 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4117 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4118 outputs.add(openOutputs.keyAt(i));
4119 }
4120 }
4121 return outputs;
4122}
4123
Eric Laurente0720872014-03-11 09:30:41 -07004124bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004125 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004126{
4127 if (outputs1.size() != outputs2.size()) {
4128 return false;
4129 }
4130 for (size_t i = 0; i < outputs1.size(); i++) {
4131 if (outputs1[i] != outputs2[i]) {
4132 return false;
4133 }
4134 }
4135 return true;
4136}
4137
Eric Laurente0720872014-03-11 09:30:41 -07004138void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004139{
4140 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4141 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4142 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4143 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4144
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004145 // also take into account external policy-related changes: add all outputs which are
4146 // associated with policies in the "before" and "after" output vectors
4147 ALOGVV("checkOutputForStrategy(): policy related outputs");
4148 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004149 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004150 if (desc != 0 && desc->mPolicyMix != NULL) {
4151 srcOutputs.add(desc->mIoHandle);
4152 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4153 }
4154 }
4155 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004156 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004157 if (desc != 0 && desc->mPolicyMix != NULL) {
4158 dstOutputs.add(desc->mIoHandle);
4159 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4160 }
4161 }
4162
Eric Laurente552edb2014-03-10 17:42:56 -07004163 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4164 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4165 strategy, srcOutputs[0], dstOutputs[0]);
4166 // mute strategy while moving tracks from one output to another
4167 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004168 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004169 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004170 setStrategyMute(strategy, true, desc);
4171 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004172 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004173 sp<AudioSourceDescriptor> source =
4174 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4175 if (source != 0){
4176 connectAudioSource(source);
4177 }
Eric Laurente552edb2014-03-10 17:42:56 -07004178 }
4179
4180 // Move effects associated to this strategy from previous output to new output
4181 if (strategy == STRATEGY_MEDIA) {
4182 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4183 SortedVector<audio_io_handle_t> moved;
4184 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004185 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4186 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4187 effectDesc->mIo != fxOutput) {
4188 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004189 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4190 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004191 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004192 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004193 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004194 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004195 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004196 }
4197 }
4198 }
4199 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004200 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004201 if (getStrategy((audio_stream_type_t)i) == strategy) {
4202 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004203 }
4204 }
4205 }
4206}
4207
Eric Laurente0720872014-03-11 09:30:41 -07004208void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004209{
François Gaffie2110e042015-03-24 08:41:51 +01004210 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004211 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004212 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004213 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004214 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004215 checkOutputForStrategy(STRATEGY_SONIFICATION);
4216 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004217 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004218 checkOutputForStrategy(STRATEGY_MEDIA);
4219 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004220 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004221}
4222
Eric Laurente0720872014-03-11 09:30:41 -07004223void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004224{
François Gaffie53615e22015-03-19 09:24:12 +01004225 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004226 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004227 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004228 return;
4229 }
4230
Eric Laurent3a4311c2014-03-17 12:00:47 -07004231 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004232 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4233 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4234 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004235 // suspend A2DP output if:
4236 // (NOT already suspended) &&
4237 // ((SCO device is connected &&
4238 // (forced usage for communication || for record is SCO))) ||
4239 // (phone state is ringing || in call)
4240 //
4241 // restore A2DP output if:
4242 // (Already suspended) &&
4243 // ((SCO device is NOT connected ||
4244 // (forced usage NOT for communication && NOT for record is SCO))) &&
4245 // (phone state is NOT ringing && NOT in call)
4246 //
4247 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004248 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004249 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4250 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4251 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4252 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004253
4254 mpClientInterface->restoreOutput(a2dpOutput);
4255 mA2dpSuspended = false;
4256 }
4257 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004258 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004259 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4260 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4261 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4262 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004263
4264 mpClientInterface->suspendOutput(a2dpOutput);
4265 mA2dpSuspended = true;
4266 }
4267 }
4268}
4269
Eric Laurentc75307b2015-03-17 15:29:32 -07004270audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4271 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004272{
4273 audio_devices_t device = AUDIO_DEVICE_NONE;
4274
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004275 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004276 if (index >= 0) {
4277 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4278 if (patchDesc->mUid != mUidCached) {
4279 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004280 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004281 return outputDesc->device();
4282 }
4283 }
4284
Eric Laurente552edb2014-03-10 17:42:56 -07004285 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004286 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004287 // use device for strategy enforced audible
4288 // 2: we are in call or the strategy phone is active on the output:
4289 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004290 // 3: the strategy for enforced audible is active but not enforced on the output:
4291 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004292 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004293 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004294 // 5: the strategy accessibility is active on the output:
4295 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004296 // 6: the strategy "respectful" sonification is active on the output:
4297 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004298 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004299 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004300 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004301 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004302 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004303 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004304 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004305 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004306 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4307 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004308 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004309 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004310 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004311 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004312 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004313 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004314 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4315 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004316 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004317 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004318 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004319 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004320 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004321 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004322 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004323 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004324 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004325 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004326 }
4327
Eric Laurent1c333e22014-05-20 10:48:17 -07004328 ALOGV("getNewOutputDevice() selected device %x", device);
4329 return device;
4330}
4331
Eric Laurent232f26f2016-02-17 18:06:27 -08004332audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
Eric Laurent1c333e22014-05-20 10:48:17 -07004333{
Eric Laurent232f26f2016-02-17 18:06:27 -08004334 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004335
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004336 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004337 if (index >= 0) {
4338 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4339 if (patchDesc->mUid != mUidCached) {
4340 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004341 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004342 return inputDesc->mDevice;
4343 }
4344 }
4345
Eric Laurent232f26f2016-02-17 18:06:27 -08004346 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004347
Eric Laurente552edb2014-03-10 17:42:56 -07004348 return device;
4349}
4350
Eric Laurent794fde22016-03-11 09:50:45 -08004351bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4352 audio_stream_type_t stream2) {
4353 return ((stream1 == stream2) ||
4354 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4355 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004356}
4357
Eric Laurente0720872014-03-11 09:30:41 -07004358uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004359 return (uint32_t)getStrategy(stream);
4360}
4361
Eric Laurente0720872014-03-11 09:30:41 -07004362audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004363 // By checking the range of stream before calling getStrategy, we avoid
4364 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4365 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004366 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004367 return AUDIO_DEVICE_NONE;
4368 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004369 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004370 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4371 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004372 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 }
Eric Laurent794fde22016-03-11 09:50:45 -08004374 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004375 audio_devices_t curDevices =
4376 getDeviceForStrategy((routing_strategy)curStrategy, true /*fromCache*/);
4377 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4378 for (size_t i = 0; i < outputs.size(); i++) {
4379 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004380 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004381 curDevices |= outputDesc->device();
4382 }
4383 }
4384 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004385 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004386
4387 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4388 and doesn't really need to.*/
4389 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4390 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4391 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4392 }
Eric Laurente552edb2014-03-10 17:42:56 -07004393 return devices;
4394}
4395
François Gaffie2110e042015-03-24 08:41:51 +01004396routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4397{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004398 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004399 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004400}
4401
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004402uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4403 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004404 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4405 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4406 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004407 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4408 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4409 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004410 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004411 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004412}
4413
Eric Laurente0720872014-03-11 09:30:41 -07004414void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004415 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004416 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004417 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4418 updateDevicesAndOutputs();
4419 break;
4420 default:
4421 break;
4422 }
4423}
4424
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004425uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004426
4427 // skip beacon mute management if a dedicated TTS output is available
4428 if (mTtsOutputAvailable) {
4429 return 0;
4430 }
4431
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004432 switch(event) {
4433 case STARTING_OUTPUT:
4434 mBeaconMuteRefCount++;
4435 break;
4436 case STOPPING_OUTPUT:
4437 if (mBeaconMuteRefCount > 0) {
4438 mBeaconMuteRefCount--;
4439 }
4440 break;
4441 case STARTING_BEACON:
4442 mBeaconPlayingRefCount++;
4443 break;
4444 case STOPPING_BEACON:
4445 if (mBeaconPlayingRefCount > 0) {
4446 mBeaconPlayingRefCount--;
4447 }
4448 break;
4449 }
4450
4451 if (mBeaconMuteRefCount > 0) {
4452 // any playback causes beacon to be muted
4453 return setBeaconMute(true);
4454 } else {
4455 // no other playback: unmute when beacon starts playing, mute when it stops
4456 return setBeaconMute(mBeaconPlayingRefCount == 0);
4457 }
4458}
4459
4460uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4461 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4462 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4463 // keep track of muted state to avoid repeating mute/unmute operations
4464 if (mBeaconMuted != mute) {
4465 // mute/unmute AUDIO_STREAM_TTS on all outputs
4466 ALOGV("\t muting %d", mute);
4467 uint32_t maxLatency = 0;
4468 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004469 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004470 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004471 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004472 0 /*delay*/, AUDIO_DEVICE_NONE);
4473 const uint32_t latency = desc->latency() * 2;
4474 if (latency > maxLatency) {
4475 maxLatency = latency;
4476 }
4477 }
4478 mBeaconMuted = mute;
4479 return maxLatency;
4480 }
4481 return 0;
4482}
4483
Eric Laurente0720872014-03-11 09:30:41 -07004484audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004485 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004486{
Paul McLeanaa981192015-03-21 09:55:15 -07004487 // Routing
4488 // see if we have an explicit route
4489 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4490 // (getStrategy(stream)).
4491 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4492 // and activity count is non-zero
4493 // the device = the device from the descriptor in the RouteMap, and exit.
4494 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4495 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004496 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4497 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004498 return route->mDeviceDescriptor->type();
4499 }
4500 }
4501
Eric Laurente552edb2014-03-10 17:42:56 -07004502 if (fromCache) {
4503 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4504 strategy, mDeviceForStrategy[strategy]);
4505 return mDeviceForStrategy[strategy];
4506 }
François Gaffie2110e042015-03-24 08:41:51 +01004507 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004508}
4509
Eric Laurente0720872014-03-11 09:30:41 -07004510void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004511{
4512 for (int i = 0; i < NUM_STRATEGIES; i++) {
4513 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4514 }
4515 mPreviousOutputs = mOutputs;
4516}
4517
Eric Laurent1f2f2232014-06-02 12:01:23 -07004518uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004519 audio_devices_t prevDevice,
4520 uint32_t delayMs)
4521{
4522 // mute/unmute strategies using an incompatible device combination
4523 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4524 // if unmuting, unmute only after the specified delay
4525 if (outputDesc->isDuplicated()) {
4526 return 0;
4527 }
4528
4529 uint32_t muteWaitMs = 0;
4530 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004531 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004532
4533 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4534 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004535 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004536 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4537 bool doMute = false;
4538
4539 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4540 doMute = true;
4541 outputDesc->mStrategyMutedByDevice[i] = true;
4542 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4543 doMute = true;
4544 outputDesc->mStrategyMutedByDevice[i] = false;
4545 }
Eric Laurent99401132014-05-07 19:48:15 -07004546 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004547 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004548 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004549 // skip output if it does not share any device with current output
4550 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4551 == AUDIO_DEVICE_NONE) {
4552 continue;
4553 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004554 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4555 mute ? "muting" : "unmuting", i, curDevice);
4556 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004557 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004558 if (mute) {
4559 // FIXME: should not need to double latency if volume could be applied
4560 // immediately by the audioflinger mixer. We must account for the delay
4561 // between now and the next time the audioflinger thread for this output
4562 // will process a buffer (which corresponds to one buffer size,
4563 // usually 1/2 or 1/4 of the latency).
4564 if (muteWaitMs < desc->latency() * 2) {
4565 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004566 }
4567 }
4568 }
4569 }
4570 }
4571 }
4572
Eric Laurent99401132014-05-07 19:48:15 -07004573 // temporary mute output if device selection changes to avoid volume bursts due to
4574 // different per device volumes
4575 if (outputDesc->isActive() && (device != prevDevice)) {
4576 if (muteWaitMs < outputDesc->latency() * 2) {
4577 muteWaitMs = outputDesc->latency() * 2;
4578 }
4579 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004580 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004581 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004582 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004583 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004584 muteWaitMs *2, device);
4585 }
4586 }
4587 }
4588
Eric Laurente552edb2014-03-10 17:42:56 -07004589 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4590 if (muteWaitMs > delayMs) {
4591 muteWaitMs -= delayMs;
4592 usleep(muteWaitMs * 1000);
4593 return muteWaitMs;
4594 }
4595 return 0;
4596}
4597
Eric Laurentc75307b2015-03-17 15:29:32 -07004598uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004599 audio_devices_t device,
4600 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004602 audio_patch_handle_t *patchHandle,
4603 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004604{
Eric Laurentc75307b2015-03-17 15:29:32 -07004605 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004606 AudioParameter param;
4607 uint32_t muteWaitMs;
4608
4609 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004610 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4611 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004612 return muteWaitMs;
4613 }
4614 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4615 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004616 if ((device != AUDIO_DEVICE_NONE) &&
4617 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004618 return 0;
4619 }
4620
4621 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004622 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004623
4624 audio_devices_t prevDevice = outputDesc->mDevice;
4625
Paul McLeanaa981192015-03-21 09:55:15 -07004626 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004627
4628 if (device != AUDIO_DEVICE_NONE) {
4629 outputDesc->mDevice = device;
4630 }
4631 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4632
4633 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004634 // the requested device is AUDIO_DEVICE_NONE
4635 // OR the requested device is the same as current device
4636 // AND force is not specified
4637 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004638 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004639 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4640 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004641 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004642 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004643 return muteWaitMs;
4644 }
4645
4646 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004647
Eric Laurente552edb2014-03-10 17:42:56 -07004648 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004649 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004650 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004651 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004652 DeviceVector deviceList;
4653 if ((address == NULL) || (strlen(address) == 0)) {
4654 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4655 } else {
4656 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4657 }
4658
Eric Laurent1c333e22014-05-20 10:48:17 -07004659 if (!deviceList.isEmpty()) {
4660 struct audio_patch patch;
4661 outputDesc->toAudioPortConfig(&patch.sources[0]);
4662 patch.num_sources = 1;
4663 patch.num_sinks = 0;
4664 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4665 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004666 patch.num_sinks++;
4667 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 ssize_t index;
4669 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4670 index = mAudioPatches.indexOfKey(*patchHandle);
4671 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004672 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 }
4674 sp< AudioPatch> patchDesc;
4675 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4676 if (index >= 0) {
4677 patchDesc = mAudioPatches.valueAt(index);
4678 afPatchHandle = patchDesc->mAfPatchHandle;
4679 }
4680
Eric Laurent1c333e22014-05-20 10:48:17 -07004681 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004682 &afPatchHandle,
4683 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004684 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4685 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004687 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004689 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 addAudioPatch(patchDesc->mHandle, patchDesc);
4691 } else {
4692 patchDesc->mPatch = patch;
4693 }
4694 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 if (patchHandle) {
4696 *patchHandle = patchDesc->mHandle;
4697 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004698 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004699 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004700 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004701 }
4702 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004703
4704 // inform all input as well
4705 for (size_t i = 0; i < mInputs.size(); i++) {
4706 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004707 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004708 AudioParameter inputCmd = AudioParameter();
4709 ALOGV("%s: inform input %d of device:%d", __func__,
4710 inputDescriptor->mIoHandle, device);
4711 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4712 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4713 inputCmd.toString(),
4714 delayMs);
4715 }
4716 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004717 }
Eric Laurente552edb2014-03-10 17:42:56 -07004718
4719 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004720 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004721
4722 return muteWaitMs;
4723}
4724
Eric Laurentc75307b2015-03-17 15:29:32 -07004725status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 int delayMs,
4727 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004728{
Eric Laurent6a94d692014-05-20 11:18:06 -07004729 ssize_t index;
4730 if (patchHandle) {
4731 index = mAudioPatches.indexOfKey(*patchHandle);
4732 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004733 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 }
4735 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004736 return INVALID_OPERATION;
4737 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4739 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004740 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004741 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 removeAudioPatch(patchDesc->mHandle);
4743 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004744 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004745 return status;
4746}
4747
4748status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4749 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004750 bool force,
4751 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004752{
4753 status_t status = NO_ERROR;
4754
Eric Laurent1f2f2232014-06-02 12:01:23 -07004755 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004756 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4757 inputDesc->mDevice = device;
4758
4759 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4760 if (!deviceList.isEmpty()) {
4761 struct audio_patch patch;
4762 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004763 // AUDIO_SOURCE_HOTWORD is for internal use only:
4764 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004765 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004766 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004767 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4768 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004769 patch.num_sinks = 1;
4770 //only one input device for now
4771 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004772 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004773 ssize_t index;
4774 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4775 index = mAudioPatches.indexOfKey(*patchHandle);
4776 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004777 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 }
4779 sp< AudioPatch> patchDesc;
4780 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4781 if (index >= 0) {
4782 patchDesc = mAudioPatches.valueAt(index);
4783 afPatchHandle = patchDesc->mAfPatchHandle;
4784 }
4785
Eric Laurent1c333e22014-05-20 10:48:17 -07004786 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004788 0);
4789 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004791 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004793 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 addAudioPatch(patchDesc->mHandle, patchDesc);
4795 } else {
4796 patchDesc->mPatch = patch;
4797 }
4798 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 if (patchHandle) {
4800 *patchHandle = patchDesc->mHandle;
4801 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004802 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004804 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004805 }
4806 }
4807 }
4808 return status;
4809}
4810
Eric Laurent6a94d692014-05-20 11:18:06 -07004811status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4812 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004813{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004814 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 ssize_t index;
4816 if (patchHandle) {
4817 index = mAudioPatches.indexOfKey(*patchHandle);
4818 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004819 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 }
4821 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004822 return INVALID_OPERATION;
4823 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004824 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4825 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004826 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004827 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004828 removeAudioPatch(patchDesc->mHandle);
4829 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004830 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004831 return status;
4832}
4833
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004834sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004835 String8 address,
4836 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004837 audio_format_t& format,
4838 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004839 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004840{
4841 // Choose an input profile based on the requested capture parameters: select the first available
4842 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004843 //
4844 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4845 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004846
4847 for (size_t i = 0; i < mHwModules.size(); i++)
4848 {
4849 if (mHwModules[i]->mHandle == 0) {
4850 continue;
4851 }
4852 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4853 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004854 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004855 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004856 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004857 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004858 format,
4859 &format /*updatedFormat*/,
4860 channelMask,
4861 &channelMask /*updatedChannelMask*/,
4862 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004863
Eric Laurente552edb2014-03-10 17:42:56 -07004864 return profile;
4865 }
4866 }
4867 }
4868 return NULL;
4869}
4870
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004871
4872audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004873 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004874{
François Gaffie036e1e92015-03-19 10:16:24 +01004875 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4876 audio_devices_t selectedDeviceFromMix =
4877 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004878
François Gaffie036e1e92015-03-19 10:16:24 +01004879 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4880 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004881 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004882 return getDeviceForInputSource(inputSource);
4883}
4884
4885audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4886{
Paul McLean466dc8e2015-04-17 13:15:36 -06004887 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4888 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004889 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004890 return route->mDeviceDescriptor->type();
4891 }
4892 }
4893
4894 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004895}
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004898 int index,
4899 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004900{
François Gaffied1ab2bd2015-12-02 18:20:06 +01004901 float volumeDb = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07004902 // if a headset is connected, apply the following rules to ring tones and notifications
4903 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07004904 // - always attenuate notifications volume by 6dB
4905 // - attenuate ring tones volume by 6dB unless music is not playing and
4906 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07004907 // - if music is playing, always limit the volume to current music volume,
4908 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004909 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004910 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4911 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4912 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4913 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4914 ((stream_strategy == STRATEGY_SONIFICATION)
4915 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004916 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004917 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004918 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01004919 mVolumeCurves->canBeMuted(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004920 // when the phone is ringing we must consider that music could have been paused just before
4921 // by the music application and behave as if music was active if the last music track was
4922 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004923 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004924 mLimitRingtoneVolume) {
Eric Laurent6af1c1d2016-04-14 11:20:44 -07004925 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004926 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004927 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004928 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
4929 musicDevice),
4930 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004931 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4932 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4933 if (volumeDb > minVolDB) {
4934 volumeDb = minVolDB;
4935 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004936 }
Eric Laurent6af1c1d2016-04-14 11:20:44 -07004937 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
4938 stream_strategy != STRATEGY_SONIFICATION) {
4939 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004940 }
4941 }
4942
Eric Laurentffbc80f2015-03-18 18:30:19 -07004943 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004944}
4945
Eric Laurente0720872014-03-11 09:30:41 -07004946status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004947 int index,
4948 const sp<AudioOutputDescriptor>& outputDesc,
4949 audio_devices_t device,
4950 int delayMs,
4951 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004952{
Eric Laurente552edb2014-03-10 17:42:56 -07004953 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004954 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004955 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004956 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004957 return NO_ERROR;
4958 }
François Gaffie2110e042015-03-24 08:41:51 +01004959 audio_policy_forced_cfg_t forceUseForComm =
4960 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004961 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004962 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4963 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004964 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004965 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004966 return INVALID_OPERATION;
4967 }
4968
Eric Laurentc75307b2015-03-17 15:29:32 -07004969 if (device == AUDIO_DEVICE_NONE) {
4970 device = outputDesc->device();
4971 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004972
Eric Laurentffbc80f2015-03-18 18:30:19 -07004973 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004974 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004975 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004976 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004977
Eric Laurentffbc80f2015-03-18 18:30:19 -07004978 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004979
Eric Laurent3b73df72014-03-11 09:06:29 -07004980 if (stream == AUDIO_STREAM_VOICE_CALL ||
4981 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004982 float voiceVolume;
4983 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004984 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004985 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004986 } else {
4987 voiceVolume = 1.0;
4988 }
4989
Eric Laurent18fba842016-03-31 14:41:26 -07004990 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07004991 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4992 mLastVoiceVolume = voiceVolume;
4993 }
4994 }
4995
4996 return NO_ERROR;
4997}
4998
Eric Laurentc75307b2015-03-17 15:29:32 -07004999void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5000 audio_devices_t device,
5001 int delayMs,
5002 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07005003{
Eric Laurentc75307b2015-03-17 15:29:32 -07005004 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07005005
Eric Laurent794fde22016-03-11 09:50:45 -08005006 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005007 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005008 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005009 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005010 device,
5011 delayMs,
5012 force);
5013 }
5014}
5015
Eric Laurente0720872014-03-11 09:30:41 -07005016void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005017 bool on,
5018 const sp<AudioOutputDescriptor>& outputDesc,
5019 int delayMs,
5020 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005021{
Eric Laurent72249d52015-06-08 11:12:15 -07005022 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5023 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005024 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005025 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005026 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005027 }
5028 }
5029}
5030
Eric Laurente0720872014-03-11 09:30:41 -07005031void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005032 bool on,
5033 const sp<AudioOutputDescriptor>& outputDesc,
5034 int delayMs,
5035 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005036{
Eric Laurente552edb2014-03-10 17:42:56 -07005037 if (device == AUDIO_DEVICE_NONE) {
5038 device = outputDesc->device();
5039 }
5040
Eric Laurentc75307b2015-03-17 15:29:32 -07005041 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5042 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005043
5044 if (on) {
5045 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005046 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005047 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005048 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005049 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005050 }
5051 }
5052 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5053 outputDesc->mMuteCount[stream]++;
5054 } else {
5055 if (outputDesc->mMuteCount[stream] == 0) {
5056 ALOGV("setStreamMute() unmuting non muted stream!");
5057 return;
5058 }
5059 if (--outputDesc->mMuteCount[stream] == 0) {
5060 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005061 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005062 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005063 device,
5064 delayMs);
5065 }
5066 }
5067}
5068
Eric Laurente0720872014-03-11 09:30:41 -07005069void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005070 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005071{
Eric Laurent87ffa392015-05-22 10:32:38 -07005072 if(!hasPrimaryOutput()) {
5073 return;
5074 }
5075
Eric Laurente552edb2014-03-10 17:42:56 -07005076 // if the stream pertains to sonification strategy and we are in call we must
5077 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5078 // in the device used for phone strategy and play the tone if the selected device does not
5079 // interfere with the device used for phone strategy
5080 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5081 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005082 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005083 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5084 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005085 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005086 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5087 stream, starting, outputDesc->mDevice, stateChange);
5088 if (outputDesc->mRefCount[stream]) {
5089 int muteCount = 1;
5090 if (stateChange) {
5091 muteCount = outputDesc->mRefCount[stream];
5092 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005093 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005094 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5095 for (int i = 0; i < muteCount; i++) {
5096 setStreamMute(stream, starting, mPrimaryOutput);
5097 }
5098 } else {
5099 ALOGV("handleIncallSonification() high visibility");
5100 if (outputDesc->device() &
5101 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5102 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5103 for (int i = 0; i < muteCount; i++) {
5104 setStreamMute(stream, starting, mPrimaryOutput);
5105 }
5106 }
5107 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005108 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5109 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005110 } else {
5111 mpClientInterface->stopTone();
5112 }
5113 }
5114 }
5115 }
5116}
5117
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005118audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5119{
5120 // flags to stream type mapping
5121 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5122 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5123 }
5124 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5125 return AUDIO_STREAM_BLUETOOTH_SCO;
5126 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005127 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5128 return AUDIO_STREAM_TTS;
5129 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005130
5131 // usage to stream type mapping
5132 switch (attr->usage) {
5133 case AUDIO_USAGE_MEDIA:
5134 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005135 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5136 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005137 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5138 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005139 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5140 return AUDIO_STREAM_SYSTEM;
5141 case AUDIO_USAGE_VOICE_COMMUNICATION:
5142 return AUDIO_STREAM_VOICE_CALL;
5143
5144 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5145 return AUDIO_STREAM_DTMF;
5146
5147 case AUDIO_USAGE_ALARM:
5148 return AUDIO_STREAM_ALARM;
5149 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5150 return AUDIO_STREAM_RING;
5151
5152 case AUDIO_USAGE_NOTIFICATION:
5153 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5154 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5155 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5156 case AUDIO_USAGE_NOTIFICATION_EVENT:
5157 return AUDIO_STREAM_NOTIFICATION;
5158
5159 case AUDIO_USAGE_UNKNOWN:
5160 default:
5161 return AUDIO_STREAM_MUSIC;
5162 }
5163}
Eric Laurente83b55d2014-11-14 10:06:21 -08005164
François Gaffie53615e22015-03-19 09:24:12 +01005165bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5166{
Eric Laurente83b55d2014-11-14 10:06:21 -08005167 // has flags that map to a strategy?
5168 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5169 return true;
5170 }
5171
5172 // has known usage?
5173 switch (paa->usage) {
5174 case AUDIO_USAGE_UNKNOWN:
5175 case AUDIO_USAGE_MEDIA:
5176 case AUDIO_USAGE_VOICE_COMMUNICATION:
5177 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5178 case AUDIO_USAGE_ALARM:
5179 case AUDIO_USAGE_NOTIFICATION:
5180 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5181 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5182 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5183 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5184 case AUDIO_USAGE_NOTIFICATION_EVENT:
5185 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5186 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5187 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5188 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005189 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005190 break;
5191 default:
5192 return false;
5193 }
5194 return true;
5195}
5196
François Gaffiead3183e2015-03-18 16:55:35 +01005197bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5198 routing_strategy strategy, uint32_t inPastMs,
5199 nsecs_t sysTime) const
5200{
5201 if ((sysTime == 0) && (inPastMs != 0)) {
5202 sysTime = systemTime();
5203 }
Eric Laurent794fde22016-03-11 09:50:45 -08005204 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005205 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5206 (NUM_STRATEGIES == strategy)) &&
5207 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5208 return true;
5209 }
5210 }
5211 return false;
5212}
5213
François Gaffie2110e042015-03-24 08:41:51 +01005214audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5215{
5216 return mEngine->getForceUse(usage);
5217}
5218
5219bool AudioPolicyManager::isInCall()
5220{
5221 return isStateInCall(mEngine->getPhoneState());
5222}
5223
5224bool AudioPolicyManager::isStateInCall(int state)
5225{
5226 return is_state_in_call(state);
5227}
5228
Eric Laurentd60560a2015-04-10 11:31:20 -07005229void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5230{
5231 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5232 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5233 if (sourceDesc->mDevice->equals(deviceDesc)) {
5234 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5235 stopAudioSource(sourceDesc->getHandle());
5236 }
5237 }
5238
5239 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5240 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5241 bool release = false;
5242 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5243 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5244 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5245 source->ext.device.type == deviceDesc->type()) {
5246 release = true;
5247 }
5248 }
5249 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5250 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5251 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5252 sink->ext.device.type == deviceDesc->type()) {
5253 release = true;
5254 }
5255 }
5256 if (release) {
5257 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5258 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5259 }
5260 }
5261}
5262
Phil Burk09bc4612016-02-24 15:58:15 -08005263// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005264void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5265 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005266 // TODO Set this based on Config properties.
5267 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005268
5269 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5270 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005271 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005272
5273 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005274 bool supportsAC3 = false;
5275 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005276 bool supportsIEC61937 = false;
5277 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5278 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005279 switch (format) {
5280 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005281 supportsAC3 = true;
5282 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005283 case AUDIO_FORMAT_E_AC3:
5284 case AUDIO_FORMAT_DTS:
5285 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005286 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005287 break;
5288 case AUDIO_FORMAT_IEC61937:
5289 supportsIEC61937 = true;
5290 break;
5291 default:
5292 break;
5293 }
5294 }
Phil Burk09bc4612016-02-24 15:58:15 -08005295
5296 // Modify formats based on surround preferences.
5297 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005298 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5299 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5300 // Remove surround sound related formats.
5301 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5302 audio_format_t format = formats[formatIndex];
5303 switch(format) {
5304 case AUDIO_FORMAT_AC3:
5305 case AUDIO_FORMAT_E_AC3:
5306 case AUDIO_FORMAT_DTS:
5307 case AUDIO_FORMAT_DTS_HD:
5308 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005309 formats.removeAt(formatIndex);
5310 break;
5311 default:
5312 formatIndex++; // keep it
5313 break;
5314 }
Phil Burk09bc4612016-02-24 15:58:15 -08005315 }
Phil Burk07ac1142016-03-25 13:39:29 -07005316 supportsAC3 = false;
5317 supportsOtherSurround = false;
5318 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005319 }
Phil Burk07ac1142016-03-25 13:39:29 -07005320 } else { // AUTO or ALWAYS
5321 // Most TVs support AC3 even if they do not report it in the EDID.
5322 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5323 && !supportsAC3) {
5324 formats.add(AUDIO_FORMAT_AC3);
5325 supportsAC3 = true;
5326 }
5327
5328 // If ALWAYS, add support for raw surround formats if all are missing.
5329 // This assumes that if any of these formats are reported by the HAL
5330 // then the report is valid and should not be modified.
5331 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5332 && !supportsOtherSurround) {
5333 formats.add(AUDIO_FORMAT_E_AC3);
5334 formats.add(AUDIO_FORMAT_DTS);
5335 formats.add(AUDIO_FORMAT_DTS_HD);
5336 supportsOtherSurround = true;
5337 }
5338
5339 // Add support for IEC61937 if any raw surround supported.
5340 // The HAL could do this but add it here, just in case.
5341 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5342 formats.add(AUDIO_FORMAT_IEC61937);
5343 supportsIEC61937 = true;
5344 }
Phil Burk09bc4612016-02-24 15:58:15 -08005345 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005346}
5347
5348// Modify the list of channel masks supported.
5349void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5350 ChannelsVector &channelMasks = *channelMasksPtr;
5351 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5352 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5353
5354 // If NEVER, then remove support for channelMasks > stereo.
5355 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5356 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5357 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5358 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5359 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5360 channelMasks.removeAt(maskIndex);
5361 } else {
5362 maskIndex++;
5363 }
5364 }
5365 // If ALWAYS, then make sure we at least support 5.1
5366 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5367 bool supports5dot1 = false;
5368 // Are there any channel masks that can be considered "surround"?
5369 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5370 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5371 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5372 supports5dot1 = true;
5373 break;
5374 }
5375 }
5376 // If not then add 5.1 support.
5377 if (!supports5dot1) {
5378 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5379 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5380 }
Phil Burk09bc4612016-02-24 15:58:15 -08005381 }
5382}
5383
Phil Burk00eeb322016-03-31 12:41:00 -07005384void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5385 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005386 AudioProfileVector &profiles)
5387{
5388 String8 reply;
5389 char *value;
Phil Burk0709b0a2016-03-31 12:54:57 -07005390
François Gaffie112b0af2015-11-19 16:13:25 +01005391 // Format MUST be checked first to update the list of AudioProfile
5392 if (profiles.hasDynamicFormat()) {
5393 reply = mpClientInterface->getParameters(ioHandle,
5394 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk0709b0a2016-03-31 12:54:57 -07005395 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005396 AudioParameter repliedParameters(reply);
5397 if (repliedParameters.get(
5398 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005399 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5400 return;
5401 }
Phil Burk09bc4612016-02-24 15:58:15 -08005402 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005403 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005404 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005405 }
Phil Burk09bc4612016-02-24 15:58:15 -08005406 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005407 }
5408 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5409
Eric Laurent20eb3a42016-01-26 18:39:17 -08005410 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005411 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005412 ChannelsVector channelMasks;
5413 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005414 AudioParameter requestedParameters;
5415 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5416
5417 if (profiles.hasDynamicRateFor(format)) {
5418 reply = mpClientInterface->getParameters(ioHandle,
5419 requestedParameters.toString() + ";" +
5420 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5421 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005422 AudioParameter repliedParameters(reply);
5423 if (repliedParameters.get(
5424 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5425 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005426 }
5427 }
5428 if (profiles.hasDynamicChannelsFor(format)) {
5429 reply = mpClientInterface->getParameters(ioHandle,
5430 requestedParameters.toString() + ";" +
5431 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5432 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005433 AudioParameter repliedParameters(reply);
5434 if (repliedParameters.get(
5435 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5436 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005437 if (device == AUDIO_DEVICE_OUT_HDMI) {
5438 filterSurroundChannelMasks(&channelMasks);
5439 }
François Gaffie112b0af2015-11-19 16:13:25 +01005440 }
5441 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005442 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005443 }
5444}
Eric Laurentd60560a2015-04-10 11:31:20 -07005445
Eric Laurente552edb2014-03-10 17:42:56 -07005446}; // namespace android