blob: 29ab262d42856ed5ba868e6bdefdb7957dc1c6c2 [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{
François Gaffie53615e22015-03-19 09:24:12 +0100294 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, "");
295
Eric Laurent3a4311c2014-03-17 12:00:47 -0700296 DeviceVector *deviceVector;
297
Eric Laurente552edb2014-03-10 17:42:56 -0700298 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700300 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700301 deviceVector = &mAvailableInputDevices;
302 } else {
303 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
304 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
François Gaffie53615e22015-03-19 09:24:12 +0100306 return deviceVector->getDeviceConnectionState(devDesc);
Eric Laurenta1d525f2015-01-29 13:36:45 -0800307}
308
Eric Laurentc2730ba2014-07-20 15:47:07 -0700309void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
310{
311 bool createTxPatch = false;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700312 status_t status;
313 audio_patch_handle_t afPatchHandle;
314 DeviceVector deviceList;
315
Eric Laurent87ffa392015-05-22 10:32:38 -0700316 if(!hasPrimaryOutput()) {
317 return;
318 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800319 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700320 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
321
322 // release existing RX patch if any
323 if (mCallRxPatch != 0) {
324 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
325 mCallRxPatch.clear();
326 }
327 // release TX patch if any
328 if (mCallTxPatch != 0) {
329 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
330 mCallTxPatch.clear();
331 }
332
333 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
334 // via setOutputDevice() on primary output.
335 // Otherwise, create two audio patches for TX and RX path.
336 if (availablePrimaryOutputDevices() & rxDevice) {
337 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
338 // If the TX device is also on the primary HW module, setOutputDevice() will take care
339 // of it due to legacy implementation. If not, create a patch.
340 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
341 == AUDIO_DEVICE_NONE) {
342 createTxPatch = true;
343 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700344 } else { // create RX path audio patch
345 struct audio_patch patch;
346
347 patch.num_sources = 1;
348 patch.num_sinks = 1;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
350 ALOG_ASSERT(!deviceList.isEmpty(),
351 "updateCallRouting() selected device not in output device list");
352 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
353 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
354 ALOG_ASSERT(!deviceList.isEmpty(),
355 "updateCallRouting() no telephony RX device");
356 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
357
358 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
359 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
360
361 // request to reuse existing output stream if one is already opened to reach the RX device
362 SortedVector<audio_io_handle_t> outputs =
363 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700364 audio_io_handle_t output = selectOutput(outputs,
365 AUDIO_OUTPUT_FLAG_NONE,
366 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700367 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700369 ALOG_ASSERT(!outputDesc->isDuplicated(),
370 "updateCallRouting() RX device output is duplicated");
371 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700372 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700373 patch.num_sources = 2;
374 }
375
376 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
377 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
378 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
379 status);
380 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100381 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700382 mCallRxPatch->mAfPatchHandle = afPatchHandle;
383 mCallRxPatch->mUid = mUidCached;
384 }
385 createTxPatch = true;
386 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700387 if (createTxPatch) { // create TX path audio patch
Eric Laurentc2730ba2014-07-20 15:47:07 -0700388 struct audio_patch patch;
Eric Laurent8ae73122016-04-12 10:13:29 -0700389
Eric Laurentc2730ba2014-07-20 15:47:07 -0700390 patch.num_sources = 1;
391 patch.num_sinks = 1;
392 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
393 ALOG_ASSERT(!deviceList.isEmpty(),
394 "updateCallRouting() selected device not in input device list");
395 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
396 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
397 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
398 ALOG_ASSERT(!deviceList.isEmpty(),
399 "updateCallRouting() no telephony TX device");
400 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
401 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
402
403 SortedVector<audio_io_handle_t> outputs =
404 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700405 audio_io_handle_t output = selectOutput(outputs,
406 AUDIO_OUTPUT_FLAG_NONE,
407 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700408 // request to reuse existing output stream if one is already opened to reach the TX
409 // path output device
410 if (output != AUDIO_IO_HANDLE_NONE) {
411 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
412 ALOG_ASSERT(!outputDesc->isDuplicated(),
413 "updateCallRouting() RX device output is duplicated");
414 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700415 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700416 patch.num_sources = 2;
417 }
418
Eric Laurentc0a889f2015-10-14 14:36:34 -0700419 // terminate active capture if on the same HW module as the call TX source device
420 // FIXME: would be better to refine to only inputs whose profile connects to the
421 // call TX device but this information is not in the audio patch and logic here must be
422 // symmetric to the one in startInput()
Eric Laurent232f26f2016-02-17 18:06:27 -0800423 audio_io_handle_t activeInput = mInputs.getActiveInput();
424 if (activeInput != 0) {
425 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
426 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
427 //FIXME: consider all active sessions
428 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
429 audio_session_t activeSession = activeSessions.keyAt(0);
430 stopInput(activeInput, activeSession);
431 releaseInput(activeInput, activeSession);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700432 }
433 }
434
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
436 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
437 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
438 status);
439 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100440 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700441 mCallTxPatch->mAfPatchHandle = afPatchHandle;
442 mCallTxPatch->mUid = mUidCached;
443 }
444 }
445}
446
Eric Laurente0720872014-03-11 09:30:41 -0700447void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700448{
449 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100450 // store previous phone state for management of sonification strategy below
451 int oldState = mEngine->getPhoneState();
452
453 if (mEngine->setPhoneState(state) != NO_ERROR) {
454 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return;
456 }
François Gaffie2110e042015-03-24 08:41:51 +0100457 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700458 // if leaving call state, handle special case of active streams
459 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700460 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700461 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800462 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700463 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700464 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800465
Eric Laurent63dea1d2015-07-02 17:10:28 -0700466 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800467 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700468 }
469
François Gaffie2110e042015-03-24 08:41:51 +0100470 /**
471 * Switching to or from incall state or switching between telephony and VoIP lead to force
472 * routing command.
473 */
474 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
475 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700476
477 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700478 checkA2dpSuspend();
479 checkOutputForAllStrategies();
480 updateDevicesAndOutputs();
481
Eric Laurente552edb2014-03-10 17:42:56 -0700482 int delayMs = 0;
483 if (isStateInCall(state)) {
484 nsecs_t sysTime = systemTime();
485 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700486 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700487 // mute media and sonification strategies and delay device switch by the largest
488 // latency of any output where either strategy is active.
489 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100490 if ((isStrategyActive(desc, STRATEGY_MEDIA,
491 SONIFICATION_HEADSET_MUSIC_DELAY,
492 sysTime) ||
493 isStrategyActive(desc, STRATEGY_SONIFICATION,
494 SONIFICATION_HEADSET_MUSIC_DELAY,
495 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700496 (delayMs < (int)desc->latency()*2)) {
497 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700498 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700499 setStrategyMute(STRATEGY_MEDIA, true, desc);
500 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700501 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700502 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
503 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700504 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
505 }
506 }
507
Eric Laurent87ffa392015-05-22 10:32:38 -0700508 if (hasPrimaryOutput()) {
509 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
510 // the device returned is not necessarily reachable via this output
511 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
512 // force routing command to audio hardware when ending call
513 // even if no device change is needed
514 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
515 rxDevice = mPrimaryOutput->device();
516 }
Eric Laurente552edb2014-03-10 17:42:56 -0700517
Eric Laurent87ffa392015-05-22 10:32:38 -0700518 if (state == AUDIO_MODE_IN_CALL) {
519 updateCallRouting(rxDevice, delayMs);
520 } else if (oldState == AUDIO_MODE_IN_CALL) {
521 if (mCallRxPatch != 0) {
522 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
523 mCallRxPatch.clear();
524 }
525 if (mCallTxPatch != 0) {
526 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
527 mCallTxPatch.clear();
528 }
529 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
530 } else {
531 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700532 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700533 }
Eric Laurente552edb2014-03-10 17:42:56 -0700534 // if entering in call state, handle special case of active streams
535 // pertaining to sonification strategy see handleIncallSonification()
536 if (isStateInCall(state)) {
537 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent794fde22016-03-11 09:50:45 -0800538 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700540 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700541
542 // force reevaluating accessibility routing when call starts
543 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700544 }
545
546 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700547 if (state == AUDIO_MODE_RINGTONE &&
548 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700549 mLimitRingtoneVolume = true;
550 } else {
551 mLimitRingtoneVolume = false;
552 }
553}
554
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700555audio_mode_t AudioPolicyManager::getPhoneState() {
556 return mEngine->getPhoneState();
557}
558
Eric Laurente0720872014-03-11 09:30:41 -0700559void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700560 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700561{
François Gaffie2110e042015-03-24 08:41:51 +0100562 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700563
François Gaffie2110e042015-03-24 08:41:51 +0100564 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
565 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
566 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700567 }
François Gaffie2110e042015-03-24 08:41:51 +0100568 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
569 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
570 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700571
572 // check for device and output changes triggered by new force usage
573 checkA2dpSuspend();
574 checkOutputForAllStrategies();
575 updateDevicesAndOutputs();
Phil Burk09bc4612016-02-24 15:58:15 -0800576
Eric Laurent87ffa392015-05-22 10:32:38 -0700577 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700578 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
579 updateCallRouting(newDevice);
580 }
Eric Laurente552edb2014-03-10 17:42:56 -0700581 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700582 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
583 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
584 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
585 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700586 }
Eric Laurente552edb2014-03-10 17:42:56 -0700587 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700588 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700589 }
590 }
591
Eric Laurent232f26f2016-02-17 18:06:27 -0800592 audio_io_handle_t activeInput = mInputs.getActiveInput();
593 if (activeInput != 0) {
594 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
595 audio_devices_t newDevice = getNewInputDevice(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700596 // Force new input selection if the new device can not be reached via current input
Eric Laurent232f26f2016-02-17 18:06:27 -0800597 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
598 setInputDevice(activeInput, newDevice);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700599 } else {
Eric Laurent232f26f2016-02-17 18:06:27 -0800600 closeInput(activeInput);
Eric Laurentc171c7c2015-09-25 12:21:06 -0700601 }
Eric Laurente552edb2014-03-10 17:42:56 -0700602 }
Eric Laurente552edb2014-03-10 17:42:56 -0700603}
604
Eric Laurente0720872014-03-11 09:30:41 -0700605void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700606{
607 ALOGV("setSystemProperty() property %s, value %s", property, value);
608}
609
610// Find a direct output profile compatible with the parameters passed, even if the input flags do
611// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800612sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700613 audio_devices_t device,
614 uint32_t samplingRate,
615 audio_format_t format,
616 audio_channel_mask_t channelMask,
617 audio_output_flags_t flags)
618{
Eric Laurent861a6282015-05-18 15:40:16 -0700619 // only retain flags that will drive the direct output profile selection
620 // if explicitly requested
621 static const uint32_t kRelevantFlags =
622 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
623 flags =
624 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
625
626 sp<IOProfile> profile;
627
Eric Laurente552edb2014-03-10 17:42:56 -0700628 for (size_t i = 0; i < mHwModules.size(); i++) {
629 if (mHwModules[i]->mHandle == 0) {
630 continue;
631 }
632 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700633 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
634 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700635 samplingRate, NULL /*updatedSamplingRate*/,
636 format, NULL /*updatedFormat*/,
637 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700638 flags)) {
639 continue;
640 }
641 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100642 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700643 continue;
644 }
645 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100646 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700647 continue;
648 }
649 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100650 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700651 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700652 }
Eric Laurente552edb2014-03-10 17:42:56 -0700653 }
654 }
Eric Laurent861a6282015-05-18 15:40:16 -0700655 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700656}
657
Eric Laurente0720872014-03-11 09:30:41 -0700658audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100659 uint32_t samplingRate,
660 audio_format_t format,
661 audio_channel_mask_t channelMask,
662 audio_output_flags_t flags,
663 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700664{
Eric Laurent3b73df72014-03-11 09:06:29 -0700665 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700666 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
667 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
668 device, stream, samplingRate, format, channelMask, flags);
669
Eric Laurente83b55d2014-11-14 10:06:21 -0800670 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
671 stream, samplingRate,format, channelMask,
672 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700673}
674
Eric Laurente83b55d2014-11-14 10:06:21 -0800675status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
676 audio_io_handle_t *output,
677 audio_session_t session,
678 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700679 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800680 uint32_t samplingRate,
681 audio_format_t format,
682 audio_channel_mask_t channelMask,
683 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700684 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800685 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700686{
Eric Laurente83b55d2014-11-14 10:06:21 -0800687 audio_attributes_t attributes;
688 if (attr != NULL) {
689 if (!isValidAttributes(attr)) {
690 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
691 attr->usage, attr->content_type, attr->flags,
692 attr->tags);
693 return BAD_VALUE;
694 }
695 attributes = *attr;
696 } else {
697 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
698 ALOGE("getOutputForAttr(): invalid stream type");
699 return BAD_VALUE;
700 }
701 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700702 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700703 sp<SwAudioOutputDescriptor> desc;
Jean-Michel Trivie8deced2016-02-11 12:50:39 -0800704 if (mPolicyMixes.getOutputForAttr(attributes, uid, desc) == NO_ERROR) {
François Gaffie036e1e92015-03-19 10:16:24 +0100705 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
Phil Burkfdb3c072016-02-09 10:47:02 -0800706 if (!audio_has_proportional_frames(format)) {
François Gaffie036e1e92015-03-19 10:16:24 +0100707 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800708 }
François Gaffie036e1e92015-03-19 10:16:24 +0100709 *stream = streamTypefromAttributesInt(&attributes);
710 *output = desc->mIoHandle;
711 ALOGV("getOutputForAttr() returns output %d", *output);
712 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800713 }
714 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
715 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
716 return BAD_VALUE;
717 }
718
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700719 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
720 " session %d selectedDeviceId %d",
721 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
722 session, selectedDeviceId);
723
724 *stream = streamTypefromAttributesInt(&attributes);
725
726 // Explicit routing?
727 sp<DeviceDescriptor> deviceDesc;
728 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
729 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
730 deviceDesc = mAvailableOutputDevices[i];
731 break;
732 }
733 }
734 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700735
Eric Laurente83b55d2014-11-14 10:06:21 -0800736 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700737 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700738
Eric Laurente83b55d2014-11-14 10:06:21 -0800739 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700740 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
741 }
742
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700743 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700744 device, samplingRate, format, channelMask, flags);
745
Eric Laurente83b55d2014-11-14 10:06:21 -0800746 *output = getOutputForDevice(device, session, *stream,
747 samplingRate, format, channelMask,
748 flags, offloadInfo);
749 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700750 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800751 return INVALID_OPERATION;
752 }
Paul McLeanaa981192015-03-21 09:55:15 -0700753
Eric Laurente83b55d2014-11-14 10:06:21 -0800754 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700755}
756
757audio_io_handle_t AudioPolicyManager::getOutputForDevice(
758 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800759 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700760 audio_stream_type_t stream,
761 uint32_t samplingRate,
762 audio_format_t format,
763 audio_channel_mask_t channelMask,
764 audio_output_flags_t flags,
765 const audio_offload_info_t *offloadInfo)
766{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700767 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700768 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700769 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700770
Eric Laurente552edb2014-03-10 17:42:56 -0700771#ifdef AUDIO_POLICY_TEST
772 if (mCurOutput != 0) {
773 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
774 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
775
776 if (mTestOutputs[mCurOutput] == 0) {
777 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700778 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
779 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700780 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700781 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700782 outputDesc->mFlags =
783 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700784 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700785 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
786 config.sample_rate = mTestSamplingRate;
787 config.channel_mask = mTestChannels;
788 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700789 if (offloadInfo != NULL) {
790 config.offload_info = *offloadInfo;
791 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700792 status = mpClientInterface->openOutput(0,
793 &mTestOutputs[mCurOutput],
794 &config,
795 &outputDesc->mDevice,
796 String8(""),
797 &outputDesc->mLatency,
798 outputDesc->mFlags);
799 if (status == NO_ERROR) {
800 outputDesc->mSamplingRate = config.sample_rate;
801 outputDesc->mFormat = config.format;
802 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700803 AudioParameter outputCmd = AudioParameter();
804 outputCmd.addInt(String8("set_id"),mCurOutput);
805 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
806 addOutput(mTestOutputs[mCurOutput], outputDesc);
807 }
808 }
809 return mTestOutputs[mCurOutput];
810 }
811#endif //AUDIO_POLICY_TEST
812
813 // open a direct output if required by specified parameters
814 //force direct flag if offload flag is set: offloading implies a direct output stream
815 // and all common behaviors are driven by checking only the direct flag
816 // this should normally be set appropriately in the policy configuration file
817 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700818 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700819 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700820 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
821 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
822 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800823 // only allow deep buffering for music stream type
824 if (stream != AUDIO_STREAM_MUSIC) {
825 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700826 } else if (/* stream == AUDIO_STREAM_MUSIC && */
827 flags == AUDIO_OUTPUT_FLAG_NONE &&
828 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
829 // use DEEP_BUFFER as default output for music stream type
830 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800831 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700832 if (stream == AUDIO_STREAM_TTS) {
833 flags = AUDIO_OUTPUT_FLAG_TTS;
834 }
Eric Laurente552edb2014-03-10 17:42:56 -0700835
Eric Laurentb732cf52014-09-24 19:08:21 -0700836 sp<IOProfile> profile;
837
838 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700839 // and not explicitly requested
840 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
Glenn Kasten05ddca52016-02-11 08:17:12 -0800841 audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700842 audio_channel_count_from_out_mask(channelMask) <= 2) {
843 goto non_direct_output;
844 }
845
Andy Hung2ddee192015-12-18 17:34:44 -0800846 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
847 // This prevents creating an offloaded track and tearing it down immediately after start
848 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700849 // FIXME: We should check the audio session here but we do not have it in this context.
850 // This may prevent offloading in rare situations where effects are left active by apps
851 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700852
Eric Laurente552edb2014-03-10 17:42:56 -0700853 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800854 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700855 profile = getProfileForDirectOutput(device,
856 samplingRate,
857 format,
858 channelMask,
859 (audio_output_flags_t)flags);
860 }
861
Eric Laurent1c333e22014-05-20 10:48:17 -0700862 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700864
865 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700866 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700867 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
868 outputDesc = desc;
869 // reuse direct output if currently open and configured with same parameters
870 if ((samplingRate == outputDesc->mSamplingRate) &&
Eric Laurente6930022016-02-11 10:20:40 -0800871 audio_formats_match(format, outputDesc->mFormat) &&
Eric Laurente552edb2014-03-10 17:42:56 -0700872 (channelMask == outputDesc->mChannelMask)) {
873 outputDesc->mDirectOpenCount++;
874 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
875 return mOutputs.keyAt(i);
876 }
877 }
878 }
879 // close direct output if currently open and configured with different parameters
880 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700881 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700882 }
Eric Laurent861a6282015-05-18 15:40:16 -0700883
884 // if the selected profile is offloaded and no offload info was specified,
885 // create a default one
886 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100887 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700888 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
889 defaultOffloadInfo.sample_rate = samplingRate;
890 defaultOffloadInfo.channel_mask = channelMask;
891 defaultOffloadInfo.format = format;
892 defaultOffloadInfo.stream_type = stream;
893 defaultOffloadInfo.bit_rate = 0;
894 defaultOffloadInfo.duration_us = -1;
895 defaultOffloadInfo.has_video = true; // conservative
896 defaultOffloadInfo.is_streaming = true; // likely
897 offloadInfo = &defaultOffloadInfo;
898 }
899
Eric Laurentc75307b2015-03-17 15:29:32 -0700900 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700901 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700902 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700903 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700904 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
905 config.sample_rate = samplingRate;
906 config.channel_mask = channelMask;
907 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700908 if (offloadInfo != NULL) {
909 config.offload_info = *offloadInfo;
910 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700911 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700912 &output,
913 &config,
914 &outputDesc->mDevice,
915 String8(""),
916 &outputDesc->mLatency,
917 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700918
919 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700920 if (status != NO_ERROR ||
921 (samplingRate != 0 && samplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -0800922 (format != AUDIO_FORMAT_DEFAULT && !audio_formats_match(format, config.format)) ||
Eric Laurentcf2c0212014-07-25 16:20:43 -0700923 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700924 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
925 "format %d %d, channelMask %04x %04x", output, samplingRate,
926 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
927 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700928 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700929 mpClientInterface->closeOutput(output);
930 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800931 // fall back to mixer output if possible when the direct output could not be open
Glenn Kasten05ddca52016-02-11 08:17:12 -0800932 if (audio_is_linear_pcm(format) && samplingRate <= SAMPLE_RATE_HZ_MAX) {
Eric Laurenta82797f2015-01-30 11:49:43 -0800933 goto non_direct_output;
934 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700935 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700936 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700937 outputDesc->mSamplingRate = config.sample_rate;
938 outputDesc->mChannelMask = config.channel_mask;
939 outputDesc->mFormat = config.format;
940 outputDesc->mRefCount[stream] = 0;
941 outputDesc->mStopTime[stream] = 0;
942 outputDesc->mDirectOpenCount = 1;
943
Eric Laurente552edb2014-03-10 17:42:56 -0700944 audio_io_handle_t srcOutput = getOutputForEffect();
945 addOutput(output, outputDesc);
946 audio_io_handle_t dstOutput = getOutputForEffect();
947 if (dstOutput == output) {
948 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
949 }
950 mPreviousOutputs = mOutputs;
951 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700952 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700953 return output;
954 }
955
Eric Laurentb732cf52014-09-24 19:08:21 -0700956non_direct_output:
Eric Laurent14cbfca2016-03-17 09:42:16 -0700957
958 // A request for HW A/V sync cannot fallback to a mixed output because time
959 // stamps are embedded in audio data
960 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
961 return AUDIO_IO_HANDLE_NONE;
962 }
963
Eric Laurente552edb2014-03-10 17:42:56 -0700964 // ignoring channel mask due to downmix capability in mixer
965
966 // open a non direct output
967
968 // for non direct outputs, only PCM is supported
969 if (audio_is_linear_pcm(format)) {
970 // get which output is suitable for the specified stream. The actual
971 // routing change will happen when startOutput() will be called
972 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
973
Eric Laurent8838a382014-09-08 16:44:28 -0700974 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
975 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
976 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700977 }
978 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
979 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
980
Paul McLeanaa981192015-03-21 09:55:15 -0700981 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700982
983 return output;
984}
985
Eric Laurente0720872014-03-11 09:30:41 -0700986audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700987 audio_output_flags_t flags,
988 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700989{
990 // select one output among several that provide a path to a particular device or set of
991 // devices (the list was previously build by getOutputsForDevice()).
992 // The priority is as follows:
993 // 1: the output with the highest number of requested policy flags
Eric Laurente6930022016-02-11 10:20:40 -0800994 // 2: the output with the bit depth the closest to the requested one
995 // 3: the primary output
996 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -0700997
998 if (outputs.size() == 0) {
999 return 0;
1000 }
1001 if (outputs.size() == 1) {
1002 return outputs[0];
1003 }
1004
1005 int maxCommonFlags = 0;
Eric Laurente6930022016-02-11 10:20:40 -08001006 audio_io_handle_t outputForFlags = 0;
1007 audio_io_handle_t outputForPrimary = 0;
1008 audio_io_handle_t outputForFormat = 0;
1009 audio_format_t bestFormat = AUDIO_FORMAT_INVALID;
1010 audio_format_t bestFormatForFlags = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001011
1012 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001013 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001014 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001015 // if a valid format is specified, skip output if not compatible
1016 if (format != AUDIO_FORMAT_INVALID) {
1017 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente6930022016-02-11 10:20:40 -08001018 if (!audio_formats_match(format, outputDesc->mFormat)) {
Eric Laurent8838a382014-09-08 16:44:28 -07001019 continue;
1020 }
1021 } else if (!audio_is_linear_pcm(format)) {
1022 continue;
1023 }
Eric Laurente6930022016-02-11 10:20:40 -08001024 if (AudioPort::isBetterFormatMatch(
1025 outputDesc->mFormat, bestFormat, format)) {
1026 outputForFormat = outputs[i];
1027 bestFormat = outputDesc->mFormat;
1028 }
Eric Laurent8838a382014-09-08 16:44:28 -07001029 }
1030
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001031 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente6930022016-02-11 10:20:40 -08001032 if (commonFlags >= maxCommonFlags) {
1033 if (commonFlags == maxCommonFlags) {
1034 if (AudioPort::isBetterFormatMatch(
1035 outputDesc->mFormat, bestFormatForFlags, format)) {
1036 outputForFlags = outputs[i];
1037 bestFormatForFlags = outputDesc->mFormat;
1038 }
1039 } else {
1040 outputForFlags = outputs[i];
1041 maxCommonFlags = commonFlags;
1042 bestFormatForFlags = outputDesc->mFormat;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1045 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001046 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente6930022016-02-11 10:20:40 -08001047 outputForPrimary = outputs[i];
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
1049 }
1050 }
1051
Eric Laurente6930022016-02-11 10:20:40 -08001052 if (outputForFlags != 0) {
1053 return outputForFlags;
Eric Laurente552edb2014-03-10 17:42:56 -07001054 }
Eric Laurente6930022016-02-11 10:20:40 -08001055 if (outputForFormat != 0) {
1056 return outputForFormat;
1057 }
1058 if (outputForPrimary != 0) {
1059 return outputForPrimary;
Eric Laurente552edb2014-03-10 17:42:56 -07001060 }
1061
1062 return outputs[0];
1063}
1064
Eric Laurente0720872014-03-11 09:30:41 -07001065status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001066 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001067 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001068{
Paul McLeanaa981192015-03-21 09:55:15 -07001069 ALOGV("startOutput() output %d, stream %d, session %d",
1070 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001071 ssize_t index = mOutputs.indexOfKey(output);
1072 if (index < 0) {
1073 ALOGW("startOutput() unknown output %d", output);
1074 return BAD_VALUE;
1075 }
1076
Eric Laurentc75307b2015-03-17 15:29:32 -07001077 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1078
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001079 // Routing?
1080 mOutputRoutes.incRouteActivity(session);
1081
Eric Laurentc75307b2015-03-17 15:29:32 -07001082 audio_devices_t newDevice;
Eric Laurentc40d9692016-04-13 19:14:13 -07001083 AudioMix *policyMix = NULL;
1084 const char *address = NULL;
Eric Laurentc75307b2015-03-17 15:29:32 -07001085 if (outputDesc->mPolicyMix != NULL) {
Eric Laurentc40d9692016-04-13 19:14:13 -07001086 policyMix = outputDesc->mPolicyMix;
1087 address = policyMix->mDeviceAddress.string();
1088 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
1089 newDevice = policyMix->mDeviceType;
1090 } else {
1091 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1092 }
Eric Laurent493404d2015-04-21 15:07:36 -07001093 } else if (mOutputRoutes.hasRouteChanged(session)) {
1094 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001095 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001096 } else {
1097 newDevice = AUDIO_DEVICE_NONE;
1098 }
1099
1100 uint32_t delayMs = 0;
1101
Eric Laurentc40d9692016-04-13 19:14:13 -07001102 status_t status = startSource(outputDesc, stream, newDevice, address, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001103
1104 if (status != NO_ERROR) {
1105 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001106 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001107 }
1108 // Automatically enable the remote submix input when output is started on a re routing mix
1109 // of type MIX_TYPE_RECORDERS
Eric Laurentc40d9692016-04-13 19:14:13 -07001110 if (audio_is_remote_submix_device(newDevice) && policyMix != NULL &&
1111 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001112 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1113 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Eric Laurentc40d9692016-04-13 19:14:13 -07001114 address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001115 "remote-submix");
1116 }
1117
1118 if (delayMs != 0) {
1119 usleep(delayMs * 1000);
1120 }
1121
1122 return status;
1123}
1124
1125status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1126 audio_stream_type_t stream,
1127 audio_devices_t device,
Eric Laurentc40d9692016-04-13 19:14:13 -07001128 const char *address,
Eric Laurentc75307b2015-03-17 15:29:32 -07001129 uint32_t *delayMs)
1130{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001131 // cannot start playback of STREAM_TTS if any other output is being used
1132 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001133
1134 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001135 if (stream == AUDIO_STREAM_TTS) {
1136 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001137 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001138 return INVALID_OPERATION;
1139 } else {
1140 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1141 }
1142 } else {
1143 // some playback other than beacon starts
1144 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1145 }
1146
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001147 // check active before incrementing usage count
1148 bool force = !outputDesc->isActive();
1149
Eric Laurente552edb2014-03-10 17:42:56 -07001150 // increment usage count for this stream on the requested output:
1151 // NOTE that the usage count is the same for duplicated output and hardware output which is
1152 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1153 outputDesc->changeRefCount(stream, 1);
1154
Eric Laurent493404d2015-04-21 15:07:36 -07001155 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001156 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001157 if (device == AUDIO_DEVICE_NONE) {
1158 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001159 }
Eric Laurente552edb2014-03-10 17:42:56 -07001160 routing_strategy strategy = getStrategy(stream);
1161 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001162 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1163 (beaconMuteLatency > 0);
1164 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001165 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001166 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001167 if (desc != outputDesc) {
1168 // force a device change if any other output is managed by the same hw
1169 // module and has a current device selection that differs from selected device.
1170 // In this case, the audio HAL must receive the new device selection so that it can
1171 // change the device currently selected by the other active output.
1172 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001173 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001174 force = true;
1175 }
1176 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001177 // a notification so that audio focus effect can propagate, or that a mute/unmute
1178 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001179 uint32_t latency = desc->latency();
1180 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1181 waitMs = latency;
1182 }
1183 }
1184 }
Eric Laurentc40d9692016-04-13 19:14:13 -07001185 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force, 0, NULL, address);
Eric Laurente552edb2014-03-10 17:42:56 -07001186
1187 // handle special case for sonification while in call
1188 if (isInCall()) {
1189 handleIncallSonification(stream, true, false);
1190 }
1191
1192 // apply volume rules for current stream and device if necessary
1193 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01001194 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07001195 outputDesc,
1196 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001197
1198 // update the outputs if starting an output with a stream that can affect notification
1199 // routing
1200 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001201
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001202 // force reevaluating accessibility routing when ringtone or alarm starts
1203 if (strategy == STRATEGY_SONIFICATION) {
1204 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1205 }
Eric Laurente552edb2014-03-10 17:42:56 -07001206 }
1207 return NO_ERROR;
1208}
1209
1210
Eric Laurente0720872014-03-11 09:30:41 -07001211status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001212 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001213 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001214{
1215 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1216 ssize_t index = mOutputs.indexOfKey(output);
1217 if (index < 0) {
1218 ALOGW("stopOutput() unknown output %d", output);
1219 return BAD_VALUE;
1220 }
1221
Eric Laurentc75307b2015-03-17 15:29:32 -07001222 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001223
Eric Laurentc75307b2015-03-17 15:29:32 -07001224 if (outputDesc->mRefCount[stream] == 1) {
1225 // Automatically disable the remote submix input when output is stopped on a
1226 // re routing mix of type MIX_TYPE_RECORDERS
1227 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1228 outputDesc->mPolicyMix != NULL &&
1229 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1230 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1231 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001232 outputDesc->mPolicyMix->mDeviceAddress,
Eric Laurentc75307b2015-03-17 15:29:32 -07001233 "remote-submix");
1234 }
1235 }
1236
1237 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001238 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001239 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001240 int activityCount = mOutputRoutes.decRouteActivity(session);
1241 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1242
1243 if (forceDeviceUpdate) {
1244 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1245 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001246 }
1247
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001248 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001249}
1250
1251status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001252 audio_stream_type_t stream,
1253 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001254{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001255 // always handle stream stop, check which stream type is stopping
1256 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1257
Eric Laurente552edb2014-03-10 17:42:56 -07001258 // handle special case for sonification while in call
1259 if (isInCall()) {
1260 handleIncallSonification(stream, false, false);
1261 }
1262
1263 if (outputDesc->mRefCount[stream] > 0) {
1264 // decrement usage count of this stream on the output
1265 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001266
Eric Laurente552edb2014-03-10 17:42:56 -07001267 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001268 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001269 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001270 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001271 // delay the device switch by twice the latency because stopOutput() is executed when
1272 // the track stop() command is received and at that time the audio track buffer can
1273 // still contain data that needs to be drained. The latency only covers the audio HAL
1274 // and kernel buffers. Also the latency does not always include additional delay in the
1275 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001276 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001277
1278 // force restoring the device selection on other active outputs if it differs from the
1279 // one being selected for this output
1280 for (size_t i = 0; i < mOutputs.size(); i++) {
1281 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001282 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001283 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001284 desc->isActive() &&
1285 outputDesc->sharesHwModuleWith(desc) &&
1286 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001287 setOutputDevice(desc,
1288 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001289 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001290 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001291 }
1292 }
1293 // update the outputs if stopping one with a stream that can affect notification routing
1294 handleNotificationRoutingForStream(stream);
1295 }
1296 return NO_ERROR;
1297 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001298 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001299 return INVALID_OPERATION;
1300 }
1301}
1302
Eric Laurente83b55d2014-11-14 10:06:21 -08001303void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001304 audio_stream_type_t stream __unused,
1305 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001306{
1307 ALOGV("releaseOutput() %d", output);
1308 ssize_t index = mOutputs.indexOfKey(output);
1309 if (index < 0) {
1310 ALOGW("releaseOutput() releasing unknown output %d", output);
1311 return;
1312 }
1313
1314#ifdef AUDIO_POLICY_TEST
1315 int testIndex = testOutputIndex(output);
1316 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001317 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001318 if (outputDesc->isActive()) {
1319 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001320 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001321 mTestOutputs[testIndex] = 0;
1322 }
1323 return;
1324 }
1325#endif //AUDIO_POLICY_TEST
1326
Paul McLeanaa981192015-03-21 09:55:15 -07001327 // Routing
1328 mOutputRoutes.removeRoute(session);
1329
Eric Laurentc75307b2015-03-17 15:29:32 -07001330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001331 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001332 if (desc->mDirectOpenCount <= 0) {
1333 ALOGW("releaseOutput() invalid open count %d for output %d",
1334 desc->mDirectOpenCount, output);
1335 return;
1336 }
1337 if (--desc->mDirectOpenCount == 0) {
1338 closeOutput(output);
1339 // If effects where present on the output, audioflinger moved them to the primary
1340 // output by default: move them back to the appropriate output.
1341 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001342 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001343 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1344 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001345 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001346 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001347 }
1348 }
1349}
1350
1351
Eric Laurentcaf7f482014-11-25 17:50:47 -08001352status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1353 audio_io_handle_t *input,
1354 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001355 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001356 uint32_t samplingRate,
1357 audio_format_t format,
1358 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001359 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001360 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001361 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001362{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001363 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1364 "session %d, flags %#x",
1365 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001366
Eric Laurentcaf7f482014-11-25 17:50:47 -08001367 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001368 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001369 audio_devices_t device;
1370 // handle legacy remote submix case where the address was not always specified
1371 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001372 audio_source_t inputSource = attr->source;
1373 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001374 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001375
Eric Laurentc447ded2015-01-06 08:47:05 -08001376 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1377 inputSource = AUDIO_SOURCE_MIC;
1378 }
1379 halInputSource = inputSource;
1380
Paul McLean466dc8e2015-04-17 13:15:36 -06001381 // Explicit routing?
1382 sp<DeviceDescriptor> deviceDesc;
1383 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1384 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1385 deviceDesc = mAvailableInputDevices[i];
1386 break;
1387 }
1388 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001389 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001390
Eric Laurentc447ded2015-01-06 08:47:05 -08001391 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001392 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001393 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001394 if (ret != NO_ERROR) {
1395 return ret;
1396 }
1397 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001398 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1399 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001400 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001401 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001402 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001403 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001404 return BAD_VALUE;
1405 }
Eric Laurentc722f302014-12-10 11:21:49 -08001406 if (policyMix != NULL) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001407 address = policyMix->mDeviceAddress;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001408 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1409 // there is an external policy, but this input is attached to a mix of recorders,
1410 // meaning it receives audio injected into the framework, so the recorder doesn't
1411 // know about it and is therefore considered "legacy"
1412 *inputType = API_INPUT_LEGACY;
1413 } else {
1414 // recording a mix of players defined by an external policy, we're rerouting for
1415 // an external policy
1416 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1417 }
Eric Laurentc722f302014-12-10 11:21:49 -08001418 } else if (audio_is_remote_submix_device(device)) {
1419 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001420 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001421 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1422 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001423 } else {
1424 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001425 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001426
Eric Laurent599c7582015-12-07 18:05:55 -08001427 }
1428
1429 *input = getInputForDevice(device, address, session, uid, inputSource,
1430 samplingRate, format, channelMask, flags,
1431 policyMix);
1432 if (*input == AUDIO_IO_HANDLE_NONE) {
1433 mInputRoutes.removeRoute(session);
1434 return INVALID_OPERATION;
1435 }
1436 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1437 return NO_ERROR;
1438}
1439
1440
1441audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1442 String8 address,
1443 audio_session_t session,
1444 uid_t uid,
1445 audio_source_t inputSource,
1446 uint32_t samplingRate,
1447 audio_format_t format,
1448 audio_channel_mask_t channelMask,
1449 audio_input_flags_t flags,
1450 AudioMix *policyMix)
1451{
1452 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1453 audio_source_t halInputSource = inputSource;
1454 bool isSoundTrigger = false;
1455
1456 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1457 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1458 if (index >= 0) {
1459 input = mSoundTriggerSessions.valueFor(session);
1460 isSoundTrigger = true;
1461 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1462 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1463 } else {
1464 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001465 }
1466 }
1467
Andy Hungf129b032015-04-07 13:45:50 -07001468 // find a compatible input profile (not necessarily identical in parameters)
1469 sp<IOProfile> profile;
1470 // samplingRate and flags may be updated by getInputProfile
Glenn Kasten05ddca52016-02-11 08:17:12 -08001471 uint32_t profileSamplingRate = (samplingRate == 0) ? SAMPLE_RATE_HZ_DEFAULT : samplingRate;
Andy Hungf129b032015-04-07 13:45:50 -07001472 audio_format_t profileFormat = format;
1473 audio_channel_mask_t profileChannelMask = channelMask;
1474 audio_input_flags_t profileFlags = flags;
1475 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001476 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001477 profileSamplingRate, profileFormat, profileChannelMask,
1478 profileFlags);
1479 if (profile != 0) {
1480 break; // success
1481 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1482 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1483 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001484 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1485 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001486 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001487 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001488 }
Eric Laurente552edb2014-03-10 17:42:56 -07001489 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08001490 // Pick input sampling rate if not specified by client
1491 if (samplingRate == 0) {
1492 samplingRate = profileSamplingRate;
1493 }
Eric Laurente552edb2014-03-10 17:42:56 -07001494
Eric Laurent322b4d22015-04-03 15:57:54 -07001495 if (profile->getModuleHandle() == 0) {
1496 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001497 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001498 }
1499
Eric Laurent599c7582015-12-07 18:05:55 -08001500 sp<AudioSession> audioSession = new AudioSession(session,
1501 inputSource,
1502 format,
1503 samplingRate,
1504 channelMask,
1505 flags,
1506 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001507 isSoundTrigger,
1508 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001509
Eric Laurent232f26f2016-02-17 18:06:27 -08001510// TODO enable input reuse
1511#if 0
Eric Laurent599c7582015-12-07 18:05:55 -08001512 // reuse an open input if possible
1513 for (size_t i = 0; i < mInputs.size(); i++) {
1514 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent232f26f2016-02-17 18:06:27 -08001515 // reuse input if it shares the same profile and same sound trigger attribute
1516 if (profile == desc->mProfile &&
1517 isSoundTrigger == desc->isSoundTrigger()) {
Eric Laurent599c7582015-12-07 18:05:55 -08001518
1519 sp<AudioSession> as = desc->getAudioSession(session);
1520 if (as != 0) {
1521 // do not allow unmatching properties on same session
1522 if (as->matches(audioSession)) {
1523 as->changeOpenCount(1);
1524 } else {
1525 ALOGW("getInputForDevice() record with different attributes"
1526 " exists for session %d", session);
Eric Laurent232f26f2016-02-17 18:06:27 -08001527 return input;
Eric Laurent599c7582015-12-07 18:05:55 -08001528 }
1529 } else {
1530 desc->addAudioSession(session, audioSession);
1531 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001532 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1533 return mInputs.keyAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001534 }
1535 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001536#endif
Eric Laurent599c7582015-12-07 18:05:55 -08001537
Eric Laurentcf2c0212014-07-25 16:20:43 -07001538 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001539 config.sample_rate = profileSamplingRate;
1540 config.channel_mask = profileChannelMask;
1541 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001542
Eric Laurent322b4d22015-04-03 15:57:54 -07001543 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001544 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001545 &config,
1546 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001547 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001548 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001549 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001550
1551 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001552 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001553 (profileSamplingRate != config.sample_rate) ||
Eric Laurente6930022016-02-11 10:20:40 -08001554 !audio_formats_match(profileFormat, config.format) ||
Andy Hungf129b032015-04-07 13:45:50 -07001555 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001556 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1557 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001558 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001559 if (input != AUDIO_IO_HANDLE_NONE) {
1560 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001561 }
Eric Laurent599c7582015-12-07 18:05:55 -08001562 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001563 }
1564
Eric Laurent1f2f2232014-06-02 12:01:23 -07001565 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001566 inputDesc->mSamplingRate = profileSamplingRate;
1567 inputDesc->mFormat = profileFormat;
1568 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001569 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001570 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001571 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001572
Eric Laurent599c7582015-12-07 18:05:55 -08001573 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001574 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001575
Eric Laurent599c7582015-12-07 18:05:55 -08001576 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001577}
1578
Eric Laurent4dc68062014-07-28 17:26:49 -07001579status_t AudioPolicyManager::startInput(audio_io_handle_t input,
Eric Laurent232f26f2016-02-17 18:06:27 -08001580 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001581{
1582 ALOGV("startInput() input %d", input);
1583 ssize_t index = mInputs.indexOfKey(input);
1584 if (index < 0) {
1585 ALOGW("startInput() unknown input %d", input);
1586 return BAD_VALUE;
1587 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001588 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001589
Eric Laurent599c7582015-12-07 18:05:55 -08001590 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1591 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001592 ALOGW("startInput() unknown session %d on input %d", session, input);
1593 return BAD_VALUE;
1594 }
1595
Eric Laurent232f26f2016-02-17 18:06:27 -08001596 // virtual input devices are compatible with other input devices
1597 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001598
Eric Laurent232f26f2016-02-17 18:06:27 -08001599 // for a non-virtual input device, check if there is another (non-virtual) active input
1600 audio_io_handle_t activeInput = mInputs.getActiveInput();
1601 if (activeInput != 0 && activeInput != input) {
Eric Laurente552edb2014-03-10 17:42:56 -07001602
Eric Laurent232f26f2016-02-17 18:06:27 -08001603 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1604 // otherwise the active input continues and the new input cannot be started.
1605 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1606 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
1607 !activeDesc->hasPreemptedSession(session)) {
1608 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1609 //FIXME: consider all active sessions
1610 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1611 audio_session_t activeSession = activeSessions.keyAt(0);
1612 SortedVector<audio_session_t> sessions =
1613 activeDesc->getPreemptedSessions();
1614 sessions.add(activeSession);
1615 inputDesc->setPreemptedSessions(sessions);
1616 stopInput(activeInput, activeSession);
1617 releaseInput(activeInput, activeSession);
1618 } else {
1619 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1620 return INVALID_OPERATION;
1621 }
1622 }
1623
1624 // Do not allow capture if an active voice call is using a software patch and
1625 // the call TX source device is on the same HW module.
1626 // FIXME: would be better to refine to only inputs whose profile connects to the
1627 // call TX device but this information is not in the audio patch
1628 if (mCallTxPatch != 0 &&
1629 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1630 return INVALID_OPERATION;
1631 }
1632 }
Eric Laurent313d1e72016-01-29 09:56:57 -08001633
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001634 // Routing?
1635 mInputRoutes.incRouteActivity(session);
1636
Eric Laurent232f26f2016-02-17 18:06:27 -08001637 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
1638 // if input maps to a dynamic policy with an activity listener, notify of state change
1639 if ((inputDesc->mPolicyMix != NULL)
1640 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001641 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001642 MIX_STATE_MIXING);
1643 }
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001644
Eric Laurent232f26f2016-02-17 18:06:27 -08001645 if (mInputs.activeInputsCount() == 0) {
1646 SoundTrigger::setCaptureState(true);
1647 }
1648 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001649
Eric Laurent232f26f2016-02-17 18:06:27 -08001650 // automatically enable the remote submix output when input is started if not
1651 // used by a policy mix of type MIX_TYPE_RECORDERS
1652 // For remote submix (a virtual device), we open only one input per capture request.
1653 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1654 String8 address = String8("");
1655 if (inputDesc->mPolicyMix == NULL) {
1656 address = String8("0");
1657 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001658 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurentc722f302014-12-10 11:21:49 -08001659 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001660 if (address != "") {
1661 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1662 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1663 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001664 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001665 }
Eric Laurente552edb2014-03-10 17:42:56 -07001666 }
1667
Eric Laurent599c7582015-12-07 18:05:55 -08001668 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001669
Eric Laurent232f26f2016-02-17 18:06:27 -08001670 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001671 return NO_ERROR;
1672}
1673
Eric Laurent4dc68062014-07-28 17:26:49 -07001674status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1675 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001676{
1677 ALOGV("stopInput() input %d", input);
1678 ssize_t index = mInputs.indexOfKey(input);
1679 if (index < 0) {
1680 ALOGW("stopInput() unknown input %d", input);
1681 return BAD_VALUE;
1682 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001683 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001684
Eric Laurent599c7582015-12-07 18:05:55 -08001685 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001686 if (index < 0) {
1687 ALOGW("stopInput() unknown session %d on input %d", session, input);
1688 return BAD_VALUE;
1689 }
1690
Eric Laurent599c7582015-12-07 18:05:55 -08001691 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001692 ALOGW("stopInput() input %d already stopped", input);
1693 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001694 }
1695
Eric Laurent599c7582015-12-07 18:05:55 -08001696 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001697
1698 // Routing?
1699 mInputRoutes.decRouteActivity(session);
1700
Eric Laurent232f26f2016-02-17 18:06:27 -08001701 if (!inputDesc->isActive()) {
1702 // if input maps to a dynamic policy with an activity listener, notify of state change
1703 if ((inputDesc->mPolicyMix != NULL)
1704 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001705 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mDeviceAddress,
Eric Laurent232f26f2016-02-17 18:06:27 -08001706 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00001707 }
Eric Laurent232f26f2016-02-17 18:06:27 -08001708
1709 // automatically disable the remote submix output when input is stopped if not
1710 // used by a policy mix of type MIX_TYPE_RECORDERS
1711 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1712 String8 address = String8("");
1713 if (inputDesc->mPolicyMix == NULL) {
1714 address = String8("0");
1715 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08001716 address = inputDesc->mPolicyMix->mDeviceAddress;
Eric Laurent232f26f2016-02-17 18:06:27 -08001717 }
1718 if (address != "") {
1719 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1720 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1721 address, "remote-submix");
1722 }
1723 }
1724
1725 resetInputDevice(input);
1726
1727 if (mInputs.activeInputsCount() == 0) {
1728 SoundTrigger::setCaptureState(false);
1729 }
1730 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001731 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001732 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001733}
1734
Eric Laurent4dc68062014-07-28 17:26:49 -07001735void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1736 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001737{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001738
Eric Laurente552edb2014-03-10 17:42:56 -07001739 ALOGV("releaseInput() %d", input);
1740 ssize_t index = mInputs.indexOfKey(input);
1741 if (index < 0) {
1742 ALOGW("releaseInput() releasing unknown input %d", input);
1743 return;
1744 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001745
1746 // Routing
1747 mInputRoutes.removeRoute(session);
1748
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001749 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1750 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001751
Eric Laurent599c7582015-12-07 18:05:55 -08001752 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001753 if (index < 0) {
1754 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1755 return;
1756 }
Eric Laurent599c7582015-12-07 18:05:55 -08001757
1758 if (audioSession->openCount() == 0) {
1759 ALOGW("releaseInput() invalid open count %d on session %d",
1760 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001761 return;
1762 }
Eric Laurent599c7582015-12-07 18:05:55 -08001763
1764 if (audioSession->changeOpenCount(-1) == 0) {
1765 inputDesc->removeAudioSession(session);
1766 }
1767
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001768 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001769 ALOGV("releaseInput() exit > 0");
1770 return;
1771 }
1772
Eric Laurent05b90f82014-08-27 15:32:29 -07001773 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001774 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001775 ALOGV("releaseInput() exit");
1776}
1777
Eric Laurentd4692962014-05-05 18:13:44 -07001778void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001779 bool patchRemoved = false;
1780
Eric Laurentd4692962014-05-05 18:13:44 -07001781 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001782 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08001783 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07001784 if (patch_index >= 0) {
1785 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1786 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1787 mAudioPatches.removeItemsAt(patch_index);
1788 patchRemoved = true;
1789 }
Eric Laurentd4692962014-05-05 18:13:44 -07001790 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1791 }
1792 mInputs.clear();
Chris Thornton52785f32016-02-09 17:28:49 -08001793 SoundTrigger::setCaptureState(false);
Eric Laurent6a94d692014-05-20 11:18:06 -07001794 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001795
1796 if (patchRemoved) {
1797 mpClientInterface->onAudioPatchListUpdate();
1798 }
Eric Laurentd4692962014-05-05 18:13:44 -07001799}
1800
Eric Laurente0720872014-03-11 09:30:41 -07001801void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001802 int indexMin,
1803 int indexMax)
1804{
1805 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffied1ab2bd2015-12-02 18:20:06 +01001806 mVolumeCurves->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08001807
1808 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001809 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1810 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001811 continue;
1812 }
1813 mVolumeCurves->initStreamVolume((audio_stream_type_t)curStream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001814 }
Eric Laurente552edb2014-03-10 17:42:56 -07001815}
1816
Eric Laurente0720872014-03-11 09:30:41 -07001817status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001818 int index,
1819 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001820{
1821
François Gaffied1ab2bd2015-12-02 18:20:06 +01001822 if ((index < mVolumeCurves->getVolumeIndexMin(stream)) ||
1823 (index > mVolumeCurves->getVolumeIndexMax(stream))) {
Eric Laurente552edb2014-03-10 17:42:56 -07001824 return BAD_VALUE;
1825 }
1826 if (!audio_is_output_device(device)) {
1827 return BAD_VALUE;
1828 }
1829
1830 // Force max volume if stream cannot be muted
François Gaffied1ab2bd2015-12-02 18:20:06 +01001831 if (!mVolumeCurves->canBeMuted(stream)) index = mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001832
Eric Laurent1fd372e2016-04-06 14:23:53 -07001833 ALOGV("setStreamVolumeIndex() stream %d, device %08x, index %d",
Eric Laurente552edb2014-03-10 17:42:56 -07001834 stream, device, index);
1835
Eric Laurent28d09f02016-03-08 10:43:05 -08001836 // update other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08001837 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1838 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001839 continue;
1840 }
1841 mVolumeCurves->addCurrentVolumeIndex((audio_stream_type_t)curStream, device, index);
1842 }
Eric Laurente552edb2014-03-10 17:42:56 -07001843
Eric Laurent1fd372e2016-04-06 14:23:53 -07001844 // update volume on all outputs and streams matching the following:
1845 // - The requested stream (or a stream matching for volume control) is active on the output
1846 // - The device (or devices) selected by the strategy corresponding to this stream includes
1847 // the requested device
1848 // - For non default requested device, currently selected device on the output is either the
1849 // requested device or one of the devices selected by the strategy
Eric Laurent5a2b6292016-04-14 18:05:57 -07001850 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
1851 // no specific device volume value exists for currently selected device.
Eric Laurente552edb2014-03-10 17:42:56 -07001852 status_t status = NO_ERROR;
1853 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001854 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1855 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent794fde22016-03-11 09:50:45 -08001856 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
1857 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001858 continue;
Eric Laurente552edb2014-03-10 17:42:56 -07001859 }
Eric Laurent1fd372e2016-04-06 14:23:53 -07001860 if (!desc->isStreamActive((audio_stream_type_t)curStream)) {
1861 continue;
1862 }
Eric Laurent794fde22016-03-11 09:50:45 -08001863 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08001864 audio_devices_t curStreamDevice = getDeviceForStrategy(curStrategy, true /*fromCache*/);
Eric Laurent1fd372e2016-04-06 14:23:53 -07001865 if ((curStreamDevice & device) == 0) {
1866 continue;
1867 }
1868 bool applyDefault = false;
Eric Laurent5a2b6292016-04-14 18:05:57 -07001869 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurent1fd372e2016-04-06 14:23:53 -07001870 curStreamDevice |= device;
1871 } else if (!mVolumeCurves->hasVolumeIndexForDevice(
1872 stream, Volume::getDeviceForVolume(curStreamDevice))) {
1873 applyDefault = true;
1874 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001875
Eric Laurent1fd372e2016-04-06 14:23:53 -07001876 if (applyDefault || ((curDevice & curStreamDevice) != 0)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001877 status_t volStatus =
1878 checkAndSetVolume((audio_stream_type_t)curStream, index, desc, curDevice);
1879 if (volStatus != NO_ERROR) {
1880 status = volStatus;
1881 }
1882 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001883 }
Eric Laurente552edb2014-03-10 17:42:56 -07001884 }
1885 return status;
1886}
1887
Eric Laurente0720872014-03-11 09:30:41 -07001888status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001889 int *index,
1890 audio_devices_t device)
1891{
1892 if (index == NULL) {
1893 return BAD_VALUE;
1894 }
1895 if (!audio_is_output_device(device)) {
1896 return BAD_VALUE;
1897 }
Eric Laurent5a2b6292016-04-14 18:05:57 -07001898 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device corresponding to
Eric Laurente552edb2014-03-10 17:42:56 -07001899 // the strategy the stream belongs to.
Eric Laurent5a2b6292016-04-14 18:05:57 -07001900 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Eric Laurente552edb2014-03-10 17:42:56 -07001901 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1902 }
François Gaffiedfd74092015-03-19 12:10:59 +01001903 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001904
François Gaffied1ab2bd2015-12-02 18:20:06 +01001905 *index = mVolumeCurves->getVolumeIndex(stream, device);
Eric Laurente552edb2014-03-10 17:42:56 -07001906 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1907 return NO_ERROR;
1908}
1909
Eric Laurente0720872014-03-11 09:30:41 -07001910audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001911 const SortedVector<audio_io_handle_t>& outputs)
1912{
1913 // select one output among several suitable for global effects.
1914 // The priority is as follows:
1915 // 1: An offloaded output. If the effect ends up not being offloadable,
1916 // AudioFlinger will invalidate the track and the offloaded output
1917 // will be closed causing the effect to be moved to a PCM output.
1918 // 2: A deep buffer output
1919 // 3: the first output in the list
1920
1921 if (outputs.size() == 0) {
1922 return 0;
1923 }
1924
1925 audio_io_handle_t outputOffloaded = 0;
1926 audio_io_handle_t outputDeepBuffer = 0;
1927
1928 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001929 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001930 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001931 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1932 outputOffloaded = outputs[i];
1933 }
1934 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1935 outputDeepBuffer = outputs[i];
1936 }
1937 }
1938
1939 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1940 outputOffloaded, outputDeepBuffer);
1941 if (outputOffloaded != 0) {
1942 return outputOffloaded;
1943 }
1944 if (outputDeepBuffer != 0) {
1945 return outputDeepBuffer;
1946 }
1947
1948 return outputs[0];
1949}
1950
Eric Laurente0720872014-03-11 09:30:41 -07001951audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001952{
1953 // apply simple rule where global effects are attached to the same output as MUSIC streams
1954
Eric Laurent3b73df72014-03-11 09:06:29 -07001955 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001956 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1957 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1958
1959 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1960 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1961 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1962
1963 return output;
1964}
1965
Eric Laurente0720872014-03-11 09:30:41 -07001966status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001967 audio_io_handle_t io,
1968 uint32_t strategy,
1969 int session,
1970 int id)
1971{
1972 ssize_t index = mOutputs.indexOfKey(io);
1973 if (index < 0) {
1974 index = mInputs.indexOfKey(io);
1975 if (index < 0) {
1976 ALOGW("registerEffect() unknown io %d", io);
1977 return INVALID_OPERATION;
1978 }
1979 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001980 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001981}
1982
Eric Laurentc75307b2015-03-17 15:29:32 -07001983bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1984{
Eric Laurent28d09f02016-03-08 10:43:05 -08001985 bool active = false;
Eric Laurent794fde22016-03-11 09:50:45 -08001986 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT && !active; curStream++) {
1987 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08001988 continue;
1989 }
1990 active = mOutputs.isStreamActive((audio_stream_type_t)curStream, inPastMs);
1991 }
Eric Laurent28d09f02016-03-08 10:43:05 -08001992 return active;
Eric Laurentc75307b2015-03-17 15:29:32 -07001993}
1994
1995bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1996{
1997 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1998}
1999
Eric Laurente0720872014-03-11 09:30:41 -07002000bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002001{
2002 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002003 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002004 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002005 return true;
2006 }
2007 }
2008 return false;
2009}
2010
Eric Laurent275e8e92014-11-30 15:14:47 -08002011// Register a list of custom mixes with their attributes and format.
2012// When a mix is registered, corresponding input and output profiles are
2013// added to the remote submix hw module. The profile contains only the
2014// parameters (sampling rate, format...) specified by the mix.
2015// The corresponding input remote submix device is also connected.
2016//
2017// When a remote submix device is connected, the address is checked to select the
2018// appropriate profile and the corresponding input or output stream is opened.
2019//
2020// When capture starts, getInputForAttr() will:
2021// - 1 look for a mix matching the address passed in attribtutes tags if any
2022// - 2 if none found, getDeviceForInputSource() will:
2023// - 2.1 look for a mix matching the attributes source
2024// - 2.2 if none found, default to device selection by policy rules
2025// At this time, the corresponding output remote submix device is also connected
2026// and active playback use cases can be transferred to this mix if needed when reconnecting
2027// after AudioTracks are invalidated
2028//
2029// When playback starts, getOutputForAttr() will:
2030// - 1 look for a mix matching the address passed in attribtutes tags if any
2031// - 2 if none found, look for a mix matching the attributes usage
2032// - 3 if none found, default to device and output selection by policy rules.
2033
2034status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2035{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002036 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2037 status_t res = NO_ERROR;
2038
2039 sp<HwModule> rSubmixModule;
2040 // examine each mix's route type
2041 for (size_t i = 0; i < mixes.size(); i++) {
2042 // we only support MIX_ROUTE_FLAG_LOOP_BACK or MIX_ROUTE_FLAG_RENDER, not the combination
2043 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_ALL) == MIX_ROUTE_FLAG_ALL) {
2044 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08002045 break;
2046 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002047 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2048 // Loop back through "remote submix"
2049 if (rSubmixModule == 0) {
2050 for (size_t j = 0; i < mHwModules.size(); j++) {
2051 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2052 && mHwModules[j]->mHandle != 0) {
2053 rSubmixModule = mHwModules[j];
2054 break;
2055 }
2056 }
2057 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002058
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002059 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK", i, mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002060
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002061 if (rSubmixModule == 0) {
2062 ALOGE(" Unable to find audio module for submix, aborting mix %zu registration", i);
2063 res = INVALID_OPERATION;
2064 break;
2065 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002066
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002067 String8 address = mixes[i].mDeviceAddress;
François Gaffie036e1e92015-03-19 10:16:24 +01002068
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002069 if (mPolicyMixes.registerMix(address, mixes[i], 0 /*output desc*/) != NO_ERROR) {
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002070 ALOGE(" Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002071 res = INVALID_OPERATION;
2072 break;
2073 }
2074 audio_config_t outputConfig = mixes[i].mFormat;
2075 audio_config_t inputConfig = mixes[i].mFormat;
2076 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2077 // stereo and let audio flinger do the channel conversion if needed.
2078 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2079 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2080 rSubmixModule->addOutputProfile(address, &outputConfig,
2081 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2082 rSubmixModule->addInputProfile(address, &inputConfig,
2083 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002084
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002085 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
2086 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2087 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2088 address.string(), "remote-submix");
2089 } else {
2090 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2091 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2092 address.string(), "remote-submix");
2093 }
2094 } else if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002095 String8 address = mixes[i].mDeviceAddress;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002096 audio_devices_t device = mixes[i].mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002097 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2098 i, mixes.size(), device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002099
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002100 bool foundOutput = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002101 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2102 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2103 sp<AudioPatch> patch = mAudioPatches.valueFor(desc->getPatchHandle());
2104 if ((patch != 0) && (patch->mPatch.num_sinks != 0)
2105 && (patch->mPatch.sinks[0].type == AUDIO_PORT_TYPE_DEVICE)
2106 && (patch->mPatch.sinks[0].ext.device.type == device)
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002107 && (strncmp(patch->mPatch.sinks[0].ext.device.address, address.string(),
2108 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002109 if (mPolicyMixes.registerMix(address, mixes[i], desc) != NO_ERROR) {
2110 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002111 } else {
2112 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002113 }
2114 break;
2115 }
2116 }
2117
2118 if (res != NO_ERROR) {
2119 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07002120 i, device, address.string());
2121 res = INVALID_OPERATION;
2122 break;
2123 } else if (!foundOutput) {
2124 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2125 i, device, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002126 res = INVALID_OPERATION;
2127 break;
2128 }
Eric Laurentc722f302014-12-10 11:21:49 -08002129 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002130 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002131 if (res != NO_ERROR) {
2132 unregisterPolicyMixes(mixes);
2133 }
2134 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002135}
2136
2137status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2138{
Eric Laurent7b279bb2015-12-14 10:18:23 -08002139 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002140 status_t res = NO_ERROR;
2141 sp<HwModule> rSubmixModule;
2142 // examine each mix's route type
Eric Laurent275e8e92014-11-30 15:14:47 -08002143 for (size_t i = 0; i < mixes.size(); i++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002144 if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01002145
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002146 if (rSubmixModule == 0) {
2147 for (size_t j = 0; i < mHwModules.size(); j++) {
2148 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[j]->mName) == 0
2149 && mHwModules[j]->mHandle != 0) {
2150 rSubmixModule = mHwModules[j];
2151 break;
2152 }
2153 }
2154 }
2155 if (rSubmixModule == 0) {
2156 res = INVALID_OPERATION;
2157 continue;
2158 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002159
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002160 String8 address = mixes[i].mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08002161
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002162 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
2163 res = INVALID_OPERATION;
2164 continue;
2165 }
2166
2167 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2168 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2169 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2170 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2171 address.string(), "remote-submix");
2172 }
2173 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2174 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2175 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2176 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2177 address.string(), "remote-submix");
2178 }
2179 rSubmixModule->removeOutputProfile(address);
2180 rSubmixModule->removeInputProfile(address);
2181
2182 } if ((mixes[i].mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2183 if (mPolicyMixes.unregisterMix(mixes[i].mDeviceAddress) != NO_ERROR) {
2184 res = INVALID_OPERATION;
2185 continue;
2186 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002187 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002188 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08002189 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08002190}
2191
Eric Laurente552edb2014-03-10 17:42:56 -07002192
Eric Laurente0720872014-03-11 09:30:41 -07002193status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002194{
2195 const size_t SIZE = 256;
2196 char buffer[SIZE];
2197 String8 result;
2198
2199 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2200 result.append(buffer);
2201
Eric Laurent87ffa392015-05-22 10:32:38 -07002202 snprintf(buffer, SIZE, " Primary Output: %d\n",
2203 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002204 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002205 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002206 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002207 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002208 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002209 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002210 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002211 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002212 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002213 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002214 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002215 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002216 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002217 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002218 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002219 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002220 result.append(buffer);
Phil Burk09bc4612016-02-24 15:58:15 -08002221 snprintf(buffer, SIZE, " Force use for encoded surround output %d\n",
2222 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND));
2223 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002224 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2225 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002226 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2227 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002228
François Gaffie2110e042015-03-24 08:41:51 +01002229 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002230
François Gaffie112b0af2015-11-19 16:13:25 +01002231 mAvailableOutputDevices.dump(fd, String8("Available output"));
2232 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002233 mHwModules.dump(fd);
2234 mOutputs.dump(fd);
2235 mInputs.dump(fd);
François Gaffied1ab2bd2015-12-02 18:20:06 +01002236 mVolumeCurves->dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002237 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002238 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002239
2240 return NO_ERROR;
2241}
2242
2243// This function checks for the parameters which can be offloaded.
2244// This can be enhanced depending on the capability of the DSP and policy
2245// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002246bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002247{
2248 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002249 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002250 offloadInfo.sample_rate, offloadInfo.channel_mask,
2251 offloadInfo.format,
2252 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2253 offloadInfo.has_video);
2254
Andy Hung2ddee192015-12-18 17:34:44 -08002255 if (mMasterMono) {
2256 return false; // no offloading if mono is set.
2257 }
2258
Eric Laurente552edb2014-03-10 17:42:56 -07002259 // Check if offload has been disabled
2260 char propValue[PROPERTY_VALUE_MAX];
2261 if (property_get("audio.offload.disable", propValue, "0")) {
2262 if (atoi(propValue) != 0) {
2263 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2264 return false;
2265 }
2266 }
2267
2268 // Check if stream type is music, then only allow offload as of now.
2269 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2270 {
2271 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2272 return false;
2273 }
2274
2275 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002276 const bool allowOffloadWithVideo =
2277 property_get_bool("audio.offload.video", false /* default_value */);
2278 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002279 ALOGV("isOffloadSupported: has_video == true, returning false");
2280 return false;
2281 }
2282
2283 //If duration is less than minimum value defined in property, return false
2284 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2285 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2286 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2287 return false;
2288 }
2289 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2290 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2291 return false;
2292 }
2293
2294 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2295 // creating an offloaded track and tearing it down immediately after start when audioflinger
2296 // detects there is an active non offloadable effect.
2297 // FIXME: We should check the audio session here but we do not have it in this context.
2298 // This may prevent offloading in rare situations where effects are left active by apps
2299 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002300 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002301 return false;
2302 }
2303
2304 // See if there is a profile to support this.
2305 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002306 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002307 offloadInfo.sample_rate,
2308 offloadInfo.format,
2309 offloadInfo.channel_mask,
2310 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002311 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2312 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002313}
2314
Eric Laurent6a94d692014-05-20 11:18:06 -07002315status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2316 audio_port_type_t type,
2317 unsigned int *num_ports,
2318 struct audio_port *ports,
2319 unsigned int *generation)
2320{
2321 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2322 generation == NULL) {
2323 return BAD_VALUE;
2324 }
2325 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2326 if (ports == NULL) {
2327 *num_ports = 0;
2328 }
2329
2330 size_t portsWritten = 0;
2331 size_t portsMax = *num_ports;
2332 *num_ports = 0;
2333 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002334 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
2335 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07002336 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002337 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
2338 if (mAvailableOutputDevices[i]->type() == AUDIO_DEVICE_OUT_STUB) {
2339 continue;
2340 }
2341 if (portsWritten < portsMax) {
2342 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2343 }
2344 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07002345 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002346 }
2347 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07002348 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2349 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_STUB) {
2350 continue;
2351 }
2352 if (portsWritten < portsMax) {
2353 mAvailableInputDevices[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 }
2359 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2360 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2361 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2362 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2363 }
2364 *num_ports += mInputs.size();
2365 }
2366 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002367 size_t numOutputs = 0;
2368 for (size_t i = 0; i < mOutputs.size(); i++) {
2369 if (!mOutputs[i]->isDuplicated()) {
2370 numOutputs++;
2371 if (portsWritten < portsMax) {
2372 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2373 }
2374 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002375 }
Eric Laurent84c70242014-06-23 08:46:27 -07002376 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002377 }
2378 }
2379 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002380 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002381 return NO_ERROR;
2382}
2383
2384status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2385{
2386 return NO_ERROR;
2387}
2388
Eric Laurent6a94d692014-05-20 11:18:06 -07002389status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2390 audio_patch_handle_t *handle,
2391 uid_t uid)
2392{
2393 ALOGV("createAudioPatch()");
2394
2395 if (handle == NULL || patch == NULL) {
2396 return BAD_VALUE;
2397 }
2398 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2399
Eric Laurent874c42872014-08-08 15:13:39 -07002400 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2401 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2402 return BAD_VALUE;
2403 }
2404 // only one source per audio patch supported for now
2405 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002406 return INVALID_OPERATION;
2407 }
Eric Laurent874c42872014-08-08 15:13:39 -07002408
2409 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002410 return INVALID_OPERATION;
2411 }
Eric Laurent874c42872014-08-08 15:13:39 -07002412 for (size_t i = 0; i < patch->num_sinks; i++) {
2413 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2414 return INVALID_OPERATION;
2415 }
2416 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002417
2418 sp<AudioPatch> patchDesc;
2419 ssize_t index = mAudioPatches.indexOfKey(*handle);
2420
Eric Laurent6a94d692014-05-20 11:18:06 -07002421 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2422 patch->sources[0].role,
2423 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002424#if LOG_NDEBUG == 0
2425 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002426 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002427 patch->sinks[i].role,
2428 patch->sinks[i].type);
2429 }
2430#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002431
2432 if (index >= 0) {
2433 patchDesc = mAudioPatches.valueAt(index);
2434 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2435 mUidCached, patchDesc->mUid, uid);
2436 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2437 return INVALID_OPERATION;
2438 }
2439 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07002440 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07002441 }
2442
2443 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002444 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002445 if (outputDesc == NULL) {
2446 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2447 return BAD_VALUE;
2448 }
Eric Laurent84c70242014-06-23 08:46:27 -07002449 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2450 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002451 if (patchDesc != 0) {
2452 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2453 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2454 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2455 return BAD_VALUE;
2456 }
2457 }
Eric Laurent874c42872014-08-08 15:13:39 -07002458 DeviceVector devices;
2459 for (size_t i = 0; i < patch->num_sinks; i++) {
2460 // Only support mix to devices connection
2461 // TODO add support for mix to mix connection
2462 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2463 ALOGV("createAudioPatch() source mix but sink is not a device");
2464 return INVALID_OPERATION;
2465 }
2466 sp<DeviceDescriptor> devDesc =
2467 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2468 if (devDesc == 0) {
2469 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2470 return BAD_VALUE;
2471 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002472
François Gaffie53615e22015-03-19 09:24:12 +01002473 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002474 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002475 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002476 NULL, // updatedSamplingRate
2477 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002478 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002479 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002480 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002481 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002482 ALOGV("createAudioPatch() profile not supported for device %08x",
2483 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002484 return INVALID_OPERATION;
2485 }
2486 devices.add(devDesc);
2487 }
2488 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002489 return INVALID_OPERATION;
2490 }
Eric Laurent874c42872014-08-08 15:13:39 -07002491
Eric Laurent6a94d692014-05-20 11:18:06 -07002492 // TODO: reconfigure output format and channels here
2493 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002494 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002495 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002496 index = mAudioPatches.indexOfKey(*handle);
2497 if (index >= 0) {
2498 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2499 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2500 }
2501 patchDesc = mAudioPatches.valueAt(index);
2502 patchDesc->mUid = uid;
2503 ALOGV("createAudioPatch() success");
2504 } else {
2505 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2506 return INVALID_OPERATION;
2507 }
2508 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2509 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2510 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002511 // only one sink supported when connecting an input device to a mix
2512 if (patch->num_sinks > 1) {
2513 return INVALID_OPERATION;
2514 }
François Gaffie53615e22015-03-19 09:24:12 +01002515 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002516 if (inputDesc == NULL) {
2517 return BAD_VALUE;
2518 }
2519 if (patchDesc != 0) {
2520 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2521 return BAD_VALUE;
2522 }
2523 }
2524 sp<DeviceDescriptor> devDesc =
2525 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2526 if (devDesc == 0) {
2527 return BAD_VALUE;
2528 }
2529
François Gaffie53615e22015-03-19 09:24:12 +01002530 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 devDesc->mAddress,
2532 patch->sinks[0].sample_rate,
2533 NULL, /*updatedSampleRate*/
2534 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002535 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002536 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002537 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002538 // FIXME for the parameter type,
2539 // and the NONE
2540 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002541 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002542 return INVALID_OPERATION;
2543 }
2544 // TODO: reconfigure output format and channels here
2545 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002546 devDesc->type(), inputDesc->mIoHandle);
2547 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002548 index = mAudioPatches.indexOfKey(*handle);
2549 if (index >= 0) {
2550 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2551 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2552 }
2553 patchDesc = mAudioPatches.valueAt(index);
2554 patchDesc->mUid = uid;
2555 ALOGV("createAudioPatch() success");
2556 } else {
2557 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2558 return INVALID_OPERATION;
2559 }
2560 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2561 // device to device connection
2562 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002563 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002564 return BAD_VALUE;
2565 }
2566 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002567 sp<DeviceDescriptor> srcDeviceDesc =
2568 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002569 if (srcDeviceDesc == 0) {
2570 return BAD_VALUE;
2571 }
Eric Laurent874c42872014-08-08 15:13:39 -07002572
Eric Laurent6a94d692014-05-20 11:18:06 -07002573 //update source and sink with our own data as the data passed in the patch may
2574 // be incomplete.
2575 struct audio_patch newPatch = *patch;
2576 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002577
Eric Laurent874c42872014-08-08 15:13:39 -07002578 for (size_t i = 0; i < patch->num_sinks; i++) {
2579 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2580 ALOGV("createAudioPatch() source device but one sink is not a device");
2581 return INVALID_OPERATION;
2582 }
2583
2584 sp<DeviceDescriptor> sinkDeviceDesc =
2585 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2586 if (sinkDeviceDesc == 0) {
2587 return BAD_VALUE;
2588 }
2589 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2590
Eric Laurent3bcf8592015-04-03 12:13:24 -07002591 // create a software bridge in PatchPanel if:
2592 // - source and sink devices are on differnt HW modules OR
2593 // - audio HAL version is < 3.0
Eric Laurent232f26f2016-02-17 18:06:27 -08002594 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002595 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002596 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002597 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002598 return INVALID_OPERATION;
2599 }
Eric Laurent874c42872014-08-08 15:13:39 -07002600 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002601 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002602 // if the sink device is reachable via an opened output stream, request to go via
2603 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002604 audio_io_handle_t output = selectOutput(outputs,
2605 AUDIO_OUTPUT_FLAG_NONE,
2606 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002607 if (output != AUDIO_IO_HANDLE_NONE) {
2608 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2609 if (outputDesc->isDuplicated()) {
2610 return INVALID_OPERATION;
2611 }
2612 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002613 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002614 newPatch.num_sources = 2;
2615 }
Eric Laurent83b88082014-06-20 18:31:16 -07002616 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002617 }
2618 // TODO: check from routing capabilities in config file and other conflicting patches
2619
2620 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2621 if (index >= 0) {
2622 afPatchHandle = patchDesc->mAfPatchHandle;
2623 }
2624
2625 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2626 &afPatchHandle,
2627 0);
2628 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2629 status, afPatchHandle);
2630 if (status == NO_ERROR) {
2631 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002632 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002633 addAudioPatch(patchDesc->mHandle, patchDesc);
2634 } else {
2635 patchDesc->mPatch = newPatch;
2636 }
2637 patchDesc->mAfPatchHandle = afPatchHandle;
2638 *handle = patchDesc->mHandle;
2639 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002640 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002641 } else {
2642 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2643 status);
2644 return INVALID_OPERATION;
2645 }
2646 } else {
2647 return BAD_VALUE;
2648 }
2649 } else {
2650 return BAD_VALUE;
2651 }
2652 return NO_ERROR;
2653}
2654
2655status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2656 uid_t uid)
2657{
2658 ALOGV("releaseAudioPatch() patch %d", handle);
2659
2660 ssize_t index = mAudioPatches.indexOfKey(handle);
2661
2662 if (index < 0) {
2663 return BAD_VALUE;
2664 }
2665 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2666 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2667 mUidCached, patchDesc->mUid, uid);
2668 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2669 return INVALID_OPERATION;
2670 }
2671
2672 struct audio_patch *patch = &patchDesc->mPatch;
2673 patchDesc->mUid = mUidCached;
2674 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002676 if (outputDesc == NULL) {
2677 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2678 return BAD_VALUE;
2679 }
2680
Eric Laurentc75307b2015-03-17 15:29:32 -07002681 setOutputDevice(outputDesc,
2682 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002683 true,
2684 0,
2685 NULL);
2686 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2687 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002688 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002689 if (inputDesc == NULL) {
2690 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2691 return BAD_VALUE;
2692 }
2693 setInputDevice(inputDesc->mIoHandle,
Eric Laurent232f26f2016-02-17 18:06:27 -08002694 getNewInputDevice(inputDesc->mIoHandle),
Eric Laurent6a94d692014-05-20 11:18:06 -07002695 true,
2696 NULL);
2697 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2698 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2699 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2700 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2701 status, patchDesc->mAfPatchHandle);
2702 removeAudioPatch(patchDesc->mHandle);
2703 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002704 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002705 } else {
2706 return BAD_VALUE;
2707 }
2708 } else {
2709 return BAD_VALUE;
2710 }
2711 return NO_ERROR;
2712}
2713
2714status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2715 struct audio_patch *patches,
2716 unsigned int *generation)
2717{
François Gaffie53615e22015-03-19 09:24:12 +01002718 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002719 return BAD_VALUE;
2720 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002721 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002722 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002723}
2724
Eric Laurente1715a42014-05-20 11:30:42 -07002725status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002726{
Eric Laurente1715a42014-05-20 11:30:42 -07002727 ALOGV("setAudioPortConfig()");
2728
2729 if (config == NULL) {
2730 return BAD_VALUE;
2731 }
2732 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2733 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002734 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2735 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002736 }
2737
Eric Laurenta121f902014-06-03 13:32:54 -07002738 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002739 if (config->type == AUDIO_PORT_TYPE_MIX) {
2740 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002741 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002742 if (outputDesc == NULL) {
2743 return BAD_VALUE;
2744 }
Eric Laurent84c70242014-06-23 08:46:27 -07002745 ALOG_ASSERT(!outputDesc->isDuplicated(),
2746 "setAudioPortConfig() called on duplicated output %d",
2747 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002748 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002749 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002750 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002751 if (inputDesc == NULL) {
2752 return BAD_VALUE;
2753 }
Eric Laurenta121f902014-06-03 13:32:54 -07002754 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002755 } else {
2756 return BAD_VALUE;
2757 }
2758 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2759 sp<DeviceDescriptor> deviceDesc;
2760 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2761 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2762 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2763 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2764 } else {
2765 return BAD_VALUE;
2766 }
2767 if (deviceDesc == NULL) {
2768 return BAD_VALUE;
2769 }
Eric Laurenta121f902014-06-03 13:32:54 -07002770 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002771 } else {
2772 return BAD_VALUE;
2773 }
2774
Eric Laurenta121f902014-06-03 13:32:54 -07002775 struct audio_port_config backupConfig;
2776 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2777 if (status == NO_ERROR) {
2778 struct audio_port_config newConfig;
2779 audioPortConfig->toAudioPortConfig(&newConfig, config);
2780 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002781 }
Eric Laurenta121f902014-06-03 13:32:54 -07002782 if (status != NO_ERROR) {
2783 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002784 }
Eric Laurente1715a42014-05-20 11:30:42 -07002785
2786 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002787}
2788
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002789void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2790{
Eric Laurentd60560a2015-04-10 11:31:20 -07002791 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002792 clearAudioPatches(uid);
2793 clearSessionRoutes(uid);
2794}
2795
Eric Laurent6a94d692014-05-20 11:18:06 -07002796void AudioPolicyManager::clearAudioPatches(uid_t uid)
2797{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002798 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002799 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2800 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002801 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002802 }
2803 }
2804}
2805
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002806void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2807 audio_io_handle_t ouptutToSkip)
2808{
2809 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2810 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2811 for (size_t j = 0; j < mOutputs.size(); j++) {
2812 if (mOutputs.keyAt(j) == ouptutToSkip) {
2813 continue;
2814 }
2815 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2816 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2817 continue;
2818 }
2819 // If the default device for this strategy is on another output mix,
2820 // invalidate all tracks in this strategy to force re connection.
2821 // Otherwise select new device on the output mix.
2822 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
Eric Laurent794fde22016-03-11 09:50:45 -08002823 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002824 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2825 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2826 }
2827 }
2828 } else {
2829 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2830 setOutputDevice(outputDesc, newDevice, false);
2831 }
2832 }
2833}
2834
2835void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2836{
2837 // remove output routes associated with this uid
2838 SortedVector<routing_strategy> affectedStrategies;
2839 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2840 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2841 if (route->mUid == uid) {
2842 mOutputRoutes.removeItemsAt(i);
2843 if (route->mDeviceDescriptor != 0) {
2844 affectedStrategies.add(getStrategy(route->mStreamType));
2845 }
2846 }
2847 }
2848 // reroute outputs if necessary
2849 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2850 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2851 }
2852
2853 // remove input routes associated with this uid
2854 SortedVector<audio_source_t> affectedSources;
2855 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2856 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2857 if (route->mUid == uid) {
2858 mInputRoutes.removeItemsAt(i);
2859 if (route->mDeviceDescriptor != 0) {
2860 affectedSources.add(route->mSource);
2861 }
2862 }
2863 }
2864 // reroute inputs if necessary
2865 SortedVector<audio_io_handle_t> inputsToClose;
2866 for (size_t i = 0; i < mInputs.size(); i++) {
2867 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002868 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002869 inputsToClose.add(inputDesc->mIoHandle);
2870 }
2871 }
2872 for (size_t i = 0; i < inputsToClose.size(); i++) {
2873 closeInput(inputsToClose[i]);
2874 }
2875}
2876
Eric Laurentd60560a2015-04-10 11:31:20 -07002877void AudioPolicyManager::clearAudioSources(uid_t uid)
2878{
2879 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2880 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2881 if (sourceDesc->mUid == uid) {
2882 stopAudioSource(mAudioSources.keyAt(i));
2883 }
2884 }
2885}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002886
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002887status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2888 audio_io_handle_t *ioHandle,
2889 audio_devices_t *device)
2890{
Glenn Kasteneeecb982016-02-26 10:44:04 -08002891 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
2892 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002893 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002894
François Gaffiedf372692015-03-19 10:43:27 +01002895 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002896}
2897
Eric Laurentd60560a2015-04-10 11:31:20 -07002898status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2899 const audio_attributes_t *attributes,
2900 audio_io_handle_t *handle,
2901 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002902{
Eric Laurentd60560a2015-04-10 11:31:20 -07002903 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2904 if (source == NULL || attributes == NULL || handle == NULL) {
2905 return BAD_VALUE;
2906 }
2907
2908 *handle = AUDIO_IO_HANDLE_NONE;
2909
2910 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2911 source->type != AUDIO_PORT_TYPE_DEVICE) {
2912 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2913 return INVALID_OPERATION;
2914 }
2915
2916 sp<DeviceDescriptor> srcDeviceDesc =
2917 mAvailableInputDevices.getDevice(source->ext.device.type,
2918 String8(source->ext.device.address));
2919 if (srcDeviceDesc == 0) {
2920 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2921 return BAD_VALUE;
2922 }
2923 sp<AudioSourceDescriptor> sourceDesc =
2924 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2925
2926 struct audio_patch dummyPatch;
2927 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2928 sourceDesc->mPatchDesc = patchDesc;
2929
2930 status_t status = connectAudioSource(sourceDesc);
2931 if (status == NO_ERROR) {
2932 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2933 *handle = sourceDesc->getHandle();
2934 }
2935 return status;
2936}
2937
2938status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2939{
2940 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2941
2942 // make sure we only have one patch per source.
2943 disconnectAudioSource(sourceDesc);
2944
2945 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
Eric Laurent28d09f02016-03-08 10:43:05 -08002946 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07002947 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2948
2949 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2950 sp<DeviceDescriptor> sinkDeviceDesc =
2951 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2952
2953 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2954 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2955
2956 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2957 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002958 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002959 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2960 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2961 // create patch between src device and output device
2962 // create Hwoutput and add to mHwOutputs
2963 } else {
2964 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2965 audio_io_handle_t output =
2966 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2967 if (output == AUDIO_IO_HANDLE_NONE) {
2968 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2969 return INVALID_OPERATION;
2970 }
2971 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2972 if (outputDesc->isDuplicated()) {
2973 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2974 return INVALID_OPERATION;
2975 }
2976 // create a special patch with no sink and two sources:
2977 // - the second source indicates to PatchPanel through which output mix this patch should
2978 // be connected as well as the stream type for volume control
2979 // - the sink is defined by whatever output device is currently selected for the output
2980 // though which this patch is routed.
2981 patch->num_sinks = 0;
2982 patch->num_sources = 2;
2983 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2984 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2985 patch->sources[1].ext.mix.usecase.stream = stream;
2986 status_t status = mpClientInterface->createAudioPatch(patch,
2987 &afPatchHandle,
2988 0);
2989 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
2990 status, afPatchHandle);
2991 if (status != NO_ERROR) {
2992 ALOGW("%s patch panel could not connect device patch, error %d",
2993 __FUNCTION__, status);
2994 return INVALID_OPERATION;
2995 }
2996 uint32_t delayMs = 0;
Eric Laurentc40d9692016-04-13 19:14:13 -07002997 status = startSource(outputDesc, stream, sinkDevice, NULL, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07002998
2999 if (status != NO_ERROR) {
3000 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
3001 return status;
3002 }
3003 sourceDesc->mSwOutput = outputDesc;
3004 if (delayMs != 0) {
3005 usleep(delayMs * 1000);
3006 }
3007 }
3008
3009 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
3010 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
3011
3012 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07003013}
3014
Eric Laurent493404d2015-04-21 15:07:36 -07003015status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07003016{
Eric Laurentd60560a2015-04-10 11:31:20 -07003017 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
3018 ALOGV("%s handle %d", __FUNCTION__, handle);
3019 if (sourceDesc == 0) {
3020 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
3021 return BAD_VALUE;
3022 }
3023 status_t status = disconnectAudioSource(sourceDesc);
3024
3025 mAudioSources.removeItem(handle);
3026 return status;
3027}
3028
Andy Hung2ddee192015-12-18 17:34:44 -08003029status_t AudioPolicyManager::setMasterMono(bool mono)
3030{
3031 if (mMasterMono == mono) {
3032 return NO_ERROR;
3033 }
3034 mMasterMono = mono;
3035 // if enabling mono we close all offloaded devices, which will invalidate the
3036 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3037 // for recreating the new AudioTrack as non-offloaded PCM.
3038 //
3039 // If disabling mono, we leave all tracks as is: we don't know which clients
3040 // and tracks are able to be recreated as offloaded. The next "song" should
3041 // play back offloaded.
3042 if (mMasterMono) {
3043 Vector<audio_io_handle_t> offloaded;
3044 for (size_t i = 0; i < mOutputs.size(); ++i) {
3045 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3046 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3047 offloaded.push(desc->mIoHandle);
3048 }
3049 }
3050 for (size_t i = 0; i < offloaded.size(); ++i) {
3051 closeOutput(offloaded[i]);
3052 }
3053 }
3054 // update master mono for all remaining outputs
3055 for (size_t i = 0; i < mOutputs.size(); ++i) {
3056 updateMono(mOutputs.keyAt(i));
3057 }
3058 return NO_ERROR;
3059}
3060
3061status_t AudioPolicyManager::getMasterMono(bool *mono)
3062{
3063 *mono = mMasterMono;
3064 return NO_ERROR;
3065}
3066
Eric Laurentd60560a2015-04-10 11:31:20 -07003067status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
3068{
3069 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
3070
3071 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
3072 if (patchDesc == 0) {
3073 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
3074 sourceDesc->mPatchDesc->mHandle);
3075 return BAD_VALUE;
3076 }
3077 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
3078
Eric Laurent28d09f02016-03-08 10:43:05 -08003079 audio_stream_type_t stream = streamTypefromAttributesInt(&sourceDesc->mAttributes);
Eric Laurentd60560a2015-04-10 11:31:20 -07003080 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
3081 if (swOutputDesc != 0) {
3082 stopSource(swOutputDesc, stream, false);
3083 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3084 } else {
3085 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
3086 if (hwOutputDesc != 0) {
3087 // release patch between src device and output device
3088 // close Hwoutput and remove from mHwOutputs
3089 } else {
3090 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
3091 }
3092 }
3093 return NO_ERROR;
3094}
3095
3096sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
3097 audio_io_handle_t output, routing_strategy strategy)
3098{
3099 sp<AudioSourceDescriptor> source;
3100 for (size_t i = 0; i < mAudioSources.size(); i++) {
3101 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
3102 routing_strategy sourceStrategy =
3103 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
3104 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
3105 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
3106 source = sourceDesc;
3107 break;
3108 }
3109 }
3110 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07003111}
3112
Eric Laurente552edb2014-03-10 17:42:56 -07003113// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003114// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003115// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07003116uint32_t AudioPolicyManager::nextAudioPortGeneration()
3117{
3118 return android_atomic_inc(&mAudioPortGeneration);
3119}
3120
Eric Laurente0720872014-03-11 09:30:41 -07003121AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003122 :
3123#ifdef AUDIO_POLICY_TEST
3124 Thread(false),
3125#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07003126 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003127 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003128 mAudioPortGeneration(1),
3129 mBeaconMuteRefCount(0),
3130 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07003131 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08003132 mTtsOutputAvailable(false),
3133 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003134{
François Gaffied1ab2bd2015-12-02 18:20:06 +01003135 mUidCached = getuid();
3136 mpClientInterface = clientInterface;
3137
3138 // TODO: remove when legacy conf file is removed. true on devices that use DRC on the
3139 // DEVICE_CATEGORY_SPEAKER path to boost soft sounds, used to adjust volume curves accordingly.
3140 // Note: remove also speaker_drc_enabled from global configuration of XML config file.
3141 bool speakerDrcEnabled = false;
3142
3143#ifdef USE_XML_AUDIO_POLICY_CONF
3144 mVolumeCurves = new VolumeCurvesCollection();
3145 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3146 mDefaultOutputDevice, speakerDrcEnabled,
3147 static_cast<VolumeCurvesCollection *>(mVolumeCurves));
3148 PolicySerializer serializer;
3149 if (serializer.deserialize(AUDIO_POLICY_XML_CONFIG_FILE, config) != NO_ERROR) {
3150#else
3151 mVolumeCurves = new StreamDescriptorCollection();
3152 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3153 mDefaultOutputDevice, speakerDrcEnabled);
3154 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3155 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3156#endif
3157 ALOGE("could not load audio policy configuration file, setting defaults");
3158 config.setDefault();
3159 }
3160 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3161 mVolumeCurves->initializeVolumeCurves(speakerDrcEnabled);
3162
3163 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
François Gaffie2110e042015-03-24 08:41:51 +01003164 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
3165 if (!engineInstance) {
3166 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
3167 return;
3168 }
3169 // Retrieve the Policy Manager Interface
3170 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3171 if (mEngine == NULL) {
3172 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3173 return;
3174 }
3175 mEngine->setObserver(this);
3176 status_t status = mEngine->initCheck();
3177 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3178
Eric Laurent3a4311c2014-03-17 12:00:47 -07003179 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003180 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003181 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3182 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003183 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003184 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003185 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003186 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003187 continue;
3188 }
3189 // open all output streams needed to access attached devices
3190 // except for direct output streams that are only opened when they are actually
3191 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003192 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003193 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3194 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003195 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003196
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003197 if (!outProfile->hasSupportedDevices()) {
3198 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003199 continue;
3200 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003201 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003202 mTtsOutputAvailable = true;
3203 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003204
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003205 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003206 continue;
3207 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003208 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003209 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3210 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003211 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003212 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003213 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003214 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003215 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003216 if ((profileType & outputDeviceTypes) == 0) {
3217 continue;
3218 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003219 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3220 mpClientInterface);
Eric Laurentc40d9692016-04-13 19:14:13 -07003221 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3222 const DeviceVector &devicesForType = supportedDevices.getDevicesFromType(profileType);
3223 String8 address = devicesForType.size() > 0 ? devicesForType.itemAt(0)->mAddress
3224 : String8("");
Eric Laurentd78f1532014-09-16 16:38:20 -07003225
3226 outputDesc->mDevice = profileType;
3227 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3228 config.sample_rate = outputDesc->mSamplingRate;
3229 config.channel_mask = outputDesc->mChannelMask;
3230 config.format = outputDesc->mFormat;
3231 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003232 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003233 &output,
3234 &config,
3235 &outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003236 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003237 &outputDesc->mLatency,
3238 outputDesc->mFlags);
3239
3240 if (status != NO_ERROR) {
3241 ALOGW("Cannot open output stream for device %08x on hw module %s",
3242 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003243 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003244 } else {
3245 outputDesc->mSamplingRate = config.sample_rate;
3246 outputDesc->mChannelMask = config.channel_mask;
3247 outputDesc->mFormat = config.format;
3248
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003249 for (size_t k = 0; k < supportedDevices.size(); k++) {
3250 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003251 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003252 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3253 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003254 }
3255 }
3256 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003257 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003258 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003259 }
3260 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003261 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003262 outputDesc->mDevice,
Eric Laurentc40d9692016-04-13 19:14:13 -07003263 true,
3264 0,
3265 NULL,
3266 address.string());
Eric Laurentd78f1532014-09-16 16:38:20 -07003267 }
Eric Laurente552edb2014-03-10 17:42:56 -07003268 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003269 // open input streams needed to access attached devices to validate
3270 // mAvailableInputDevices list
3271 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3272 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003273 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003274
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003275 if (!inProfile->hasSupportedDevices()) {
3276 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003277 continue;
3278 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003279 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003280 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003281 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3282
Eric Laurentd78f1532014-09-16 16:38:20 -07003283 if ((profileType & inputDeviceTypes) == 0) {
3284 continue;
3285 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003286 sp<AudioInputDescriptor> inputDesc =
3287 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003288
Eric Laurentd78f1532014-09-16 16:38:20 -07003289 inputDesc->mDevice = profileType;
3290
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003291 // find the address
3292 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3293 // the inputs vector must be of size 1, but we don't want to crash here
3294 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3295 : String8("");
3296 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3297 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3298
Eric Laurentd78f1532014-09-16 16:38:20 -07003299 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3300 config.sample_rate = inputDesc->mSamplingRate;
3301 config.channel_mask = inputDesc->mChannelMask;
3302 config.format = inputDesc->mFormat;
3303 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003304 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003305 &input,
3306 &config,
3307 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003308 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003309 AUDIO_SOURCE_MIC,
3310 AUDIO_INPUT_FLAG_NONE);
3311
3312 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003313 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3314 for (size_t k = 0; k < supportedDevices.size(); k++) {
3315 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003316 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003317 if (index >= 0) {
3318 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3319 if (!devDesc->isAttached()) {
3320 devDesc->attach(mHwModules[i]);
3321 devDesc->importAudioPort(inProfile);
3322 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003323 }
3324 }
3325 mpClientInterface->closeInput(input);
3326 } else {
3327 ALOGW("Cannot open input stream for device %08x on hw module %s",
3328 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003329 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003330 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003331 }
3332 }
3333 // make sure all attached devices have been allocated a unique ID
3334 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003335 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003336 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003337 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3338 continue;
3339 }
François Gaffie2110e042015-03-24 08:41:51 +01003340 // The device is now validated and can be appended to the available devices of the engine
3341 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3342 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003343 i++;
3344 }
3345 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003346 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003347 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003348 mAvailableInputDevices.remove(mAvailableInputDevices[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(mAvailableInputDevices[i],
3353 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003354 i++;
3355 }
3356 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003357 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003358 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003359 }
Eric Laurente552edb2014-03-10 17:42:56 -07003360
3361 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3362
3363 updateDevicesAndOutputs();
3364
3365#ifdef AUDIO_POLICY_TEST
3366 if (mPrimaryOutput != 0) {
3367 AudioParameter outputCmd = AudioParameter();
3368 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003369 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003370
3371 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3372 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003373 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3374 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003375 mTestLatencyMs = 0;
3376 mCurOutput = 0;
3377 mDirectOutput = false;
3378 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3379 mTestOutputs[i] = 0;
3380 }
3381
3382 const size_t SIZE = 256;
3383 char buffer[SIZE];
3384 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3385 run(buffer, ANDROID_PRIORITY_AUDIO);
3386 }
3387#endif //AUDIO_POLICY_TEST
3388}
3389
Eric Laurente0720872014-03-11 09:30:41 -07003390AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003391{
3392#ifdef AUDIO_POLICY_TEST
3393 exit();
3394#endif //AUDIO_POLICY_TEST
3395 for (size_t i = 0; i < mOutputs.size(); i++) {
3396 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003397 }
3398 for (size_t i = 0; i < mInputs.size(); i++) {
3399 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003400 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003401 mAvailableOutputDevices.clear();
3402 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003403 mOutputs.clear();
3404 mInputs.clear();
3405 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003406}
3407
Eric Laurente0720872014-03-11 09:30:41 -07003408status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003409{
Eric Laurent87ffa392015-05-22 10:32:38 -07003410 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003411}
3412
3413#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003414bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003415{
3416 ALOGV("entering threadLoop()");
3417 while (!exitPending())
3418 {
3419 String8 command;
3420 int valueInt;
3421 String8 value;
3422
3423 Mutex::Autolock _l(mLock);
3424 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3425
3426 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3427 AudioParameter param = AudioParameter(command);
3428
3429 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3430 valueInt != 0) {
3431 ALOGV("Test command %s received", command.string());
3432 String8 target;
3433 if (param.get(String8("target"), target) != NO_ERROR) {
3434 target = "Manager";
3435 }
3436 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3437 param.remove(String8("test_cmd_policy_output"));
3438 mCurOutput = valueInt;
3439 }
3440 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3441 param.remove(String8("test_cmd_policy_direct"));
3442 if (value == "false") {
3443 mDirectOutput = false;
3444 } else if (value == "true") {
3445 mDirectOutput = true;
3446 }
3447 }
3448 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3449 param.remove(String8("test_cmd_policy_input"));
3450 mTestInput = valueInt;
3451 }
3452
3453 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3454 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003455 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003456 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003457 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003458 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003459 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003460 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003461 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003462 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003463 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003464 if (target == "Manager") {
3465 mTestFormat = format;
3466 } else if (mTestOutputs[mCurOutput] != 0) {
3467 AudioParameter outputParam = AudioParameter();
3468 outputParam.addInt(String8("format"), format);
3469 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3470 }
3471 }
3472 }
3473 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3474 param.remove(String8("test_cmd_policy_channels"));
3475 int channels = 0;
3476
3477 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003478 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003479 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003480 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003481 }
3482 if (channels != 0) {
3483 if (target == "Manager") {
3484 mTestChannels = channels;
3485 } else if (mTestOutputs[mCurOutput] != 0) {
3486 AudioParameter outputParam = AudioParameter();
3487 outputParam.addInt(String8("channels"), channels);
3488 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3489 }
3490 }
3491 }
3492 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3493 param.remove(String8("test_cmd_policy_sampleRate"));
3494 if (valueInt >= 0 && valueInt <= 96000) {
3495 int samplingRate = valueInt;
3496 if (target == "Manager") {
3497 mTestSamplingRate = samplingRate;
3498 } else if (mTestOutputs[mCurOutput] != 0) {
3499 AudioParameter outputParam = AudioParameter();
3500 outputParam.addInt(String8("sampling_rate"), samplingRate);
3501 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3502 }
3503 }
3504 }
3505
3506 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3507 param.remove(String8("test_cmd_policy_reopen"));
3508
Eric Laurentc75307b2015-03-17 15:29:32 -07003509 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003510
Eric Laurentc75307b2015-03-17 15:29:32 -07003511 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003512
Eric Laurentc75307b2015-03-17 15:29:32 -07003513 removeOutput(mPrimaryOutput->mIoHandle);
3514 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3515 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003516 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003517 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3518 config.sample_rate = outputDesc->mSamplingRate;
3519 config.channel_mask = outputDesc->mChannelMask;
3520 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003521 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003522 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003523 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003524 &config,
3525 &outputDesc->mDevice,
3526 String8(""),
3527 &outputDesc->mLatency,
3528 outputDesc->mFlags);
3529 if (status != NO_ERROR) {
3530 ALOGE("Failed to reopen hardware output stream, "
3531 "samplingRate: %d, format %d, channels %d",
3532 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003533 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003534 outputDesc->mSamplingRate = config.sample_rate;
3535 outputDesc->mChannelMask = config.channel_mask;
3536 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003537 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003538 AudioParameter outputCmd = AudioParameter();
3539 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003540 mpClientInterface->setParameters(handle, outputCmd.toString());
3541 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003542 }
3543 }
3544
3545
3546 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3547 }
3548 }
3549 return false;
3550}
3551
Eric Laurente0720872014-03-11 09:30:41 -07003552void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003553{
3554 {
3555 AutoMutex _l(mLock);
3556 requestExit();
3557 mWaitWorkCV.signal();
3558 }
3559 requestExitAndWait();
3560}
3561
Eric Laurente0720872014-03-11 09:30:41 -07003562int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003563{
3564 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3565 if (output == mTestOutputs[i]) return i;
3566 }
3567 return 0;
3568}
3569#endif //AUDIO_POLICY_TEST
3570
3571// ---
3572
Eric Laurentc75307b2015-03-17 15:29:32 -07003573void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003574{
François Gaffie98cc1912015-03-18 17:52:40 +01003575 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003576 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003577 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003578 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003579}
3580
François Gaffie53615e22015-03-19 09:24:12 +01003581void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3582{
3583 mOutputs.removeItem(output);
3584}
3585
Eric Laurent1f2f2232014-06-02 12:01:23 -07003586void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003587{
François Gaffie98cc1912015-03-18 17:52:40 +01003588 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003589 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003590 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003591}
Eric Laurente552edb2014-03-10 17:42:56 -07003592
Eric Laurentc75307b2015-03-17 15:29:32 -07003593void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003594 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003595 const String8 address /*in*/,
3596 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003597 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003598 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003599 if (devDesc != 0) {
3600 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3601 desc->mIoHandle, address.string());
3602 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003603 }
3604}
3605
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003606status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003607 audio_policy_dev_state_t state,
3608 SortedVector<audio_io_handle_t>& outputs,
3609 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003610{
François Gaffie53615e22015-03-19 09:24:12 +01003611 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003612 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003613
3614 if (audio_device_is_digital(device)) {
3615 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003616 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003617 }
Eric Laurente552edb2014-03-10 17:42:56 -07003618
Eric Laurent3b73df72014-03-11 09:06:29 -07003619 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003620 // first list already open outputs that can be routed to this device
3621 for (size_t i = 0; i < mOutputs.size(); i++) {
3622 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003623 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003624 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003625 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3626 outputs.add(mOutputs.keyAt(i));
3627 } else {
3628 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003629 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003630 }
Eric Laurente552edb2014-03-10 17:42:56 -07003631 }
3632 }
3633 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003634 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003635 for (size_t i = 0; i < mHwModules.size(); i++)
3636 {
3637 if (mHwModules[i]->mHandle == 0) {
3638 continue;
3639 }
3640 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3641 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003642 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003643 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003644 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003645 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003646 profiles.add(profile);
3647 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3648 }
Eric Laurente552edb2014-03-10 17:42:56 -07003649 }
3650 }
3651 }
3652
Eric Laurent7b279bb2015-12-14 10:18:23 -08003653 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003654
Eric Laurente552edb2014-03-10 17:42:56 -07003655 if (profiles.isEmpty() && outputs.isEmpty()) {
3656 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3657 return BAD_VALUE;
3658 }
3659
3660 // open outputs for matching profiles if needed. Direct outputs are also opened to
3661 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3662 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003663 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003664
3665 // nothing to do if one output is already opened for this profile
3666 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003667 for (j = 0; j < outputs.size(); j++) {
3668 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003669 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003670 // matching profile: save the sample rates, format and channel masks supported
3671 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003672 if (audio_device_is_digital(device)) {
3673 devDesc->importAudioPort(profile);
3674 }
Eric Laurente552edb2014-03-10 17:42:56 -07003675 break;
3676 }
3677 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003678 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003679 continue;
3680 }
3681
Eric Laurent83b88082014-06-20 18:31:16 -07003682 ALOGV("opening output for device %08x with params %s profile %p",
3683 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003684 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003685 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003686 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3687 config.sample_rate = desc->mSamplingRate;
3688 config.channel_mask = desc->mChannelMask;
3689 config.format = desc->mFormat;
3690 config.offload_info.sample_rate = desc->mSamplingRate;
3691 config.offload_info.channel_mask = desc->mChannelMask;
3692 config.offload_info.format = desc->mFormat;
3693 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003694 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003695 &output,
3696 &config,
3697 &desc->mDevice,
3698 address,
3699 &desc->mLatency,
3700 desc->mFlags);
3701 if (status == NO_ERROR) {
3702 desc->mSamplingRate = config.sample_rate;
3703 desc->mChannelMask = config.channel_mask;
3704 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003705
Eric Laurentd4692962014-05-05 18:13:44 -07003706 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003707 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003708 char *param = audio_device_address_to_parameter(device, address);
3709 mpClientInterface->setParameters(output, String8(param));
3710 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003711 }
Phil Burk00eeb322016-03-31 12:41:00 -07003712 updateAudioProfiles(device, output, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003713 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003714 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003715 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003716 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003717 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003718 mpClientInterface->closeOutput(output);
Phil Burk702b1052016-03-02 16:38:26 -08003719 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003720 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003721 config.offload_info.sample_rate = config.sample_rate;
3722 config.offload_info.channel_mask = config.channel_mask;
3723 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003724 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003725 &output,
3726 &config,
3727 &desc->mDevice,
3728 address,
3729 &desc->mLatency,
3730 desc->mFlags);
3731 if (status == NO_ERROR) {
3732 desc->mSamplingRate = config.sample_rate;
3733 desc->mChannelMask = config.channel_mask;
3734 desc->mFormat = config.format;
3735 } else {
3736 output = AUDIO_IO_HANDLE_NONE;
3737 }
Eric Laurentd4692962014-05-05 18:13:44 -07003738 }
3739
Eric Laurentcf2c0212014-07-25 16:20:43 -07003740 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003741 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003742 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003743 sp<AudioPolicyMix> policyMix;
3744 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003745 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3746 address.string());
3747 }
François Gaffie036e1e92015-03-19 10:16:24 +01003748 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003749 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003750
Eric Laurent87ffa392015-05-22 10:32:38 -07003751 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3752 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003753 // no duplicated output for direct outputs and
3754 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003755 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003756
Eric Laurentd4692962014-05-05 18:13:44 -07003757 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003758 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003759
Eric Laurentd4692962014-05-05 18:13:44 -07003760 //TODO: configure audio effect output stage here
3761
3762 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003763 duplicatedOutput =
3764 mpClientInterface->openDuplicateOutput(output,
3765 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003766 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003767 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003768 sp<SwAudioOutputDescriptor> dupOutputDesc =
3769 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3770 dupOutputDesc->mOutput1 = mPrimaryOutput;
3771 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003772 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3773 dupOutputDesc->mFormat = desc->mFormat;
3774 dupOutputDesc->mChannelMask = desc->mChannelMask;
3775 dupOutputDesc->mLatency = desc->mLatency;
3776 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003777 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003778 } else {
3779 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003780 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003781 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003782 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003783 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003784 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003785 }
Eric Laurente552edb2014-03-10 17:42:56 -07003786 }
3787 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003788 } else {
3789 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003790 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003791 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003792 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003793 profiles.removeAt(profile_index);
3794 profile_index--;
3795 } else {
3796 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003797 // Load digital format info only for digital devices
3798 if (audio_device_is_digital(device)) {
3799 devDesc->importAudioPort(profile);
3800 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003801
François Gaffie53615e22015-03-19 09:24:12 +01003802 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003803 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3804 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003805 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003806 NULL/*patch handle*/, address.string());
3807 }
Eric Laurente552edb2014-03-10 17:42:56 -07003808 ALOGV("checkOutputsForDevice(): adding output %d", output);
3809 }
3810 }
3811
3812 if (profiles.isEmpty()) {
3813 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3814 return BAD_VALUE;
3815 }
Eric Laurentd4692962014-05-05 18:13:44 -07003816 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003817 // check if one opened output is not needed any more after disconnecting one device
3818 for (size_t i = 0; i < mOutputs.size(); i++) {
3819 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003820 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003821 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003822 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003823 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003824 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003825 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003826 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3827 mOutputs.keyAt(i));
3828 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003829 }
Eric Laurente552edb2014-03-10 17:42:56 -07003830 }
3831 }
Eric Laurentd4692962014-05-05 18:13:44 -07003832 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003833 for (size_t i = 0; i < mHwModules.size(); i++)
3834 {
3835 if (mHwModules[i]->mHandle == 0) {
3836 continue;
3837 }
3838 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3839 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003840 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003841 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003842 ALOGV("checkOutputsForDevice(): "
3843 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003844 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003845 }
3846 }
3847 }
3848 }
3849 return NO_ERROR;
3850}
3851
Paul McLean9080a4c2015-06-18 08:24:02 -07003852status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003853 audio_policy_dev_state_t state,
3854 SortedVector<audio_io_handle_t>& inputs,
3855 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003856{
Paul McLean9080a4c2015-06-18 08:24:02 -07003857 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003858 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003859
3860 if (audio_device_is_digital(device)) {
3861 // erase all current sample rates, formats and channel masks
Eric Laurent20eb3a42016-01-26 18:39:17 -08003862 devDesc->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07003863 }
3864
Eric Laurentd4692962014-05-05 18:13:44 -07003865 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3866 // first list already open inputs that can be routed to this device
3867 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3868 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003869 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003870 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3871 inputs.add(mInputs.keyAt(input_index));
3872 }
3873 }
3874
3875 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003876 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003877 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3878 {
3879 if (mHwModules[module_idx]->mHandle == 0) {
3880 continue;
3881 }
3882 for (size_t profile_index = 0;
3883 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3884 profile_index++)
3885 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003886 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3887
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003888 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003889 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003890 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003891 profiles.add(profile);
3892 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3893 profile_index, module_idx);
3894 }
Eric Laurentd4692962014-05-05 18:13:44 -07003895 }
3896 }
3897 }
3898
3899 if (profiles.isEmpty() && inputs.isEmpty()) {
3900 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3901 return BAD_VALUE;
3902 }
3903
3904 // open inputs for matching profiles if needed. Direct inputs are also opened to
3905 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3906 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3907
Eric Laurent1c333e22014-05-20 10:48:17 -07003908 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003909 // nothing to do if one input is already opened for this profile
3910 size_t input_index;
3911 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3912 desc = mInputs.valueAt(input_index);
3913 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003914 if (audio_device_is_digital(device)) {
3915 devDesc->importAudioPort(profile);
3916 }
Eric Laurentd4692962014-05-05 18:13:44 -07003917 break;
3918 }
3919 }
3920 if (input_index != mInputs.size()) {
3921 continue;
3922 }
3923
3924 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3925 desc = new AudioInputDescriptor(profile);
3926 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003927 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3928 config.sample_rate = desc->mSamplingRate;
3929 config.channel_mask = desc->mChannelMask;
3930 config.format = desc->mFormat;
3931 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003932 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003933 &input,
3934 &config,
3935 &desc->mDevice,
3936 address,
3937 AUDIO_SOURCE_MIC,
3938 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003939
Eric Laurentcf2c0212014-07-25 16:20:43 -07003940 if (status == NO_ERROR) {
3941 desc->mSamplingRate = config.sample_rate;
3942 desc->mChannelMask = config.channel_mask;
3943 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003944
Eric Laurentd4692962014-05-05 18:13:44 -07003945 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003946 char *param = audio_device_address_to_parameter(device, address);
3947 mpClientInterface->setParameters(input, String8(param));
3948 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003949 }
Phil Burk00eeb322016-03-31 12:41:00 -07003950 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01003951 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003952 ALOGW("checkInputsForDevice() direct input missing param");
3953 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003954 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003955 }
3956
3957 if (input != 0) {
3958 addInput(input, desc);
3959 }
3960 } // endif input != 0
3961
Eric Laurentcf2c0212014-07-25 16:20:43 -07003962 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003963 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003964 profiles.removeAt(profile_index);
3965 profile_index--;
3966 } else {
3967 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003968 if (audio_device_is_digital(device)) {
3969 devDesc->importAudioPort(profile);
3970 }
Eric Laurentd4692962014-05-05 18:13:44 -07003971 ALOGV("checkInputsForDevice(): adding input %d", input);
3972 }
3973 } // end scan profiles
3974
3975 if (profiles.isEmpty()) {
3976 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3977 return BAD_VALUE;
3978 }
3979 } else {
3980 // Disconnect
3981 // check if one opened input is not needed any more after disconnecting one device
3982 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3983 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003984 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003985 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3986 mInputs.keyAt(input_index));
3987 inputs.add(mInputs.keyAt(input_index));
3988 }
3989 }
3990 // Clear any profiles associated with the disconnected device.
3991 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3992 if (mHwModules[module_index]->mHandle == 0) {
3993 continue;
3994 }
3995 for (size_t profile_index = 0;
3996 profile_index < mHwModules[module_index]->mInputProfiles.size();
3997 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003998 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003999 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004000 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07004001 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01004002 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07004003 }
4004 }
4005 }
4006 } // end disconnect
4007
4008 return NO_ERROR;
4009}
4010
4011
Eric Laurente0720872014-03-11 09:30:41 -07004012void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07004013{
4014 ALOGV("closeOutput(%d)", output);
4015
Eric Laurentc75307b2015-03-17 15:29:32 -07004016 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004017 if (outputDesc == NULL) {
4018 ALOGW("closeOutput() unknown output %d", output);
4019 return;
4020 }
François Gaffie036e1e92015-03-19 10:16:24 +01004021 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08004022
Eric Laurente552edb2014-03-10 17:42:56 -07004023 // look for duplicated outputs connected to the output being removed.
4024 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004025 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004026 if (dupOutputDesc->isDuplicated() &&
4027 (dupOutputDesc->mOutput1 == outputDesc ||
4028 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004029 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07004030 if (dupOutputDesc->mOutput1 == outputDesc) {
4031 outputDesc2 = dupOutputDesc->mOutput2;
4032 } else {
4033 outputDesc2 = dupOutputDesc->mOutput1;
4034 }
4035 // As all active tracks on duplicated output will be deleted,
4036 // and as they were also referenced on the other output, the reference
4037 // count for their stream type must be adjusted accordingly on
4038 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004039 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004040 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004041 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004042 }
4043 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4044 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4045
4046 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01004047 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004048 }
4049 }
4050
Eric Laurent05b90f82014-08-27 15:32:29 -07004051 nextAudioPortGeneration();
4052
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004053 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004054 if (index >= 0) {
4055 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4056 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4057 mAudioPatches.removeItemsAt(index);
4058 mpClientInterface->onAudioPatchListUpdate();
4059 }
4060
Eric Laurente552edb2014-03-10 17:42:56 -07004061 AudioParameter param;
4062 param.add(String8("closing"), String8("true"));
4063 mpClientInterface->setParameters(output, param.toString());
4064
4065 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01004066 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004067 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004068}
4069
4070void AudioPolicyManager::closeInput(audio_io_handle_t input)
4071{
4072 ALOGV("closeInput(%d)", input);
4073
4074 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4075 if (inputDesc == NULL) {
4076 ALOGW("closeInput() unknown input %d", input);
4077 return;
4078 }
4079
Eric Laurent6a94d692014-05-20 11:18:06 -07004080 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004081
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004082 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07004083 if (index >= 0) {
4084 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4085 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4086 mAudioPatches.removeItemsAt(index);
4087 mpClientInterface->onAudioPatchListUpdate();
4088 }
4089
4090 mpClientInterface->closeInput(input);
4091 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004092}
4093
Eric Laurentc75307b2015-03-17 15:29:32 -07004094SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
4095 audio_devices_t device,
4096 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004097{
4098 SortedVector<audio_io_handle_t> outputs;
4099
4100 ALOGVV("getOutputsForDevice() device %04x", device);
4101 for (size_t i = 0; i < openOutputs.size(); i++) {
4102 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004103 i, openOutputs.valueAt(i)->isDuplicated(),
4104 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004105 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4106 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4107 outputs.add(openOutputs.keyAt(i));
4108 }
4109 }
4110 return outputs;
4111}
4112
Eric Laurente0720872014-03-11 09:30:41 -07004113bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01004114 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07004115{
4116 if (outputs1.size() != outputs2.size()) {
4117 return false;
4118 }
4119 for (size_t i = 0; i < outputs1.size(); i++) {
4120 if (outputs1[i] != outputs2[i]) {
4121 return false;
4122 }
4123 }
4124 return true;
4125}
4126
Eric Laurente0720872014-03-11 09:30:41 -07004127void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004128{
4129 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4130 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4131 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4132 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4133
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004134 // also take into account external policy-related changes: add all outputs which are
4135 // associated with policies in the "before" and "after" output vectors
4136 ALOGVV("checkOutputForStrategy(): policy related outputs");
4137 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004138 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004139 if (desc != 0 && desc->mPolicyMix != NULL) {
4140 srcOutputs.add(desc->mIoHandle);
4141 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4142 }
4143 }
4144 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004145 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004146 if (desc != 0 && desc->mPolicyMix != NULL) {
4147 dstOutputs.add(desc->mIoHandle);
4148 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4149 }
4150 }
4151
Eric Laurente552edb2014-03-10 17:42:56 -07004152 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4153 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4154 strategy, srcOutputs[0], dstOutputs[0]);
4155 // mute strategy while moving tracks from one output to another
4156 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004157 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004158 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004159 setStrategyMute(strategy, true, desc);
4160 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004161 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004162 sp<AudioSourceDescriptor> source =
4163 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4164 if (source != 0){
4165 connectAudioSource(source);
4166 }
Eric Laurente552edb2014-03-10 17:42:56 -07004167 }
4168
4169 // Move effects associated to this strategy from previous output to new output
4170 if (strategy == STRATEGY_MEDIA) {
4171 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4172 SortedVector<audio_io_handle_t> moved;
4173 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004174 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4175 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4176 effectDesc->mIo != fxOutput) {
4177 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004178 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4179 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004180 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004181 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004182 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004183 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004184 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004185 }
4186 }
4187 }
4188 // Move tracks associated to this strategy from previous output to new output
Eric Laurent794fde22016-03-11 09:50:45 -08004189 for (int i = 0; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004190 if (getStrategy((audio_stream_type_t)i) == strategy) {
4191 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004192 }
4193 }
4194 }
4195}
4196
Eric Laurente0720872014-03-11 09:30:41 -07004197void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004198{
François Gaffie2110e042015-03-24 08:41:51 +01004199 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004200 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004201 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004202 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004203 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004204 checkOutputForStrategy(STRATEGY_SONIFICATION);
4205 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004206 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004207 checkOutputForStrategy(STRATEGY_MEDIA);
4208 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004209 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004210}
4211
Eric Laurente0720872014-03-11 09:30:41 -07004212void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004213{
François Gaffie53615e22015-03-19 09:24:12 +01004214 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004215 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004216 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004217 return;
4218 }
4219
Eric Laurent3a4311c2014-03-17 12:00:47 -07004220 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004221 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4222 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4223 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004224 // suspend A2DP output if:
4225 // (NOT already suspended) &&
4226 // ((SCO device is connected &&
4227 // (forced usage for communication || for record is SCO))) ||
4228 // (phone state is ringing || in call)
4229 //
4230 // restore A2DP output if:
4231 // (Already suspended) &&
4232 // ((SCO device is NOT connected ||
4233 // (forced usage NOT for communication && NOT for record is SCO))) &&
4234 // (phone state is NOT ringing && NOT in call)
4235 //
4236 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004237 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004238 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4239 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4240 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4241 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004242
4243 mpClientInterface->restoreOutput(a2dpOutput);
4244 mA2dpSuspended = false;
4245 }
4246 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004247 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004248 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4249 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4250 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4251 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004252
4253 mpClientInterface->suspendOutput(a2dpOutput);
4254 mA2dpSuspended = true;
4255 }
4256 }
4257}
4258
Eric Laurentc75307b2015-03-17 15:29:32 -07004259audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4260 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004261{
4262 audio_devices_t device = AUDIO_DEVICE_NONE;
4263
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004264 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 if (index >= 0) {
4266 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4267 if (patchDesc->mUid != mUidCached) {
4268 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004269 outputDesc->device(), outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004270 return outputDesc->device();
4271 }
4272 }
4273
Eric Laurente552edb2014-03-10 17:42:56 -07004274 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004275 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004276 // use device for strategy enforced audible
4277 // 2: we are in call or the strategy phone is active on the output:
4278 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004279 // 3: the strategy for enforced audible is active but not enforced on the output:
4280 // use the device for strategy enforced audible
Eric Laurent28d09f02016-03-08 10:43:05 -08004281 // 4: the strategy sonification is active on the output:
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004282 // use device for strategy sonification
Eric Laurent28d09f02016-03-08 10:43:05 -08004283 // 5: the strategy accessibility is active on the output:
4284 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004285 // 6: the strategy "respectful" sonification is active on the output:
4286 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004287 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004288 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004289 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004290 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004291 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004292 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004293 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004294 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004295 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4296 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004297 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004298 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004299 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004300 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004301 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004302 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
Eric Laurent28d09f02016-03-08 10:43:05 -08004303 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4304 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004305 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004306 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004307 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004308 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004309 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004310 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004311 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004312 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004313 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004314 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004315 }
4316
Eric Laurent1c333e22014-05-20 10:48:17 -07004317 ALOGV("getNewOutputDevice() selected device %x", device);
4318 return device;
4319}
4320
Eric Laurent232f26f2016-02-17 18:06:27 -08004321audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
Eric Laurent1c333e22014-05-20 10:48:17 -07004322{
Eric Laurent232f26f2016-02-17 18:06:27 -08004323 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004324
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004325 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004326 if (index >= 0) {
4327 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4328 if (patchDesc->mUid != mUidCached) {
4329 ALOGV("getNewInputDevice() device %08x forced by patch %d",
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004330 inputDesc->mDevice, inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004331 return inputDesc->mDevice;
4332 }
4333 }
4334
Eric Laurent232f26f2016-02-17 18:06:27 -08004335 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004336
Eric Laurente552edb2014-03-10 17:42:56 -07004337 return device;
4338}
4339
Eric Laurent794fde22016-03-11 09:50:45 -08004340bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
4341 audio_stream_type_t stream2) {
4342 return ((stream1 == stream2) ||
4343 ((stream1 == AUDIO_STREAM_ACCESSIBILITY) && (stream2 == AUDIO_STREAM_MUSIC)) ||
4344 ((stream1 == AUDIO_STREAM_MUSIC) && (stream2 == AUDIO_STREAM_ACCESSIBILITY)));
Eric Laurent28d09f02016-03-08 10:43:05 -08004345}
4346
Eric Laurente0720872014-03-11 09:30:41 -07004347uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004348 return (uint32_t)getStrategy(stream);
4349}
4350
Eric Laurente0720872014-03-11 09:30:41 -07004351audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004352 // By checking the range of stream before calling getStrategy, we avoid
4353 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4354 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004355 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004356 return AUDIO_DEVICE_NONE;
4357 }
Eric Laurent28d09f02016-03-08 10:43:05 -08004358 audio_devices_t devices = AUDIO_DEVICE_NONE;
Eric Laurent794fde22016-03-11 09:50:45 -08004359 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
4360 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004361 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07004362 }
Eric Laurent794fde22016-03-11 09:50:45 -08004363 routing_strategy curStrategy = getStrategy((audio_stream_type_t)curStream);
Eric Laurent28d09f02016-03-08 10:43:05 -08004364 audio_devices_t curDevices =
4365 getDeviceForStrategy((routing_strategy)curStrategy, true /*fromCache*/);
4366 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(curDevices, mOutputs);
4367 for (size_t i = 0; i < outputs.size(); i++) {
4368 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent794fde22016-03-11 09:50:45 -08004369 if (outputDesc->isStreamActive((audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08004370 curDevices |= outputDesc->device();
4371 }
4372 }
4373 devices |= curDevices;
Eric Laurente552edb2014-03-10 17:42:56 -07004374 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004375
4376 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4377 and doesn't really need to.*/
4378 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4379 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4380 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4381 }
Eric Laurente552edb2014-03-10 17:42:56 -07004382 return devices;
4383}
4384
François Gaffie2110e042015-03-24 08:41:51 +01004385routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4386{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004387 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004388 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004389}
4390
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004391uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4392 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004393 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4394 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4395 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004396 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4397 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4398 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004399 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004400 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004401}
4402
Eric Laurente0720872014-03-11 09:30:41 -07004403void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004404 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004405 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004406 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4407 updateDevicesAndOutputs();
4408 break;
4409 default:
4410 break;
4411 }
4412}
4413
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004414uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004415
4416 // skip beacon mute management if a dedicated TTS output is available
4417 if (mTtsOutputAvailable) {
4418 return 0;
4419 }
4420
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004421 switch(event) {
4422 case STARTING_OUTPUT:
4423 mBeaconMuteRefCount++;
4424 break;
4425 case STOPPING_OUTPUT:
4426 if (mBeaconMuteRefCount > 0) {
4427 mBeaconMuteRefCount--;
4428 }
4429 break;
4430 case STARTING_BEACON:
4431 mBeaconPlayingRefCount++;
4432 break;
4433 case STOPPING_BEACON:
4434 if (mBeaconPlayingRefCount > 0) {
4435 mBeaconPlayingRefCount--;
4436 }
4437 break;
4438 }
4439
4440 if (mBeaconMuteRefCount > 0) {
4441 // any playback causes beacon to be muted
4442 return setBeaconMute(true);
4443 } else {
4444 // no other playback: unmute when beacon starts playing, mute when it stops
4445 return setBeaconMute(mBeaconPlayingRefCount == 0);
4446 }
4447}
4448
4449uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4450 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4451 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4452 // keep track of muted state to avoid repeating mute/unmute operations
4453 if (mBeaconMuted != mute) {
4454 // mute/unmute AUDIO_STREAM_TTS on all outputs
4455 ALOGV("\t muting %d", mute);
4456 uint32_t maxLatency = 0;
4457 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004458 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004459 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004460 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004461 0 /*delay*/, AUDIO_DEVICE_NONE);
4462 const uint32_t latency = desc->latency() * 2;
4463 if (latency > maxLatency) {
4464 maxLatency = latency;
4465 }
4466 }
4467 mBeaconMuted = mute;
4468 return maxLatency;
4469 }
4470 return 0;
4471}
4472
Eric Laurente0720872014-03-11 09:30:41 -07004473audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004474 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004475{
Paul McLeanaa981192015-03-21 09:55:15 -07004476 // Routing
4477 // see if we have an explicit route
4478 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4479 // (getStrategy(stream)).
4480 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4481 // and activity count is non-zero
4482 // the device = the device from the descriptor in the RouteMap, and exit.
4483 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4484 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
Eric Laurent28d09f02016-03-08 10:43:05 -08004485 routing_strategy routeStrategy = getStrategy(route->mStreamType);
4486 if ((routeStrategy == strategy) && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004487 return route->mDeviceDescriptor->type();
4488 }
4489 }
4490
Eric Laurente552edb2014-03-10 17:42:56 -07004491 if (fromCache) {
4492 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4493 strategy, mDeviceForStrategy[strategy]);
4494 return mDeviceForStrategy[strategy];
4495 }
François Gaffie2110e042015-03-24 08:41:51 +01004496 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004497}
4498
Eric Laurente0720872014-03-11 09:30:41 -07004499void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004500{
4501 for (int i = 0; i < NUM_STRATEGIES; i++) {
4502 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4503 }
4504 mPreviousOutputs = mOutputs;
4505}
4506
Eric Laurent1f2f2232014-06-02 12:01:23 -07004507uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004508 audio_devices_t prevDevice,
4509 uint32_t delayMs)
4510{
4511 // mute/unmute strategies using an incompatible device combination
4512 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4513 // if unmuting, unmute only after the specified delay
4514 if (outputDesc->isDuplicated()) {
4515 return 0;
4516 }
4517
4518 uint32_t muteWaitMs = 0;
4519 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004520 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004521
4522 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4523 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004524 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004525 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4526 bool doMute = false;
4527
4528 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4529 doMute = true;
4530 outputDesc->mStrategyMutedByDevice[i] = true;
4531 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4532 doMute = true;
4533 outputDesc->mStrategyMutedByDevice[i] = false;
4534 }
Eric Laurent99401132014-05-07 19:48:15 -07004535 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004536 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004537 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004538 // skip output if it does not share any device with current output
4539 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4540 == AUDIO_DEVICE_NONE) {
4541 continue;
4542 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004543 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4544 mute ? "muting" : "unmuting", i, curDevice);
4545 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004546 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004547 if (mute) {
4548 // FIXME: should not need to double latency if volume could be applied
4549 // immediately by the audioflinger mixer. We must account for the delay
4550 // between now and the next time the audioflinger thread for this output
4551 // will process a buffer (which corresponds to one buffer size,
4552 // usually 1/2 or 1/4 of the latency).
4553 if (muteWaitMs < desc->latency() * 2) {
4554 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004555 }
4556 }
4557 }
4558 }
4559 }
4560 }
4561
Eric Laurent99401132014-05-07 19:48:15 -07004562 // temporary mute output if device selection changes to avoid volume bursts due to
4563 // different per device volumes
4564 if (outputDesc->isActive() && (device != prevDevice)) {
4565 if (muteWaitMs < outputDesc->latency() * 2) {
4566 muteWaitMs = outputDesc->latency() * 2;
4567 }
4568 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004569 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004570 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004571 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004572 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004573 muteWaitMs *2, device);
4574 }
4575 }
4576 }
4577
Eric Laurente552edb2014-03-10 17:42:56 -07004578 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4579 if (muteWaitMs > delayMs) {
4580 muteWaitMs -= delayMs;
4581 usleep(muteWaitMs * 1000);
4582 return muteWaitMs;
4583 }
4584 return 0;
4585}
4586
Eric Laurentc75307b2015-03-17 15:29:32 -07004587uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004588 audio_devices_t device,
4589 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004590 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004591 audio_patch_handle_t *patchHandle,
4592 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004593{
Eric Laurentc75307b2015-03-17 15:29:32 -07004594 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004595 AudioParameter param;
4596 uint32_t muteWaitMs;
4597
4598 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004599 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4600 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004601 return muteWaitMs;
4602 }
4603 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4604 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004605 if ((device != AUDIO_DEVICE_NONE) &&
4606 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004607 return 0;
4608 }
4609
4610 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004611 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004612
4613 audio_devices_t prevDevice = outputDesc->mDevice;
4614
Paul McLeanaa981192015-03-21 09:55:15 -07004615 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004616
4617 if (device != AUDIO_DEVICE_NONE) {
4618 outputDesc->mDevice = device;
4619 }
4620 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4621
4622 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004623 // the requested device is AUDIO_DEVICE_NONE
4624 // OR the requested device is the same as current device
4625 // AND force is not specified
4626 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004627 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004628 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4629 !force &&
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004630 outputDesc->getPatchHandle() != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004631 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004632 return muteWaitMs;
4633 }
4634
4635 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004636
Eric Laurente552edb2014-03-10 17:42:56 -07004637 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004638 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004639 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004640 } else {
Eric Laurentc40d9692016-04-13 19:14:13 -07004641 DeviceVector deviceList;
4642 if ((address == NULL) || (strlen(address) == 0)) {
4643 deviceList = mAvailableOutputDevices.getDevicesFromType(device);
4644 } else {
4645 deviceList = mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
4646 }
4647
Eric Laurent1c333e22014-05-20 10:48:17 -07004648 if (!deviceList.isEmpty()) {
4649 struct audio_patch patch;
4650 outputDesc->toAudioPortConfig(&patch.sources[0]);
4651 patch.num_sources = 1;
4652 patch.num_sinks = 0;
4653 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4654 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004655 patch.num_sinks++;
4656 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004657 ssize_t index;
4658 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4659 index = mAudioPatches.indexOfKey(*patchHandle);
4660 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004661 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004662 }
4663 sp< AudioPatch> patchDesc;
4664 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4665 if (index >= 0) {
4666 patchDesc = mAudioPatches.valueAt(index);
4667 afPatchHandle = patchDesc->mAfPatchHandle;
4668 }
4669
Eric Laurent1c333e22014-05-20 10:48:17 -07004670 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 &afPatchHandle,
4672 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004673 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4674 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004675 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004676 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004677 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004678 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 addAudioPatch(patchDesc->mHandle, patchDesc);
4680 } else {
4681 patchDesc->mPatch = patch;
4682 }
4683 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004684 if (patchHandle) {
4685 *patchHandle = patchDesc->mHandle;
4686 }
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004687 outputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004689 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004690 }
4691 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004692
4693 // inform all input as well
4694 for (size_t i = 0; i < mInputs.size(); i++) {
4695 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004696 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004697 AudioParameter inputCmd = AudioParameter();
4698 ALOGV("%s: inform input %d of device:%d", __func__,
4699 inputDescriptor->mIoHandle, device);
4700 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4701 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4702 inputCmd.toString(),
4703 delayMs);
4704 }
4705 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004706 }
Eric Laurente552edb2014-03-10 17:42:56 -07004707
4708 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004709 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004710
4711 return muteWaitMs;
4712}
4713
Eric Laurentc75307b2015-03-17 15:29:32 -07004714status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004715 int delayMs,
4716 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004717{
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 ssize_t index;
4719 if (patchHandle) {
4720 index = mAudioPatches.indexOfKey(*patchHandle);
4721 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08004722 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 }
4724 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004725 return INVALID_OPERATION;
4726 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004727 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4728 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004729 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004730 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 removeAudioPatch(patchDesc->mHandle);
4732 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004733 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004734 return status;
4735}
4736
4737status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4738 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 bool force,
4740 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004741{
4742 status_t status = NO_ERROR;
4743
Eric Laurent1f2f2232014-06-02 12:01:23 -07004744 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004745 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4746 inputDesc->mDevice = device;
4747
4748 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4749 if (!deviceList.isEmpty()) {
4750 struct audio_patch patch;
4751 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004752 // AUDIO_SOURCE_HOTWORD is for internal use only:
4753 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004754 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004755 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004756 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4757 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004758 patch.num_sinks = 1;
4759 //only one input device for now
4760 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004761 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 ssize_t index;
4763 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4764 index = mAudioPatches.indexOfKey(*patchHandle);
4765 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004766 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 }
4768 sp< AudioPatch> patchDesc;
4769 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4770 if (index >= 0) {
4771 patchDesc = mAudioPatches.valueAt(index);
4772 afPatchHandle = patchDesc->mAfPatchHandle;
4773 }
4774
Eric Laurent1c333e22014-05-20 10:48:17 -07004775 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004777 0);
4778 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004779 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004780 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004782 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 addAudioPatch(patchDesc->mHandle, patchDesc);
4784 } else {
4785 patchDesc->mPatch = patch;
4786 }
4787 patchDesc->mAfPatchHandle = afPatchHandle;
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 if (patchHandle) {
4789 *patchHandle = patchDesc->mHandle;
4790 }
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004791 inputDesc->setPatchHandle(patchDesc->mHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004793 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004794 }
4795 }
4796 }
4797 return status;
4798}
4799
Eric Laurent6a94d692014-05-20 11:18:06 -07004800status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4801 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004802{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004803 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 ssize_t index;
4805 if (patchHandle) {
4806 index = mAudioPatches.indexOfKey(*patchHandle);
4807 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08004808 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004809 }
4810 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004811 return INVALID_OPERATION;
4812 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004813 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4814 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004815 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07004816 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 removeAudioPatch(patchDesc->mHandle);
4818 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004819 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004820 return status;
4821}
4822
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004823sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004824 String8 address,
4825 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004826 audio_format_t& format,
4827 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004828 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004829{
4830 // Choose an input profile based on the requested capture parameters: select the first available
4831 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004832 //
4833 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4834 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004835
4836 for (size_t i = 0; i < mHwModules.size(); i++)
4837 {
4838 if (mHwModules[i]->mHandle == 0) {
4839 continue;
4840 }
4841 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4842 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004843 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004844 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004845 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004846 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004847 format,
4848 &format /*updatedFormat*/,
4849 channelMask,
4850 &channelMask /*updatedChannelMask*/,
4851 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004852
Eric Laurente552edb2014-03-10 17:42:56 -07004853 return profile;
4854 }
4855 }
4856 }
4857 return NULL;
4858}
4859
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004860
4861audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004862 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004863{
François Gaffie036e1e92015-03-19 10:16:24 +01004864 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4865 audio_devices_t selectedDeviceFromMix =
4866 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004867
François Gaffie036e1e92015-03-19 10:16:24 +01004868 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4869 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004870 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004871 return getDeviceForInputSource(inputSource);
4872}
4873
4874audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4875{
Paul McLean466dc8e2015-04-17 13:15:36 -06004876 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4877 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004878 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004879 return route->mDeviceDescriptor->type();
4880 }
4881 }
4882
4883 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004884}
4885
Eric Laurente0720872014-03-11 09:30:41 -07004886float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004887 int index,
4888 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004889{
François Gaffied1ab2bd2015-12-02 18:20:06 +01004890 float volumeDb = mVolumeCurves->volIndexToDb(stream, Volume::getDeviceCategory(device), index);
Eric Laurente552edb2014-03-10 17:42:56 -07004891 // if a headset is connected, apply the following rules to ring tones and notifications
4892 // to avoid sound level bursts in user's ears:
4893 // - always attenuate ring tones and notifications volume by 6dB
4894 // - if music is playing, always limit the volume to current music volume,
4895 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004896 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004897 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4898 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4899 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4900 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4901 ((stream_strategy == STRATEGY_SONIFICATION)
4902 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004903 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004904 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004905 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
François Gaffied1ab2bd2015-12-02 18:20:06 +01004906 mVolumeCurves->canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004907 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004908 // when the phone is ringing we must consider that music could have been paused just before
4909 // by the music application and behave as if music was active if the last music track was
4910 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004911 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004912 mLimitRingtoneVolume) {
4913 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004914 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004915 mVolumeCurves->getVolumeIndex(AUDIO_STREAM_MUSIC,
4916 musicDevice),
4917 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004918 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4919 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4920 if (volumeDb > minVolDB) {
4921 volumeDb = minVolDB;
4922 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004923 }
4924 }
4925 }
4926
Eric Laurentffbc80f2015-03-18 18:30:19 -07004927 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004928}
4929
Eric Laurente0720872014-03-11 09:30:41 -07004930status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004931 int index,
4932 const sp<AudioOutputDescriptor>& outputDesc,
4933 audio_devices_t device,
4934 int delayMs,
4935 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004936{
Eric Laurente552edb2014-03-10 17:42:56 -07004937 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004938 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004939 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004940 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004941 return NO_ERROR;
4942 }
François Gaffie2110e042015-03-24 08:41:51 +01004943 audio_policy_forced_cfg_t forceUseForComm =
4944 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004945 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004946 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4947 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004948 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004949 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004950 return INVALID_OPERATION;
4951 }
4952
Eric Laurentc75307b2015-03-17 15:29:32 -07004953 if (device == AUDIO_DEVICE_NONE) {
4954 device = outputDesc->device();
4955 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004956
Eric Laurentffbc80f2015-03-18 18:30:19 -07004957 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004958 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004959 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004960 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004961
Eric Laurentffbc80f2015-03-18 18:30:19 -07004962 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004963
Eric Laurent3b73df72014-03-11 09:06:29 -07004964 if (stream == AUDIO_STREAM_VOICE_CALL ||
4965 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004966 float voiceVolume;
4967 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004968 if (stream == AUDIO_STREAM_VOICE_CALL) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01004969 voiceVolume = (float)index/(float)mVolumeCurves->getVolumeIndexMax(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004970 } else {
4971 voiceVolume = 1.0;
4972 }
4973
Eric Laurent18fba842016-03-31 14:41:26 -07004974 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07004975 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4976 mLastVoiceVolume = voiceVolume;
4977 }
4978 }
4979
4980 return NO_ERROR;
4981}
4982
Eric Laurentc75307b2015-03-17 15:29:32 -07004983void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4984 audio_devices_t device,
4985 int delayMs,
4986 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004987{
Eric Laurentc75307b2015-03-17 15:29:32 -07004988 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004989
Eric Laurent794fde22016-03-11 09:50:45 -08004990 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004991 checkAndSetVolume((audio_stream_type_t)stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01004992 mVolumeCurves->getVolumeIndex((audio_stream_type_t)stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004993 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004994 device,
4995 delayMs,
4996 force);
4997 }
4998}
4999
Eric Laurente0720872014-03-11 09:30:41 -07005000void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07005001 bool on,
5002 const sp<AudioOutputDescriptor>& outputDesc,
5003 int delayMs,
5004 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005005{
Eric Laurent72249d52015-06-08 11:12:15 -07005006 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
5007 strategy, on, outputDesc->getId());
Eric Laurent794fde22016-03-11 09:50:45 -08005008 for (int stream = 0; stream < AUDIO_STREAM_FOR_POLICY_CNT; stream++) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005009 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005010 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005011 }
5012 }
5013}
5014
Eric Laurente0720872014-03-11 09:30:41 -07005015void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07005016 bool on,
5017 const sp<AudioOutputDescriptor>& outputDesc,
5018 int delayMs,
5019 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005020{
Eric Laurente552edb2014-03-10 17:42:56 -07005021 if (device == AUDIO_DEVICE_NONE) {
5022 device = outputDesc->device();
5023 }
5024
Eric Laurentc75307b2015-03-17 15:29:32 -07005025 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
5026 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07005027
5028 if (on) {
5029 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005030 if (mVolumeCurves->canBeMuted(stream) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005031 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01005032 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005033 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005034 }
5035 }
5036 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5037 outputDesc->mMuteCount[stream]++;
5038 } else {
5039 if (outputDesc->mMuteCount[stream] == 0) {
5040 ALOGV("setStreamMute() unmuting non muted stream!");
5041 return;
5042 }
5043 if (--outputDesc->mMuteCount[stream] == 0) {
5044 checkAndSetVolume(stream,
François Gaffied1ab2bd2015-12-02 18:20:06 +01005045 mVolumeCurves->getVolumeIndex(stream, device),
Eric Laurentc75307b2015-03-17 15:29:32 -07005046 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005047 device,
5048 delayMs);
5049 }
5050 }
5051}
5052
Eric Laurente0720872014-03-11 09:30:41 -07005053void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005054 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005055{
Eric Laurent87ffa392015-05-22 10:32:38 -07005056 if(!hasPrimaryOutput()) {
5057 return;
5058 }
5059
Eric Laurente552edb2014-03-10 17:42:56 -07005060 // if the stream pertains to sonification strategy and we are in call we must
5061 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5062 // in the device used for phone strategy and play the tone if the selected device does not
5063 // interfere with the device used for phone strategy
5064 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5065 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005066 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005067 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5068 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005069 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07005070 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5071 stream, starting, outputDesc->mDevice, stateChange);
5072 if (outputDesc->mRefCount[stream]) {
5073 int muteCount = 1;
5074 if (stateChange) {
5075 muteCount = outputDesc->mRefCount[stream];
5076 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005077 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005078 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5079 for (int i = 0; i < muteCount; i++) {
5080 setStreamMute(stream, starting, mPrimaryOutput);
5081 }
5082 } else {
5083 ALOGV("handleIncallSonification() high visibility");
5084 if (outputDesc->device() &
5085 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5086 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5087 for (int i = 0; i < muteCount; i++) {
5088 setStreamMute(stream, starting, mPrimaryOutput);
5089 }
5090 }
5091 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005092 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5093 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005094 } else {
5095 mpClientInterface->stopTone();
5096 }
5097 }
5098 }
5099 }
5100}
5101
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005102audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5103{
5104 // flags to stream type mapping
5105 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
5106 return AUDIO_STREAM_ENFORCED_AUDIBLE;
5107 }
5108 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
5109 return AUDIO_STREAM_BLUETOOTH_SCO;
5110 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08005111 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
5112 return AUDIO_STREAM_TTS;
5113 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005114
5115 // usage to stream type mapping
5116 switch (attr->usage) {
5117 case AUDIO_USAGE_MEDIA:
5118 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005119 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5120 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005121 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5122 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005123 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5124 return AUDIO_STREAM_SYSTEM;
5125 case AUDIO_USAGE_VOICE_COMMUNICATION:
5126 return AUDIO_STREAM_VOICE_CALL;
5127
5128 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5129 return AUDIO_STREAM_DTMF;
5130
5131 case AUDIO_USAGE_ALARM:
5132 return AUDIO_STREAM_ALARM;
5133 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5134 return AUDIO_STREAM_RING;
5135
5136 case AUDIO_USAGE_NOTIFICATION:
5137 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5138 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5139 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5140 case AUDIO_USAGE_NOTIFICATION_EVENT:
5141 return AUDIO_STREAM_NOTIFICATION;
5142
5143 case AUDIO_USAGE_UNKNOWN:
5144 default:
5145 return AUDIO_STREAM_MUSIC;
5146 }
5147}
Eric Laurente83b55d2014-11-14 10:06:21 -08005148
François Gaffie53615e22015-03-19 09:24:12 +01005149bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5150{
Eric Laurente83b55d2014-11-14 10:06:21 -08005151 // has flags that map to a strategy?
5152 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5153 return true;
5154 }
5155
5156 // has known usage?
5157 switch (paa->usage) {
5158 case AUDIO_USAGE_UNKNOWN:
5159 case AUDIO_USAGE_MEDIA:
5160 case AUDIO_USAGE_VOICE_COMMUNICATION:
5161 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5162 case AUDIO_USAGE_ALARM:
5163 case AUDIO_USAGE_NOTIFICATION:
5164 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5165 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5166 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5167 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5168 case AUDIO_USAGE_NOTIFICATION_EVENT:
5169 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5170 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5171 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5172 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005173 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005174 break;
5175 default:
5176 return false;
5177 }
5178 return true;
5179}
5180
François Gaffiead3183e2015-03-18 16:55:35 +01005181bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5182 routing_strategy strategy, uint32_t inPastMs,
5183 nsecs_t sysTime) const
5184{
5185 if ((sysTime == 0) && (inPastMs != 0)) {
5186 sysTime = systemTime();
5187 }
Eric Laurent794fde22016-03-11 09:50:45 -08005188 for (int i = 0; i < (int)AUDIO_STREAM_FOR_POLICY_CNT; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01005189 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5190 (NUM_STRATEGIES == strategy)) &&
5191 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5192 return true;
5193 }
5194 }
5195 return false;
5196}
5197
François Gaffie2110e042015-03-24 08:41:51 +01005198audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5199{
5200 return mEngine->getForceUse(usage);
5201}
5202
5203bool AudioPolicyManager::isInCall()
5204{
5205 return isStateInCall(mEngine->getPhoneState());
5206}
5207
5208bool AudioPolicyManager::isStateInCall(int state)
5209{
5210 return is_state_in_call(state);
5211}
5212
Eric Laurentd60560a2015-04-10 11:31:20 -07005213void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5214{
5215 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5216 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5217 if (sourceDesc->mDevice->equals(deviceDesc)) {
5218 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5219 stopAudioSource(sourceDesc->getHandle());
5220 }
5221 }
5222
5223 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5224 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5225 bool release = false;
5226 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5227 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5228 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5229 source->ext.device.type == deviceDesc->type()) {
5230 release = true;
5231 }
5232 }
5233 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5234 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5235 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5236 sink->ext.device.type == deviceDesc->type()) {
5237 release = true;
5238 }
5239 }
5240 if (release) {
5241 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5242 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5243 }
5244 }
5245}
5246
Phil Burk09bc4612016-02-24 15:58:15 -08005247// Modify the list of surround sound formats supported.
Phil Burk0709b0a2016-03-31 12:54:57 -07005248void AudioPolicyManager::filterSurroundFormats(FormatVector *formatsPtr) {
5249 FormatVector &formats = *formatsPtr;
Phil Burk07ac1142016-03-25 13:39:29 -07005250 // TODO Set this based on Config properties.
5251 const bool alwaysForceAC3 = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005252
5253 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5254 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07005255 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Phil Burk09bc4612016-02-24 15:58:15 -08005256
5257 // Analyze original support for various formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005258 bool supportsAC3 = false;
5259 bool supportsOtherSurround = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005260 bool supportsIEC61937 = false;
5261 for (size_t formatIndex = 0; formatIndex < formats.size(); formatIndex++) {
5262 audio_format_t format = formats[formatIndex];
Phil Burk09bc4612016-02-24 15:58:15 -08005263 switch (format) {
5264 case AUDIO_FORMAT_AC3:
Phil Burk07ac1142016-03-25 13:39:29 -07005265 supportsAC3 = true;
5266 break;
Phil Burk09bc4612016-02-24 15:58:15 -08005267 case AUDIO_FORMAT_E_AC3:
5268 case AUDIO_FORMAT_DTS:
5269 case AUDIO_FORMAT_DTS_HD:
Phil Burk07ac1142016-03-25 13:39:29 -07005270 supportsOtherSurround = true;
Phil Burk09bc4612016-02-24 15:58:15 -08005271 break;
5272 case AUDIO_FORMAT_IEC61937:
5273 supportsIEC61937 = true;
5274 break;
5275 default:
5276 break;
5277 }
5278 }
Phil Burk09bc4612016-02-24 15:58:15 -08005279
5280 // Modify formats based on surround preferences.
5281 // If NEVER, remove support for surround formats.
Phil Burk07ac1142016-03-25 13:39:29 -07005282 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5283 if (supportsAC3 || supportsOtherSurround || supportsIEC61937) {
5284 // Remove surround sound related formats.
5285 for (size_t formatIndex = 0; formatIndex < formats.size(); ) {
5286 audio_format_t format = formats[formatIndex];
5287 switch(format) {
5288 case AUDIO_FORMAT_AC3:
5289 case AUDIO_FORMAT_E_AC3:
5290 case AUDIO_FORMAT_DTS:
5291 case AUDIO_FORMAT_DTS_HD:
5292 case AUDIO_FORMAT_IEC61937:
Phil Burk07ac1142016-03-25 13:39:29 -07005293 formats.removeAt(formatIndex);
5294 break;
5295 default:
5296 formatIndex++; // keep it
5297 break;
5298 }
Phil Burk09bc4612016-02-24 15:58:15 -08005299 }
Phil Burk07ac1142016-03-25 13:39:29 -07005300 supportsAC3 = false;
5301 supportsOtherSurround = false;
5302 supportsIEC61937 = false;
Phil Burk09bc4612016-02-24 15:58:15 -08005303 }
Phil Burk07ac1142016-03-25 13:39:29 -07005304 } else { // AUTO or ALWAYS
5305 // Most TVs support AC3 even if they do not report it in the EDID.
5306 if ((alwaysForceAC3 || (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS))
5307 && !supportsAC3) {
5308 formats.add(AUDIO_FORMAT_AC3);
5309 supportsAC3 = true;
5310 }
5311
5312 // If ALWAYS, add support for raw surround formats if all are missing.
5313 // This assumes that if any of these formats are reported by the HAL
5314 // then the report is valid and should not be modified.
5315 if ((forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS)
5316 && !supportsOtherSurround) {
5317 formats.add(AUDIO_FORMAT_E_AC3);
5318 formats.add(AUDIO_FORMAT_DTS);
5319 formats.add(AUDIO_FORMAT_DTS_HD);
5320 supportsOtherSurround = true;
5321 }
5322
5323 // Add support for IEC61937 if any raw surround supported.
5324 // The HAL could do this but add it here, just in case.
5325 if ((supportsAC3 || supportsOtherSurround) && !supportsIEC61937) {
5326 formats.add(AUDIO_FORMAT_IEC61937);
5327 supportsIEC61937 = true;
5328 }
Phil Burk09bc4612016-02-24 15:58:15 -08005329 }
Phil Burk0709b0a2016-03-31 12:54:57 -07005330}
5331
5332// Modify the list of channel masks supported.
5333void AudioPolicyManager::filterSurroundChannelMasks(ChannelsVector *channelMasksPtr) {
5334 ChannelsVector &channelMasks = *channelMasksPtr;
5335 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5336 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5337
5338 // If NEVER, then remove support for channelMasks > stereo.
5339 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
5340 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
5341 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5342 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
5343 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
5344 channelMasks.removeAt(maskIndex);
5345 } else {
5346 maskIndex++;
5347 }
5348 }
5349 // If ALWAYS, then make sure we at least support 5.1
5350 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
5351 bool supports5dot1 = false;
5352 // Are there any channel masks that can be considered "surround"?
5353 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); maskIndex++) {
5354 audio_channel_mask_t channelMask = channelMasks[maskIndex];
5355 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
5356 supports5dot1 = true;
5357 break;
5358 }
5359 }
5360 // If not then add 5.1 support.
5361 if (!supports5dot1) {
5362 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
5363 ALOGI("%s: force ALWAYS, so adding channelMask for 5.1 surround", __FUNCTION__);
5364 }
Phil Burk09bc4612016-02-24 15:58:15 -08005365 }
5366}
5367
Phil Burk00eeb322016-03-31 12:41:00 -07005368void AudioPolicyManager::updateAudioProfiles(audio_devices_t device,
5369 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01005370 AudioProfileVector &profiles)
5371{
5372 String8 reply;
5373 char *value;
Phil Burk0709b0a2016-03-31 12:54:57 -07005374
François Gaffie112b0af2015-11-19 16:13:25 +01005375 // Format MUST be checked first to update the list of AudioProfile
5376 if (profiles.hasDynamicFormat()) {
5377 reply = mpClientInterface->getParameters(ioHandle,
5378 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Phil Burk0709b0a2016-03-31 12:54:57 -07005379 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005380 AudioParameter repliedParameters(reply);
5381 if (repliedParameters.get(
5382 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01005383 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5384 return;
5385 }
Phil Burk09bc4612016-02-24 15:58:15 -08005386 FormatVector formats = formatsFromString(reply.string());
Phil Burk00eeb322016-03-31 12:41:00 -07005387 if (device == AUDIO_DEVICE_OUT_HDMI) {
Phil Burk0709b0a2016-03-31 12:54:57 -07005388 filterSurroundFormats(&formats);
Phil Burk00eeb322016-03-31 12:41:00 -07005389 }
Phil Burk09bc4612016-02-24 15:58:15 -08005390 profiles.setFormats(formats);
François Gaffie112b0af2015-11-19 16:13:25 +01005391 }
5392 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5393
Eric Laurent20eb3a42016-01-26 18:39:17 -08005394 for (size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
François Gaffie112b0af2015-11-19 16:13:25 +01005395 audio_format_t format = supportedFormats[formatIndex];
Eric Laurent20eb3a42016-01-26 18:39:17 -08005396 ChannelsVector channelMasks;
5397 SampleRateVector samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01005398 AudioParameter requestedParameters;
5399 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5400
5401 if (profiles.hasDynamicRateFor(format)) {
5402 reply = mpClientInterface->getParameters(ioHandle,
5403 requestedParameters.toString() + ";" +
5404 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5405 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005406 AudioParameter repliedParameters(reply);
5407 if (repliedParameters.get(
5408 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES), reply) == NO_ERROR) {
5409 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01005410 }
5411 }
5412 if (profiles.hasDynamicChannelsFor(format)) {
5413 reply = mpClientInterface->getParameters(ioHandle,
5414 requestedParameters.toString() + ";" +
5415 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5416 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08005417 AudioParameter repliedParameters(reply);
5418 if (repliedParameters.get(
5419 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS), reply) == NO_ERROR) {
5420 channelMasks = channelMasksFromString(reply.string());
Phil Burk0709b0a2016-03-31 12:54:57 -07005421 if (device == AUDIO_DEVICE_OUT_HDMI) {
5422 filterSurroundChannelMasks(&channelMasks);
5423 }
François Gaffie112b0af2015-11-19 16:13:25 +01005424 }
5425 }
Eric Laurent20eb3a42016-01-26 18:39:17 -08005426 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01005427 }
5428}
Eric Laurentd60560a2015-04-10 11:31:20 -07005429
Eric Laurente552edb2014-03-10 17:42:56 -07005430}; // namespace android