blob: 04af88d041326c2c7658c2ed76db054b4708d30d [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 Trivi56ec4ff2015-01-23 16:45:18 -080017#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
Eric Laurentd4692962014-05-05 18:13:44 -070027#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070028#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070029
François Gaffie2110e042015-03-24 08:41:51 +010030#include <AudioPolicyManagerInterface.h>
31#include <AudioPolicyEngineInstance.h>
Eric Laurente552edb2014-03-10 17:42:56 -070032#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <utils/Log.h>
34#include <hardware/audio.h>
35#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070036#include <media/AudioParameter.h>
Eric Laurente83b55d2014-11-14 10:06:21 -080037#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070038#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070039#include "AudioPolicyManager.h"
François Gaffie53615e22015-03-19 09:24:12 +010040#include <ConfigParsingUtils.h>
François Gaffiea8ecc2c2015-11-09 16:10:40 +010041#include "TypeConverter.h"
François Gaffie53615e22015-03-19 09:24:12 +010042#include <policy.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043
Eric Laurent3b73df72014-03-11 09:06:29 -070044namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070045
46// ----------------------------------------------------------------------------
47// AudioPolicyInterface implementation
48// ----------------------------------------------------------------------------
49
Eric Laurente0720872014-03-11 09:30:41 -070050status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Paul McLeane743a472015-01-28 11:07:31 -080051 audio_policy_dev_state_t state,
52 const char *device_address,
53 const char *device_name)
Eric Laurente552edb2014-03-10 17:42:56 -070054{
Paul McLeane743a472015-01-28 11:07:31 -080055 return setDeviceConnectionStateInt(device, state, device_address, device_name);
Eric Laurentc73ca6e2014-12-12 14:34:22 -080056}
57
58status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -080059 audio_policy_dev_state_t state,
Paul McLeane743a472015-01-28 11:07:31 -080060 const char *device_address,
61 const char *device_name)
Eric Laurentc73ca6e2014-12-12 14:34:22 -080062{
Paul McLeane743a472015-01-28 11:07:31 -080063 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s",
64- device, state, device_address, device_name);
Eric Laurente552edb2014-03-10 17:42:56 -070065
66 // connect/disconnect only 1 device at a time
67 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
68
François Gaffie53615e22015-03-19 09:24:12 +010069 sp<DeviceDescriptor> devDesc =
70 mHwModules.getDeviceDescriptor(device, device_address, device_name);
Paul McLeane743a472015-01-28 11:07:31 -080071
Eric Laurente552edb2014-03-10 17:42:56 -070072 // handle output devices
73 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -070074 SortedVector <audio_io_handle_t> outputs;
75
Eric Laurent3a4311c2014-03-17 12:00:47 -070076 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
77
Eric Laurente552edb2014-03-10 17:42:56 -070078 // save a copy of the opened output descriptors before any output is opened or closed
79 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
80 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -070081 switch (state)
82 {
83 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -080084 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -070086 ALOGW("setDeviceConnectionState() device already connected: %x", device);
87 return INVALID_OPERATION;
88 }
89 ALOGV("setDeviceConnectionState() connecting device %x", device);
90
Eric Laurente552edb2014-03-10 17:42:56 -070091 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -070092 index = mAvailableOutputDevices.add(devDesc);
93 if (index >= 0) {
François Gaffie53615e22015-03-19 09:24:12 +010094 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -070095 if (module == 0) {
96 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
97 device);
98 mAvailableOutputDevices.remove(devDesc);
99 return INVALID_OPERATION;
100 }
Paul McLeane743a472015-01-28 11:07:31 -0800101 mAvailableOutputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 } else {
103 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700104 }
105
Eric Laurenta1d525f2015-01-29 13:36:45 -0800106 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700107 mAvailableOutputDevices.remove(devDesc);
108 return INVALID_OPERATION;
109 }
François Gaffie2110e042015-03-24 08:41:51 +0100110 // Propagate device availability to Engine
111 mEngine->setDeviceConnectionState(devDesc, state);
112
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700113 // outputs should never be empty here
114 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
115 "checkOutputsForDevice() returned no outputs but status OK");
116 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
117 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800118
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800119 // Send connect to HALs
Eric Laurent3ae5f312015-02-03 17:12:08 -0800120 AudioParameter param = AudioParameter(devDesc->mAddress);
121 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
122 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
123
124 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700125 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700126 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700127 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700128 ALOGW("setDeviceConnectionState() device not connected: %x", device);
129 return INVALID_OPERATION;
130 }
131
Paul McLean5c477aa2014-08-20 16:47:57 -0700132 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
133
Paul McLeane743a472015-01-28 11:07:31 -0800134 // Send Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800135 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700136 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
137 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
138
Eric Laurente552edb2014-03-10 17:42:56 -0700139 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700140 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700141
Eric Laurenta1d525f2015-01-29 13:36:45 -0800142 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
François Gaffie2110e042015-03-24 08:41:51 +0100143
144 // Propagate device availability to Engine
145 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700146 } break;
147
148 default:
149 ALOGE("setDeviceConnectionState() invalid state: %x", state);
150 return BAD_VALUE;
151 }
152
Eric Laurent3a4311c2014-03-17 12:00:47 -0700153 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
154 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700155 checkA2dpSuspend();
156 checkOutputForAllStrategies();
157 // outputs must be closed after checkOutputForAllStrategies() is executed
158 if (!outputs.isEmpty()) {
159 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700160 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700161 // close unused outputs after device disconnection or direct outputs that have been
162 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700163 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700164 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
165 (desc->mDirectOpenCount == 0))) {
166 closeOutput(outputs[i]);
167 }
168 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700169 // check again after closing A2DP output to reset mA2dpSuspended if needed
170 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700171 }
172
173 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700174 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700175 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
176 updateCallRouting(newDevice);
177 }
Eric Laurente552edb2014-03-10 17:42:56 -0700178 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700179 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
180 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
181 audio_devices_t newDevice = getNewOutputDevice(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700182 // do not force device change on duplicated output because if device is 0, it will
183 // also force a device 0 for the two outputs it is duplicated to which may override
184 // a valid device selection on those outputs.
Eric Laurentc75307b2015-03-17 15:29:32 -0700185 bool force = !desc->isDuplicated()
François Gaffie53615e22015-03-19 09:24:12 +0100186 && (!device_distinguishes_on_address(device)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700187 // always force when disconnecting (a non-duplicated device)
188 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurentc75307b2015-03-17 15:29:32 -0700189 setOutputDevice(desc, newDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700190 }
Eric Laurente552edb2014-03-10 17:42:56 -0700191 }
192
Eric Laurentd60560a2015-04-10 11:31:20 -0700193 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
194 cleanUpForDevice(devDesc);
195 }
196
Eric Laurent72aa32f2014-05-30 18:51:48 -0700197 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700198 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700199 } // end if is output device
200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // handle input devices
202 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700203 SortedVector <audio_io_handle_t> inputs;
204
Eric Laurent3a4311c2014-03-17 12:00:47 -0700205 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700206 switch (state)
207 {
208 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700209 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700210 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700211 ALOGW("setDeviceConnectionState() device already connected: %d", device);
212 return INVALID_OPERATION;
213 }
François Gaffie53615e22015-03-19 09:24:12 +0100214 sp<HwModule> module = mHwModules.getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700215 if (module == NULL) {
216 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
217 device);
218 return INVALID_OPERATION;
219 }
Paul McLean9080a4c2015-06-18 08:24:02 -0700220 if (checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700221 return INVALID_OPERATION;
222 }
223
Eric Laurent3a4311c2014-03-17 12:00:47 -0700224 index = mAvailableInputDevices.add(devDesc);
225 if (index >= 0) {
Paul McLeane743a472015-01-28 11:07:31 -0800226 mAvailableInputDevices[index]->attach(module);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700227 } else {
228 return NO_MEMORY;
229 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230
231 // Set connect to HALs
232 AudioParameter param = AudioParameter(devDesc->mAddress);
233 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
234 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
235
François Gaffie2110e042015-03-24 08:41:51 +0100236 // Propagate device availability to Engine
237 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700238 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700239
240 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700241 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700242 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700243 ALOGW("setDeviceConnectionState() device not connected: %d", device);
244 return INVALID_OPERATION;
245 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700246
247 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
248
249 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800250 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700251 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
252 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
253
Paul McLean9080a4c2015-06-18 08:24:02 -0700254 checkInputsForDevice(devDesc, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700255 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700256
François Gaffie2110e042015-03-24 08:41:51 +0100257 // Propagate device availability to Engine
258 mEngine->setDeviceConnectionState(devDesc, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700259 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700260
261 default:
262 ALOGE("setDeviceConnectionState() invalid state: %x", state);
263 return BAD_VALUE;
264 }
265
Eric Laurentd4692962014-05-05 18:13:44 -0700266 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700267
Eric Laurent87ffa392015-05-22 10:32:38 -0700268 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700269 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
270 updateCallRouting(newDevice);
271 }
272
Eric Laurentd60560a2015-04-10 11:31:20 -0700273 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
274 cleanUpForDevice(devDesc);
275 }
276
Eric Laurentb52c1522014-05-20 11:27:36 -0700277 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700278 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700279 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700280
281 ALOGW("setDeviceConnectionState() invalid device: %x", device);
282 return BAD_VALUE;
283}
284
Eric Laurente0720872014-03-11 09:30:41 -0700285audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100286 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700287{
François Gaffie53615e22015-03-19 09:24:12 +0100288 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(device, device_address, "");
289
Eric Laurent3a4311c2014-03-17 12:00:47 -0700290 DeviceVector *deviceVector;
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700293 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700294 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700295 deviceVector = &mAvailableInputDevices;
296 } else {
297 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
298 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
François Gaffie53615e22015-03-19 09:24:12 +0100300 return deviceVector->getDeviceConnectionState(devDesc);
Eric Laurenta1d525f2015-01-29 13:36:45 -0800301}
302
Eric Laurentc2730ba2014-07-20 15:47:07 -0700303void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
304{
305 bool createTxPatch = false;
306 struct audio_patch patch;
307 patch.num_sources = 1;
308 patch.num_sinks = 1;
309 status_t status;
310 audio_patch_handle_t afPatchHandle;
311 DeviceVector deviceList;
312
Eric Laurent87ffa392015-05-22 10:32:38 -0700313 if(!hasPrimaryOutput()) {
314 return;
315 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800316 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700317 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
318
319 // release existing RX patch if any
320 if (mCallRxPatch != 0) {
321 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
322 mCallRxPatch.clear();
323 }
324 // release TX patch if any
325 if (mCallTxPatch != 0) {
326 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
327 mCallTxPatch.clear();
328 }
329
330 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
331 // via setOutputDevice() on primary output.
332 // Otherwise, create two audio patches for TX and RX path.
333 if (availablePrimaryOutputDevices() & rxDevice) {
334 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
335 // If the TX device is also on the primary HW module, setOutputDevice() will take care
336 // of it due to legacy implementation. If not, create a patch.
337 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
338 == AUDIO_DEVICE_NONE) {
339 createTxPatch = true;
340 }
341 } else {
342 // create RX path audio patch
343 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
344 ALOG_ASSERT(!deviceList.isEmpty(),
345 "updateCallRouting() selected device not in output device list");
346 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
347 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
348 ALOG_ASSERT(!deviceList.isEmpty(),
349 "updateCallRouting() no telephony RX device");
350 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
351
352 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
353 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
354
355 // request to reuse existing output stream if one is already opened to reach the RX device
356 SortedVector<audio_io_handle_t> outputs =
357 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700358 audio_io_handle_t output = selectOutput(outputs,
359 AUDIO_OUTPUT_FLAG_NONE,
360 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700361 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700362 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700363 ALOG_ASSERT(!outputDesc->isDuplicated(),
364 "updateCallRouting() RX device output is duplicated");
365 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700366 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700367 patch.num_sources = 2;
368 }
369
370 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
371 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
372 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
373 status);
374 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100375 mCallRxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700376 mCallRxPatch->mAfPatchHandle = afPatchHandle;
377 mCallRxPatch->mUid = mUidCached;
378 }
379 createTxPatch = true;
380 }
381 if (createTxPatch) {
382
383 struct audio_patch patch;
384 patch.num_sources = 1;
385 patch.num_sinks = 1;
386 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
387 ALOG_ASSERT(!deviceList.isEmpty(),
388 "updateCallRouting() selected device not in input device list");
389 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
390 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
391 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
392 ALOG_ASSERT(!deviceList.isEmpty(),
393 "updateCallRouting() no telephony TX device");
394 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
395 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
396
397 SortedVector<audio_io_handle_t> outputs =
398 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700399 audio_io_handle_t output = selectOutput(outputs,
400 AUDIO_OUTPUT_FLAG_NONE,
401 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700402 // request to reuse existing output stream if one is already opened to reach the TX
403 // path output device
404 if (output != AUDIO_IO_HANDLE_NONE) {
405 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
406 ALOG_ASSERT(!outputDesc->isDuplicated(),
407 "updateCallRouting() RX device output is duplicated");
408 outputDesc->toAudioPortConfig(&patch.sources[1]);
Eric Laurent3bcf8592015-04-03 12:13:24 -0700409 patch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700410 patch.num_sources = 2;
411 }
412
Eric Laurentc0a889f2015-10-14 14:36:34 -0700413 // terminate active capture if on the same HW module as the call TX source device
414 // FIXME: would be better to refine to only inputs whose profile connects to the
415 // call TX device but this information is not in the audio patch and logic here must be
416 // symmetric to the one in startInput()
417 audio_io_handle_t activeInput = mInputs.getActiveInput();
418 if (activeInput != 0) {
419 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
420 if (activeDesc->getModuleHandle() == txSourceDeviceDesc->getModuleHandle()) {
Eric Laurent599c7582015-12-07 18:05:55 -0800421 //FIXME: consider all active sessions
422 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
423 audio_session_t activeSession = activeSessions.keyAt(0);
Eric Laurentc0a889f2015-10-14 14:36:34 -0700424 stopInput(activeInput, activeSession);
425 releaseInput(activeInput, activeSession);
426 }
427 }
428
Eric Laurentc2730ba2014-07-20 15:47:07 -0700429 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
430 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
431 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
432 status);
433 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100434 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700435 mCallTxPatch->mAfPatchHandle = afPatchHandle;
436 mCallTxPatch->mUid = mUidCached;
437 }
438 }
439}
440
Eric Laurente0720872014-03-11 09:30:41 -0700441void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700442{
443 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100444 // store previous phone state for management of sonification strategy below
445 int oldState = mEngine->getPhoneState();
446
447 if (mEngine->setPhoneState(state) != NO_ERROR) {
448 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return;
450 }
François Gaffie2110e042015-03-24 08:41:51 +0100451 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700452 // if leaving call state, handle special case of active streams
453 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700454 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700455 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700456 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800457 if (stream == AUDIO_STREAM_PATCH) {
458 continue;
459 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700460 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700461 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800462
Eric Laurent63dea1d2015-07-02 17:10:28 -0700463 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800464 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700465 }
466
François Gaffie2110e042015-03-24 08:41:51 +0100467 /**
468 * Switching to or from incall state or switching between telephony and VoIP lead to force
469 * routing command.
470 */
471 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
472 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700473
474 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700475 checkA2dpSuspend();
476 checkOutputForAllStrategies();
477 updateDevicesAndOutputs();
478
Eric Laurente552edb2014-03-10 17:42:56 -0700479 int delayMs = 0;
480 if (isStateInCall(state)) {
481 nsecs_t sysTime = systemTime();
482 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700483 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700484 // mute media and sonification strategies and delay device switch by the largest
485 // latency of any output where either strategy is active.
486 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100487 if ((isStrategyActive(desc, STRATEGY_MEDIA,
488 SONIFICATION_HEADSET_MUSIC_DELAY,
489 sysTime) ||
490 isStrategyActive(desc, STRATEGY_SONIFICATION,
491 SONIFICATION_HEADSET_MUSIC_DELAY,
492 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700493 (delayMs < (int)desc->latency()*2)) {
494 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700495 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700496 setStrategyMute(STRATEGY_MEDIA, true, desc);
497 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700498 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700499 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
500 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700501 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
502 }
503 }
504
Eric Laurent87ffa392015-05-22 10:32:38 -0700505 if (hasPrimaryOutput()) {
506 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
507 // the device returned is not necessarily reachable via this output
508 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
509 // force routing command to audio hardware when ending call
510 // even if no device change is needed
511 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
512 rxDevice = mPrimaryOutput->device();
513 }
Eric Laurente552edb2014-03-10 17:42:56 -0700514
Eric Laurent87ffa392015-05-22 10:32:38 -0700515 if (state == AUDIO_MODE_IN_CALL) {
516 updateCallRouting(rxDevice, delayMs);
517 } else if (oldState == AUDIO_MODE_IN_CALL) {
518 if (mCallRxPatch != 0) {
519 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
520 mCallRxPatch.clear();
521 }
522 if (mCallTxPatch != 0) {
523 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
524 mCallTxPatch.clear();
525 }
526 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
527 } else {
528 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700529 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700530 }
Eric Laurente552edb2014-03-10 17:42:56 -0700531 // if entering in call state, handle special case of active streams
532 // pertaining to sonification strategy see handleIncallSonification()
533 if (isStateInCall(state)) {
534 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700535 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800536 if (stream == AUDIO_STREAM_PATCH) {
537 continue;
538 }
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();
Eric Laurent87ffa392015-05-22 10:32:38 -0700576 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700577 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
578 updateCallRouting(newDevice);
579 }
Eric Laurente552edb2014-03-10 17:42:56 -0700580 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700581 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
582 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
583 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
584 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700585 }
Eric Laurente552edb2014-03-10 17:42:56 -0700586 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700587 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700588 }
589 }
590
François Gaffie53615e22015-03-19 09:24:12 +0100591 audio_io_handle_t activeInput = mInputs.getActiveInput();
Eric Laurente552edb2014-03-10 17:42:56 -0700592 if (activeInput != 0) {
Eric Laurentc171c7c2015-09-25 12:21:06 -0700593 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
594 audio_devices_t newDevice = getNewInputDevice(activeInput);
595 // Force new input selection if the new device can not be reached via current input
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100596 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentc171c7c2015-09-25 12:21:06 -0700597 setInputDevice(activeInput, newDevice);
598 } else {
599 closeInput(activeInput);
600 }
Eric Laurente552edb2014-03-10 17:42:56 -0700601 }
Eric Laurente552edb2014-03-10 17:42:56 -0700602}
603
Eric Laurente0720872014-03-11 09:30:41 -0700604void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700605{
606 ALOGV("setSystemProperty() property %s, value %s", property, value);
607}
608
609// Find a direct output profile compatible with the parameters passed, even if the input flags do
610// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800611sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700612 audio_devices_t device,
613 uint32_t samplingRate,
614 audio_format_t format,
615 audio_channel_mask_t channelMask,
616 audio_output_flags_t flags)
617{
Eric Laurent861a6282015-05-18 15:40:16 -0700618 // only retain flags that will drive the direct output profile selection
619 // if explicitly requested
620 static const uint32_t kRelevantFlags =
621 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
622 flags =
623 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
624
625 sp<IOProfile> profile;
626
Eric Laurente552edb2014-03-10 17:42:56 -0700627 for (size_t i = 0; i < mHwModules.size(); i++) {
628 if (mHwModules[i]->mHandle == 0) {
629 continue;
630 }
631 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700632 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
633 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700634 samplingRate, NULL /*updatedSamplingRate*/,
635 format, NULL /*updatedFormat*/,
636 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700637 flags)) {
638 continue;
639 }
640 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100641 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700642 continue;
643 }
644 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100645 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700646 continue;
647 }
648 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100649 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700650 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700651 }
Eric Laurente552edb2014-03-10 17:42:56 -0700652 }
653 }
Eric Laurent861a6282015-05-18 15:40:16 -0700654 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700655}
656
Eric Laurente0720872014-03-11 09:30:41 -0700657audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100658 uint32_t samplingRate,
659 audio_format_t format,
660 audio_channel_mask_t channelMask,
661 audio_output_flags_t flags,
662 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700663{
Eric Laurent3b73df72014-03-11 09:06:29 -0700664 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700665 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
666 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
667 device, stream, samplingRate, format, channelMask, flags);
668
Eric Laurente83b55d2014-11-14 10:06:21 -0800669 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
670 stream, samplingRate,format, channelMask,
671 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700672}
673
Eric Laurente83b55d2014-11-14 10:06:21 -0800674status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
675 audio_io_handle_t *output,
676 audio_session_t session,
677 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700678 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800679 uint32_t samplingRate,
680 audio_format_t format,
681 audio_channel_mask_t channelMask,
682 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700683 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800684 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700685{
Eric Laurente83b55d2014-11-14 10:06:21 -0800686 audio_attributes_t attributes;
687 if (attr != NULL) {
688 if (!isValidAttributes(attr)) {
689 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
690 attr->usage, attr->content_type, attr->flags,
691 attr->tags);
692 return BAD_VALUE;
693 }
694 attributes = *attr;
695 } else {
696 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
697 ALOGE("getOutputForAttr(): invalid stream type");
698 return BAD_VALUE;
699 }
700 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700701 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700702 sp<SwAudioOutputDescriptor> desc;
François Gaffie036e1e92015-03-19 10:16:24 +0100703 if (mPolicyMixes.getOutputForAttr(attributes, desc) == NO_ERROR) {
704 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
705 if (!audio_is_linear_pcm(format)) {
706 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800707 }
François Gaffie036e1e92015-03-19 10:16:24 +0100708 *stream = streamTypefromAttributesInt(&attributes);
709 *output = desc->mIoHandle;
710 ALOGV("getOutputForAttr() returns output %d", *output);
711 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800712 }
713 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
714 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
715 return BAD_VALUE;
716 }
717
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700718 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
719 " session %d selectedDeviceId %d",
720 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
721 session, selectedDeviceId);
722
723 *stream = streamTypefromAttributesInt(&attributes);
724
725 // Explicit routing?
726 sp<DeviceDescriptor> deviceDesc;
727 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
728 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
729 deviceDesc = mAvailableOutputDevices[i];
730 break;
731 }
732 }
733 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700734
Eric Laurente83b55d2014-11-14 10:06:21 -0800735 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700736 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700737
Eric Laurente83b55d2014-11-14 10:06:21 -0800738 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700739 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
740 }
741
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700742 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700743 device, samplingRate, format, channelMask, flags);
744
Eric Laurente83b55d2014-11-14 10:06:21 -0800745 *output = getOutputForDevice(device, session, *stream,
746 samplingRate, format, channelMask,
747 flags, offloadInfo);
748 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700749 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800750 return INVALID_OPERATION;
751 }
Paul McLeanaa981192015-03-21 09:55:15 -0700752
Eric Laurente83b55d2014-11-14 10:06:21 -0800753 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700754}
755
756audio_io_handle_t AudioPolicyManager::getOutputForDevice(
757 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800758 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700759 audio_stream_type_t stream,
760 uint32_t samplingRate,
761 audio_format_t format,
762 audio_channel_mask_t channelMask,
763 audio_output_flags_t flags,
764 const audio_offload_info_t *offloadInfo)
765{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700766 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700767 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700768 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700769
Eric Laurente552edb2014-03-10 17:42:56 -0700770#ifdef AUDIO_POLICY_TEST
771 if (mCurOutput != 0) {
772 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
773 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
774
775 if (mTestOutputs[mCurOutput] == 0) {
776 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700777 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
778 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700779 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700780 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700781 outputDesc->mFlags =
782 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700783 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700784 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
785 config.sample_rate = mTestSamplingRate;
786 config.channel_mask = mTestChannels;
787 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700788 if (offloadInfo != NULL) {
789 config.offload_info = *offloadInfo;
790 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700791 status = mpClientInterface->openOutput(0,
792 &mTestOutputs[mCurOutput],
793 &config,
794 &outputDesc->mDevice,
795 String8(""),
796 &outputDesc->mLatency,
797 outputDesc->mFlags);
798 if (status == NO_ERROR) {
799 outputDesc->mSamplingRate = config.sample_rate;
800 outputDesc->mFormat = config.format;
801 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700802 AudioParameter outputCmd = AudioParameter();
803 outputCmd.addInt(String8("set_id"),mCurOutput);
804 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
805 addOutput(mTestOutputs[mCurOutput], outputDesc);
806 }
807 }
808 return mTestOutputs[mCurOutput];
809 }
810#endif //AUDIO_POLICY_TEST
811
812 // open a direct output if required by specified parameters
813 //force direct flag if offload flag is set: offloading implies a direct output stream
814 // and all common behaviors are driven by checking only the direct flag
815 // this should normally be set appropriately in the policy configuration file
816 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700817 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700818 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700819 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
820 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
821 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800822 // only allow deep buffering for music stream type
823 if (stream != AUDIO_STREAM_MUSIC) {
824 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700825 } else if (/* stream == AUDIO_STREAM_MUSIC && */
826 flags == AUDIO_OUTPUT_FLAG_NONE &&
827 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
828 // use DEEP_BUFFER as default output for music stream type
829 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800830 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700831 if (stream == AUDIO_STREAM_TTS) {
832 flags = AUDIO_OUTPUT_FLAG_TTS;
833 }
Eric Laurente552edb2014-03-10 17:42:56 -0700834
Eric Laurentb732cf52014-09-24 19:08:21 -0700835 sp<IOProfile> profile;
836
837 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700838 // and not explicitly requested
839 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
840 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700841 audio_channel_count_from_out_mask(channelMask) <= 2) {
842 goto non_direct_output;
843 }
844
Andy Hung2ddee192015-12-18 17:34:44 -0800845 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
846 // This prevents creating an offloaded track and tearing it down immediately after start
847 // when audioflinger detects there is an active non offloadable effect.
Eric Laurente552edb2014-03-10 17:42:56 -0700848 // FIXME: We should check the audio session here but we do not have it in this context.
849 // This may prevent offloading in rare situations where effects are left active by apps
850 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700851
Eric Laurente552edb2014-03-10 17:42:56 -0700852 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
Andy Hung2ddee192015-12-18 17:34:44 -0800853 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700854 profile = getProfileForDirectOutput(device,
855 samplingRate,
856 format,
857 channelMask,
858 (audio_output_flags_t)flags);
859 }
860
Eric Laurent1c333e22014-05-20 10:48:17 -0700861 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700862 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700863
864 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700865 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700866 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
867 outputDesc = desc;
868 // reuse direct output if currently open and configured with same parameters
869 if ((samplingRate == outputDesc->mSamplingRate) &&
870 (format == outputDesc->mFormat) &&
871 (channelMask == outputDesc->mChannelMask)) {
872 outputDesc->mDirectOpenCount++;
873 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
874 return mOutputs.keyAt(i);
875 }
876 }
877 }
878 // close direct output if currently open and configured with different parameters
879 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700880 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700881 }
Eric Laurent861a6282015-05-18 15:40:16 -0700882
883 // if the selected profile is offloaded and no offload info was specified,
884 // create a default one
885 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100886 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700887 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
888 defaultOffloadInfo.sample_rate = samplingRate;
889 defaultOffloadInfo.channel_mask = channelMask;
890 defaultOffloadInfo.format = format;
891 defaultOffloadInfo.stream_type = stream;
892 defaultOffloadInfo.bit_rate = 0;
893 defaultOffloadInfo.duration_us = -1;
894 defaultOffloadInfo.has_video = true; // conservative
895 defaultOffloadInfo.is_streaming = true; // likely
896 offloadInfo = &defaultOffloadInfo;
897 }
898
Eric Laurentc75307b2015-03-17 15:29:32 -0700899 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700900 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700901 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700902 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700903 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
904 config.sample_rate = samplingRate;
905 config.channel_mask = channelMask;
906 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700907 if (offloadInfo != NULL) {
908 config.offload_info = *offloadInfo;
909 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700910 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700911 &output,
912 &config,
913 &outputDesc->mDevice,
914 String8(""),
915 &outputDesc->mLatency,
916 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700917
918 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700919 if (status != NO_ERROR ||
920 (samplingRate != 0 && samplingRate != config.sample_rate) ||
921 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
922 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700923 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
924 "format %d %d, channelMask %04x %04x", output, samplingRate,
925 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
926 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700927 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700928 mpClientInterface->closeOutput(output);
929 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800930 // fall back to mixer output if possible when the direct output could not be open
931 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
932 goto non_direct_output;
933 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700934 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700935 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700936 outputDesc->mSamplingRate = config.sample_rate;
937 outputDesc->mChannelMask = config.channel_mask;
938 outputDesc->mFormat = config.format;
939 outputDesc->mRefCount[stream] = 0;
940 outputDesc->mStopTime[stream] = 0;
941 outputDesc->mDirectOpenCount = 1;
942
Eric Laurente552edb2014-03-10 17:42:56 -0700943 audio_io_handle_t srcOutput = getOutputForEffect();
944 addOutput(output, outputDesc);
945 audio_io_handle_t dstOutput = getOutputForEffect();
946 if (dstOutput == output) {
947 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
948 }
949 mPreviousOutputs = mOutputs;
950 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700951 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700952 return output;
953 }
954
Eric Laurentb732cf52014-09-24 19:08:21 -0700955non_direct_output:
Eric Laurente552edb2014-03-10 17:42:56 -0700956 // ignoring channel mask due to downmix capability in mixer
957
958 // open a non direct output
959
960 // for non direct outputs, only PCM is supported
961 if (audio_is_linear_pcm(format)) {
962 // get which output is suitable for the specified stream. The actual
963 // routing change will happen when startOutput() will be called
964 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
965
Eric Laurent8838a382014-09-08 16:44:28 -0700966 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
967 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
968 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700969 }
970 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
971 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
972
Paul McLeanaa981192015-03-21 09:55:15 -0700973 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700974
975 return output;
976}
977
Eric Laurente0720872014-03-11 09:30:41 -0700978audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700979 audio_output_flags_t flags,
980 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700981{
982 // select one output among several that provide a path to a particular device or set of
983 // devices (the list was previously build by getOutputsForDevice()).
984 // The priority is as follows:
985 // 1: the output with the highest number of requested policy flags
986 // 2: the primary output
987 // 3: the first output in the list
988
989 if (outputs.size() == 0) {
990 return 0;
991 }
992 if (outputs.size() == 1) {
993 return outputs[0];
994 }
995
996 int maxCommonFlags = 0;
997 audio_io_handle_t outputFlags = 0;
998 audio_io_handle_t outputPrimary = 0;
999
1000 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001001 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001002 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001003 // if a valid format is specified, skip output if not compatible
1004 if (format != AUDIO_FORMAT_INVALID) {
1005 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1006 if (format != outputDesc->mFormat) {
1007 continue;
1008 }
1009 } else if (!audio_is_linear_pcm(format)) {
1010 continue;
1011 }
1012 }
1013
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001014 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001015 if (commonFlags > maxCommonFlags) {
1016 outputFlags = outputs[i];
1017 maxCommonFlags = commonFlags;
1018 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1019 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001020 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente552edb2014-03-10 17:42:56 -07001021 outputPrimary = outputs[i];
1022 }
1023 }
1024 }
1025
1026 if (outputFlags != 0) {
1027 return outputFlags;
1028 }
1029 if (outputPrimary != 0) {
1030 return outputPrimary;
1031 }
1032
1033 return outputs[0];
1034}
1035
Eric Laurente0720872014-03-11 09:30:41 -07001036status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001037 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001038 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001039{
Paul McLeanaa981192015-03-21 09:55:15 -07001040 ALOGV("startOutput() output %d, stream %d, session %d",
1041 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001042 ssize_t index = mOutputs.indexOfKey(output);
1043 if (index < 0) {
1044 ALOGW("startOutput() unknown output %d", output);
1045 return BAD_VALUE;
1046 }
1047
Eric Laurentc75307b2015-03-17 15:29:32 -07001048 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1049
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001050 // Routing?
1051 mOutputRoutes.incRouteActivity(session);
1052
Eric Laurentc75307b2015-03-17 15:29:32 -07001053 audio_devices_t newDevice;
1054 if (outputDesc->mPolicyMix != NULL) {
1055 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -07001056 } else if (mOutputRoutes.hasRouteChanged(session)) {
1057 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001058 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001059 } else {
1060 newDevice = AUDIO_DEVICE_NONE;
1061 }
1062
1063 uint32_t delayMs = 0;
1064
Eric Laurentc75307b2015-03-17 15:29:32 -07001065 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1066
1067 if (status != NO_ERROR) {
1068 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001069 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001070 }
1071 // Automatically enable the remote submix input when output is started on a re routing mix
1072 // of type MIX_TYPE_RECORDERS
1073 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1074 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1075 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1076 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1077 outputDesc->mPolicyMix->mRegistrationId,
1078 "remote-submix");
1079 }
1080
1081 if (delayMs != 0) {
1082 usleep(delayMs * 1000);
1083 }
1084
1085 return status;
1086}
1087
1088status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1089 audio_stream_type_t stream,
1090 audio_devices_t device,
1091 uint32_t *delayMs)
1092{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001093 // cannot start playback of STREAM_TTS if any other output is being used
1094 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001095
1096 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001097 if (stream == AUDIO_STREAM_TTS) {
1098 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001099 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001100 return INVALID_OPERATION;
1101 } else {
1102 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1103 }
1104 } else {
1105 // some playback other than beacon starts
1106 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1107 }
1108
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001109 // check active before incrementing usage count
1110 bool force = !outputDesc->isActive();
1111
Eric Laurente552edb2014-03-10 17:42:56 -07001112 // increment usage count for this stream on the requested output:
1113 // NOTE that the usage count is the same for duplicated output and hardware output which is
1114 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1115 outputDesc->changeRefCount(stream, 1);
1116
Eric Laurent493404d2015-04-21 15:07:36 -07001117 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001118 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001119 if (device == AUDIO_DEVICE_NONE) {
1120 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001121 }
Eric Laurente552edb2014-03-10 17:42:56 -07001122 routing_strategy strategy = getStrategy(stream);
1123 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001124 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1125 (beaconMuteLatency > 0);
1126 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001127 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001128 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 if (desc != outputDesc) {
1130 // force a device change if any other output is managed by the same hw
1131 // module and has a current device selection that differs from selected device.
1132 // In this case, the audio HAL must receive the new device selection so that it can
1133 // change the device currently selected by the other active output.
1134 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001135 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001136 force = true;
1137 }
1138 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001139 // a notification so that audio focus effect can propagate, or that a mute/unmute
1140 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001141 uint32_t latency = desc->latency();
1142 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1143 waitMs = latency;
1144 }
1145 }
1146 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001147 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001148
1149 // handle special case for sonification while in call
1150 if (isInCall()) {
1151 handleIncallSonification(stream, true, false);
1152 }
1153
1154 // apply volume rules for current stream and device if necessary
1155 checkAndSetVolume(stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07001156 mStreams.valueFor(stream).getVolumeIndex(device),
1157 outputDesc,
1158 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001159
1160 // update the outputs if starting an output with a stream that can affect notification
1161 // routing
1162 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001163
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001164 // force reevaluating accessibility routing when ringtone or alarm starts
1165 if (strategy == STRATEGY_SONIFICATION) {
1166 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1167 }
Eric Laurente552edb2014-03-10 17:42:56 -07001168 }
1169 return NO_ERROR;
1170}
1171
1172
Eric Laurente0720872014-03-11 09:30:41 -07001173status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001174 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001175 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001176{
1177 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1178 ssize_t index = mOutputs.indexOfKey(output);
1179 if (index < 0) {
1180 ALOGW("stopOutput() unknown output %d", output);
1181 return BAD_VALUE;
1182 }
1183
Eric Laurentc75307b2015-03-17 15:29:32 -07001184 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001185
Eric Laurentc75307b2015-03-17 15:29:32 -07001186 if (outputDesc->mRefCount[stream] == 1) {
1187 // Automatically disable the remote submix input when output is stopped on a
1188 // re routing mix of type MIX_TYPE_RECORDERS
1189 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1190 outputDesc->mPolicyMix != NULL &&
1191 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1192 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1193 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1194 outputDesc->mPolicyMix->mRegistrationId,
1195 "remote-submix");
1196 }
1197 }
1198
1199 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001200 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001201 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001202 int activityCount = mOutputRoutes.decRouteActivity(session);
1203 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1204
1205 if (forceDeviceUpdate) {
1206 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1207 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001208 }
1209
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001210 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001211}
1212
1213status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001214 audio_stream_type_t stream,
1215 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001216{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001217 // always handle stream stop, check which stream type is stopping
1218 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1219
Eric Laurente552edb2014-03-10 17:42:56 -07001220 // handle special case for sonification while in call
1221 if (isInCall()) {
1222 handleIncallSonification(stream, false, false);
1223 }
1224
1225 if (outputDesc->mRefCount[stream] > 0) {
1226 // decrement usage count of this stream on the output
1227 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001228
Eric Laurente552edb2014-03-10 17:42:56 -07001229 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001230 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001231 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001232 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001233 // delay the device switch by twice the latency because stopOutput() is executed when
1234 // the track stop() command is received and at that time the audio track buffer can
1235 // still contain data that needs to be drained. The latency only covers the audio HAL
1236 // and kernel buffers. Also the latency does not always include additional delay in the
1237 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001238 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001239
1240 // force restoring the device selection on other active outputs if it differs from the
1241 // one being selected for this output
1242 for (size_t i = 0; i < mOutputs.size(); i++) {
1243 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001244 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001245 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001246 desc->isActive() &&
1247 outputDesc->sharesHwModuleWith(desc) &&
1248 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001249 setOutputDevice(desc,
1250 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001251 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001252 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001253 }
1254 }
1255 // update the outputs if stopping one with a stream that can affect notification routing
1256 handleNotificationRoutingForStream(stream);
1257 }
1258 return NO_ERROR;
1259 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001260 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001261 return INVALID_OPERATION;
1262 }
1263}
1264
Eric Laurente83b55d2014-11-14 10:06:21 -08001265void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001266 audio_stream_type_t stream __unused,
1267 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001268{
1269 ALOGV("releaseOutput() %d", output);
1270 ssize_t index = mOutputs.indexOfKey(output);
1271 if (index < 0) {
1272 ALOGW("releaseOutput() releasing unknown output %d", output);
1273 return;
1274 }
1275
1276#ifdef AUDIO_POLICY_TEST
1277 int testIndex = testOutputIndex(output);
1278 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001279 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001280 if (outputDesc->isActive()) {
1281 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001282 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001283 mTestOutputs[testIndex] = 0;
1284 }
1285 return;
1286 }
1287#endif //AUDIO_POLICY_TEST
1288
Paul McLeanaa981192015-03-21 09:55:15 -07001289 // Routing
1290 mOutputRoutes.removeRoute(session);
1291
Eric Laurentc75307b2015-03-17 15:29:32 -07001292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001293 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001294 if (desc->mDirectOpenCount <= 0) {
1295 ALOGW("releaseOutput() invalid open count %d for output %d",
1296 desc->mDirectOpenCount, output);
1297 return;
1298 }
1299 if (--desc->mDirectOpenCount == 0) {
1300 closeOutput(output);
1301 // If effects where present on the output, audioflinger moved them to the primary
1302 // output by default: move them back to the appropriate output.
1303 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001304 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001305 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1306 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001307 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001308 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001309 }
1310 }
1311}
1312
1313
Eric Laurentcaf7f482014-11-25 17:50:47 -08001314status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1315 audio_io_handle_t *input,
1316 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001317 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001318 uint32_t samplingRate,
1319 audio_format_t format,
1320 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001321 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001322 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001323 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001324{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001325 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1326 "session %d, flags %#x",
1327 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001328
Eric Laurentcaf7f482014-11-25 17:50:47 -08001329 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001330 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001331 audio_devices_t device;
1332 // handle legacy remote submix case where the address was not always specified
1333 String8 address = String8("");
Eric Laurentc447ded2015-01-06 08:47:05 -08001334 audio_source_t inputSource = attr->source;
1335 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001336 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001337
Eric Laurentc447ded2015-01-06 08:47:05 -08001338 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1339 inputSource = AUDIO_SOURCE_MIC;
1340 }
1341 halInputSource = inputSource;
1342
Paul McLean466dc8e2015-04-17 13:15:36 -06001343 // Explicit routing?
1344 sp<DeviceDescriptor> deviceDesc;
1345 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1346 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1347 deviceDesc = mAvailableInputDevices[i];
1348 break;
1349 }
1350 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001351 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001352
Eric Laurentc447ded2015-01-06 08:47:05 -08001353 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001354 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001355 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001356 if (ret != NO_ERROR) {
1357 return ret;
1358 }
1359 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001360 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1361 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001362 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001363 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001364 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001365 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001366 return BAD_VALUE;
1367 }
Eric Laurentc722f302014-12-10 11:21:49 -08001368 if (policyMix != NULL) {
1369 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001370 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1371 // there is an external policy, but this input is attached to a mix of recorders,
1372 // meaning it receives audio injected into the framework, so the recorder doesn't
1373 // know about it and is therefore considered "legacy"
1374 *inputType = API_INPUT_LEGACY;
1375 } else {
1376 // recording a mix of players defined by an external policy, we're rerouting for
1377 // an external policy
1378 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1379 }
Eric Laurentc722f302014-12-10 11:21:49 -08001380 } else if (audio_is_remote_submix_device(device)) {
1381 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001382 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001383 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1384 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001385 } else {
1386 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001387 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001388
Eric Laurent599c7582015-12-07 18:05:55 -08001389 }
1390
1391 *input = getInputForDevice(device, address, session, uid, inputSource,
1392 samplingRate, format, channelMask, flags,
1393 policyMix);
1394 if (*input == AUDIO_IO_HANDLE_NONE) {
1395 mInputRoutes.removeRoute(session);
1396 return INVALID_OPERATION;
1397 }
1398 ALOGV("getInputForAttr() returns input type = %d", *inputType);
1399 return NO_ERROR;
1400}
1401
1402
1403audio_io_handle_t AudioPolicyManager::getInputForDevice(audio_devices_t device,
1404 String8 address,
1405 audio_session_t session,
1406 uid_t uid,
1407 audio_source_t inputSource,
1408 uint32_t samplingRate,
1409 audio_format_t format,
1410 audio_channel_mask_t channelMask,
1411 audio_input_flags_t flags,
1412 AudioMix *policyMix)
1413{
1414 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1415 audio_source_t halInputSource = inputSource;
1416 bool isSoundTrigger = false;
1417
1418 if (inputSource == AUDIO_SOURCE_HOTWORD) {
1419 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1420 if (index >= 0) {
1421 input = mSoundTriggerSessions.valueFor(session);
1422 isSoundTrigger = true;
1423 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1424 ALOGV("SoundTrigger capture on session %d input %d", session, input);
1425 } else {
1426 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001427 }
1428 }
1429
Andy Hungf129b032015-04-07 13:45:50 -07001430 // find a compatible input profile (not necessarily identical in parameters)
1431 sp<IOProfile> profile;
1432 // samplingRate and flags may be updated by getInputProfile
1433 uint32_t profileSamplingRate = samplingRate;
1434 audio_format_t profileFormat = format;
1435 audio_channel_mask_t profileChannelMask = channelMask;
1436 audio_input_flags_t profileFlags = flags;
1437 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001438 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001439 profileSamplingRate, profileFormat, profileChannelMask,
1440 profileFlags);
1441 if (profile != 0) {
1442 break; // success
1443 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1444 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1445 } else { // fail
Eric Laurent599c7582015-12-07 18:05:55 -08001446 ALOGW("getInputForDevice() could not find profile for device 0x%X,"
1447 "samplingRate %u, format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001448 device, samplingRate, format, channelMask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08001449 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001450 }
Eric Laurente552edb2014-03-10 17:42:56 -07001451 }
1452
Eric Laurent322b4d22015-04-03 15:57:54 -07001453 if (profile->getModuleHandle() == 0) {
1454 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08001455 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001456 }
1457
Eric Laurent599c7582015-12-07 18:05:55 -08001458 sp<AudioSession> audioSession = new AudioSession(session,
1459 inputSource,
1460 format,
1461 samplingRate,
1462 channelMask,
1463 flags,
1464 uid,
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001465 isSoundTrigger,
1466 policyMix, mpClientInterface);
Eric Laurent599c7582015-12-07 18:05:55 -08001467
1468// TODO enable input reuse
1469#if 0
1470 // reuse an open input if possible
1471 for (size_t i = 0; i < mInputs.size(); i++) {
1472 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
1473 // reuse input if it shares the same profile and same sound trigger attribute
1474 if (profile == desc->mProfile &&
1475 isSoundTrigger == desc->isSoundTrigger()) {
1476
1477 sp<AudioSession> as = desc->getAudioSession(session);
1478 if (as != 0) {
1479 // do not allow unmatching properties on same session
1480 if (as->matches(audioSession)) {
1481 as->changeOpenCount(1);
1482 } else {
1483 ALOGW("getInputForDevice() record with different attributes"
1484 " exists for session %d", session);
1485 return input;
1486 }
1487 } else {
1488 desc->addAudioSession(session, audioSession);
1489 }
1490 ALOGV("getInputForDevice() reusing input %d", mInputs.keyAt(i));
1491 return mInputs.keyAt(i);
1492 }
1493 }
1494#endif
1495
Eric Laurentcf2c0212014-07-25 16:20:43 -07001496 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001497 config.sample_rate = profileSamplingRate;
1498 config.channel_mask = profileChannelMask;
1499 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001500
Eric Laurent322b4d22015-04-03 15:57:54 -07001501 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurent599c7582015-12-07 18:05:55 -08001502 &input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001503 &config,
1504 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001505 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001506 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001507 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001508
1509 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08001510 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001511 (profileSamplingRate != config.sample_rate) ||
1512 (profileFormat != config.format) ||
1513 (profileChannelMask != config.channel_mask)) {
Eric Laurent599c7582015-12-07 18:05:55 -08001514 ALOGW("getInputForAttr() failed opening input: samplingRate %d"
1515 ", format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001516 samplingRate, format, channelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08001517 if (input != AUDIO_IO_HANDLE_NONE) {
1518 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001519 }
Eric Laurent599c7582015-12-07 18:05:55 -08001520 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001521 }
1522
Eric Laurent1f2f2232014-06-02 12:01:23 -07001523 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Andy Hungf129b032015-04-07 13:45:50 -07001524 inputDesc->mSamplingRate = profileSamplingRate;
1525 inputDesc->mFormat = profileFormat;
1526 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001527 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001528 inputDesc->mPolicyMix = policyMix;
Eric Laurent599c7582015-12-07 18:05:55 -08001529 inputDesc->addAudioSession(session, audioSession);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001530
Eric Laurent599c7582015-12-07 18:05:55 -08001531 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001532 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001533
Eric Laurent599c7582015-12-07 18:05:55 -08001534 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07001535}
1536
Eric Laurent4dc68062014-07-28 17:26:49 -07001537status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1538 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001539{
1540 ALOGV("startInput() input %d", input);
1541 ssize_t index = mInputs.indexOfKey(input);
1542 if (index < 0) {
1543 ALOGW("startInput() unknown input %d", input);
1544 return BAD_VALUE;
1545 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001546 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001547
Eric Laurent599c7582015-12-07 18:05:55 -08001548 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
1549 if (audioSession == 0) {
Eric Laurent4dc68062014-07-28 17:26:49 -07001550 ALOGW("startInput() unknown session %d on input %d", session, input);
1551 return BAD_VALUE;
1552 }
1553
Glenn Kasten74a8e252014-07-24 14:09:55 -07001554 // virtual input devices are compatible with other input devices
François Gaffie53615e22015-03-19 09:24:12 +01001555 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001556
1557 // for a non-virtual input device, check if there is another (non-virtual) active input
François Gaffie53615e22015-03-19 09:24:12 +01001558 audio_io_handle_t activeInput = mInputs.getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001559 if (activeInput != 0 && activeInput != input) {
1560
1561 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1562 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001563 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurent599c7582015-12-07 18:05:55 -08001564 if ((activeDesc->inputSource() == AUDIO_SOURCE_HOTWORD) &&
Eric Laurent64265b22015-09-18 18:32:07 -07001565 !activeDesc->hasPreemptedSession(session)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001566 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent599c7582015-12-07 18:05:55 -08001567 //FIXME: consider all active sessions
1568 AudioSessionCollection activeSessions = activeDesc->getActiveAudioSessions();
1569 audio_session_t activeSession = activeSessions.keyAt(0);
1570 SortedVector<audio_session_t> sessions =
1571 activeDesc->getPreemptedSessions();
Eric Laurent64265b22015-09-18 18:32:07 -07001572 sessions.add(activeSession);
1573 inputDesc->setPreemptedSessions(sessions);
1574 stopInput(activeInput, activeSession);
1575 releaseInput(activeInput, activeSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001576 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001577 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001578 return INVALID_OPERATION;
1579 }
1580 }
Eric Laurentc0a889f2015-10-14 14:36:34 -07001581
1582 // Do not allow capture if an active voice call is using a software patch and
1583 // the call TX source device is on the same HW module.
1584 // FIXME: would be better to refine to only inputs whose profile connects to the
1585 // call TX device but this information is not in the audio patch
1586 if (mCallTxPatch != 0 &&
1587 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1588 return INVALID_OPERATION;
1589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590 }
1591
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001592 // Routing?
1593 mInputRoutes.incRouteActivity(session);
1594
Eric Laurent599c7582015-12-07 18:05:55 -08001595 if (!inputDesc->isActive() || mInputRoutes.hasRouteChanged(session)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001596 // if input maps to a dynamic policy with an activity listener, notify of state change
1597 if ((inputDesc->mPolicyMix != NULL)
Jean-Michel Trivif613d422015-04-23 18:41:29 -07001598 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001599 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1600 MIX_STATE_MIXING);
1601 }
1602
François Gaffie53615e22015-03-19 09:24:12 +01001603 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001604 SoundTrigger::setCaptureState(true);
1605 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001606 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001607
Eric Laurentc722f302014-12-10 11:21:49 -08001608 // automatically enable the remote submix output when input is started if not
1609 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001610 // For remote submix (a virtual device), we open only one input per capture request.
1611 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001612 String8 address = String8("");
1613 if (inputDesc->mPolicyMix == NULL) {
1614 address = String8("0");
1615 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1616 address = inputDesc->mPolicyMix->mRegistrationId;
1617 }
1618 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001619 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001620 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001621 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001622 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001623 }
Eric Laurente552edb2014-03-10 17:42:56 -07001624 }
1625
Eric Laurent599c7582015-12-07 18:05:55 -08001626 ALOGV("AudioPolicyManager::startInput() input source = %d", audioSession->inputSource());
Eric Laurente552edb2014-03-10 17:42:56 -07001627
Eric Laurent599c7582015-12-07 18:05:55 -08001628 audioSession->changeActiveCount(1);
Eric Laurente552edb2014-03-10 17:42:56 -07001629 return NO_ERROR;
1630}
1631
Eric Laurent4dc68062014-07-28 17:26:49 -07001632status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1633 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001634{
1635 ALOGV("stopInput() input %d", input);
1636 ssize_t index = mInputs.indexOfKey(input);
1637 if (index < 0) {
1638 ALOGW("stopInput() unknown input %d", input);
1639 return BAD_VALUE;
1640 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001641 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001642
Eric Laurent599c7582015-12-07 18:05:55 -08001643 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001644 if (index < 0) {
1645 ALOGW("stopInput() unknown session %d on input %d", session, input);
1646 return BAD_VALUE;
1647 }
1648
Eric Laurent599c7582015-12-07 18:05:55 -08001649 if (audioSession->activeCount() == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001650 ALOGW("stopInput() input %d already stopped", input);
1651 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001652 }
1653
Eric Laurent599c7582015-12-07 18:05:55 -08001654 audioSession->changeActiveCount(-1);
Paul McLean466dc8e2015-04-17 13:15:36 -06001655
1656 // Routing?
1657 mInputRoutes.decRouteActivity(session);
1658
Eric Laurent599c7582015-12-07 18:05:55 -08001659 if (!inputDesc->isActive()) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001660 // if input maps to a dynamic policy with an activity listener, notify of state change
1661 if ((inputDesc->mPolicyMix != NULL)
Jean-Michel Trivif613d422015-04-23 18:41:29 -07001662 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001663 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1664 MIX_STATE_IDLE);
1665 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001666
Eric Laurentc722f302014-12-10 11:21:49 -08001667 // automatically disable the remote submix output when input is stopped if not
1668 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001669 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001670 String8 address = String8("");
1671 if (inputDesc->mPolicyMix == NULL) {
1672 address = String8("0");
1673 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1674 address = inputDesc->mPolicyMix->mRegistrationId;
1675 }
1676 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001677 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001678 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001679 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001680 }
Eric Laurente552edb2014-03-10 17:42:56 -07001681 }
1682
Eric Laurent1c333e22014-05-20 10:48:17 -07001683 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001684
François Gaffie53615e22015-03-19 09:24:12 +01001685 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001686 SoundTrigger::setCaptureState(false);
1687 }
Eric Laurent64265b22015-09-18 18:32:07 -07001688 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001689 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001690 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001691}
1692
Eric Laurent4dc68062014-07-28 17:26:49 -07001693void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1694 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001695{
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08001696
Eric Laurente552edb2014-03-10 17:42:56 -07001697 ALOGV("releaseInput() %d", input);
1698 ssize_t index = mInputs.indexOfKey(input);
1699 if (index < 0) {
1700 ALOGW("releaseInput() releasing unknown input %d", input);
1701 return;
1702 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001703
1704 // Routing
1705 mInputRoutes.removeRoute(session);
1706
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001707 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1708 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001709
Eric Laurent599c7582015-12-07 18:05:55 -08001710 sp<AudioSession> audioSession = inputDesc->getAudioSession(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001711 if (index < 0) {
1712 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1713 return;
1714 }
Eric Laurent599c7582015-12-07 18:05:55 -08001715
1716 if (audioSession->openCount() == 0) {
1717 ALOGW("releaseInput() invalid open count %d on session %d",
1718 audioSession->openCount(), session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001719 return;
1720 }
Eric Laurent599c7582015-12-07 18:05:55 -08001721
1722 if (audioSession->changeOpenCount(-1) == 0) {
1723 inputDesc->removeAudioSession(session);
1724 }
1725
Jean-Michel Trivi65bfe912015-12-04 15:56:47 -08001726 if (inputDesc->getOpenRefCount() > 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001727 ALOGV("releaseInput() exit > 0");
1728 return;
1729 }
1730
Eric Laurent05b90f82014-08-27 15:32:29 -07001731 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001732 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001733 ALOGV("releaseInput() exit");
1734}
1735
Eric Laurentd4692962014-05-05 18:13:44 -07001736void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001737 bool patchRemoved = false;
1738
Eric Laurentd4692962014-05-05 18:13:44 -07001739 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001740 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1741 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1742 if (patch_index >= 0) {
1743 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1744 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1745 mAudioPatches.removeItemsAt(patch_index);
1746 patchRemoved = true;
1747 }
Eric Laurentd4692962014-05-05 18:13:44 -07001748 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1749 }
1750 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001751 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001752
1753 if (patchRemoved) {
1754 mpClientInterface->onAudioPatchListUpdate();
1755 }
Eric Laurentd4692962014-05-05 18:13:44 -07001756}
1757
Eric Laurente0720872014-03-11 09:30:41 -07001758void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001759 int indexMin,
1760 int indexMax)
1761{
1762 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffie2110e042015-03-24 08:41:51 +01001763 mEngine->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001764 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1765 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffie2110e042015-03-24 08:41:51 +01001766 mEngine->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001767 }
Eric Laurente552edb2014-03-10 17:42:56 -07001768}
1769
Eric Laurente0720872014-03-11 09:30:41 -07001770status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001771 int index,
1772 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001773{
1774
Eric Laurentc75307b2015-03-17 15:29:32 -07001775 if ((index < mStreams.valueFor(stream).getVolumeIndexMin()) ||
1776 (index > mStreams.valueFor(stream).getVolumeIndexMax())) {
Eric Laurente552edb2014-03-10 17:42:56 -07001777 return BAD_VALUE;
1778 }
1779 if (!audio_is_output_device(device)) {
1780 return BAD_VALUE;
1781 }
1782
1783 // Force max volume if stream cannot be muted
Eric Laurentc75307b2015-03-17 15:29:32 -07001784 if (!mStreams.canBeMuted(stream)) index = mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07001785
1786 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1787 stream, device, index);
1788
1789 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1790 // clear all device specific values
1791 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffiedfd74092015-03-19 12:10:59 +01001792 mStreams.clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001793 }
François Gaffiedfd74092015-03-19 12:10:59 +01001794 mStreams.addCurrentVolumeIndex(stream, device, index);
Eric Laurente552edb2014-03-10 17:42:56 -07001795
Eric Laurent31551f82014-10-10 18:21:56 -07001796 // update volume on all outputs whose current device is also selected by the same
1797 // strategy as the device specified by the caller
1798 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001799
1800
1801 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1802 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1803 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffiedfd74092015-03-19 12:10:59 +01001804 mStreams.addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001805 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1806 }
1807 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1808 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001809 return NO_ERROR;
1810 }
Eric Laurente552edb2014-03-10 17:42:56 -07001811 status_t status = NO_ERROR;
1812 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001813 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1814 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001815 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001816 status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07001817 if (volStatus != NO_ERROR) {
1818 status = volStatus;
1819 }
1820 }
Jean-Michel Triviaf20bc22015-09-14 16:37:07 -07001821 if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
1822 ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
1823 {
Eric Laurent223fd5c2014-11-11 13:43:36 -08001824 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
Eric Laurentc75307b2015-03-17 15:29:32 -07001825 index, desc, curDevice);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001826 }
Eric Laurente552edb2014-03-10 17:42:56 -07001827 }
1828 return status;
1829}
1830
Eric Laurente0720872014-03-11 09:30:41 -07001831status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001832 int *index,
1833 audio_devices_t device)
1834{
1835 if (index == NULL) {
1836 return BAD_VALUE;
1837 }
1838 if (!audio_is_output_device(device)) {
1839 return BAD_VALUE;
1840 }
1841 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1842 // the strategy the stream belongs to.
1843 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1844 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1845 }
François Gaffiedfd74092015-03-19 12:10:59 +01001846 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001847
Eric Laurentc75307b2015-03-17 15:29:32 -07001848 *index = mStreams.valueFor(stream).getVolumeIndex(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001849 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1850 return NO_ERROR;
1851}
1852
Eric Laurente0720872014-03-11 09:30:41 -07001853audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001854 const SortedVector<audio_io_handle_t>& outputs)
1855{
1856 // select one output among several suitable for global effects.
1857 // The priority is as follows:
1858 // 1: An offloaded output. If the effect ends up not being offloadable,
1859 // AudioFlinger will invalidate the track and the offloaded output
1860 // will be closed causing the effect to be moved to a PCM output.
1861 // 2: A deep buffer output
1862 // 3: the first output in the list
1863
1864 if (outputs.size() == 0) {
1865 return 0;
1866 }
1867
1868 audio_io_handle_t outputOffloaded = 0;
1869 audio_io_handle_t outputDeepBuffer = 0;
1870
1871 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001872 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001873 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001874 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1875 outputOffloaded = outputs[i];
1876 }
1877 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1878 outputDeepBuffer = outputs[i];
1879 }
1880 }
1881
1882 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1883 outputOffloaded, outputDeepBuffer);
1884 if (outputOffloaded != 0) {
1885 return outputOffloaded;
1886 }
1887 if (outputDeepBuffer != 0) {
1888 return outputDeepBuffer;
1889 }
1890
1891 return outputs[0];
1892}
1893
Eric Laurente0720872014-03-11 09:30:41 -07001894audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001895{
1896 // apply simple rule where global effects are attached to the same output as MUSIC streams
1897
Eric Laurent3b73df72014-03-11 09:06:29 -07001898 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001899 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1900 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1901
1902 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1903 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1904 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1905
1906 return output;
1907}
1908
Eric Laurente0720872014-03-11 09:30:41 -07001909status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001910 audio_io_handle_t io,
1911 uint32_t strategy,
1912 int session,
1913 int id)
1914{
1915 ssize_t index = mOutputs.indexOfKey(io);
1916 if (index < 0) {
1917 index = mInputs.indexOfKey(io);
1918 if (index < 0) {
1919 ALOGW("registerEffect() unknown io %d", io);
1920 return INVALID_OPERATION;
1921 }
1922 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001923 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001924}
1925
Eric Laurentc75307b2015-03-17 15:29:32 -07001926bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1927{
1928 return mOutputs.isStreamActive(stream, inPastMs);
1929}
1930
1931bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1932{
1933 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1934}
1935
Eric Laurente0720872014-03-11 09:30:41 -07001936bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001937{
1938 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001939 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08001940 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001941 return true;
1942 }
1943 }
1944 return false;
1945}
1946
Eric Laurent275e8e92014-11-30 15:14:47 -08001947// Register a list of custom mixes with their attributes and format.
1948// When a mix is registered, corresponding input and output profiles are
1949// added to the remote submix hw module. The profile contains only the
1950// parameters (sampling rate, format...) specified by the mix.
1951// The corresponding input remote submix device is also connected.
1952//
1953// When a remote submix device is connected, the address is checked to select the
1954// appropriate profile and the corresponding input or output stream is opened.
1955//
1956// When capture starts, getInputForAttr() will:
1957// - 1 look for a mix matching the address passed in attribtutes tags if any
1958// - 2 if none found, getDeviceForInputSource() will:
1959// - 2.1 look for a mix matching the attributes source
1960// - 2.2 if none found, default to device selection by policy rules
1961// At this time, the corresponding output remote submix device is also connected
1962// and active playback use cases can be transferred to this mix if needed when reconnecting
1963// after AudioTracks are invalidated
1964//
1965// When playback starts, getOutputForAttr() will:
1966// - 1 look for a mix matching the address passed in attribtutes tags if any
1967// - 2 if none found, look for a mix matching the attributes usage
1968// - 3 if none found, default to device and output selection by policy rules.
1969
1970status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
1971{
1972 sp<HwModule> module;
1973 for (size_t i = 0; i < mHwModules.size(); i++) {
1974 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1975 mHwModules[i]->mHandle != 0) {
1976 module = mHwModules[i];
1977 break;
1978 }
1979 }
1980
1981 if (module == 0) {
1982 return INVALID_OPERATION;
1983 }
1984
Eric Laurent7b279bb2015-12-14 10:18:23 -08001985 ALOGV("registerPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08001986
1987 for (size_t i = 0; i < mixes.size(); i++) {
1988 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01001989
1990 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001991 continue;
1992 }
1993 audio_config_t outputConfig = mixes[i].mFormat;
1994 audio_config_t inputConfig = mixes[i].mFormat;
1995 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
1996 // stereo and let audio flinger do the channel conversion if needed.
1997 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1998 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
1999 module->addOutputProfile(address, &outputConfig,
2000 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2001 module->addInputProfile(address, &inputConfig,
2002 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01002003
Eric Laurentc722f302014-12-10 11:21:49 -08002004 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002005 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002006 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002007 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002008 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002009 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002010 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002011 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002012 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002013 }
2014 return NO_ERROR;
2015}
2016
2017status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2018{
2019 sp<HwModule> module;
2020 for (size_t i = 0; i < mHwModules.size(); i++) {
2021 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2022 mHwModules[i]->mHandle != 0) {
2023 module = mHwModules[i];
2024 break;
2025 }
2026 }
2027
2028 if (module == 0) {
2029 return INVALID_OPERATION;
2030 }
2031
Eric Laurent7b279bb2015-12-14 10:18:23 -08002032 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Eric Laurent275e8e92014-11-30 15:14:47 -08002033
2034 for (size_t i = 0; i < mixes.size(); i++) {
2035 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01002036
2037 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002038 continue;
2039 }
2040
Eric Laurentc722f302014-12-10 11:21:49 -08002041 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2042 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2043 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002044 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002045 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002046 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08002047 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002048
2049 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2050 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2051 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002052 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002053 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08002054 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08002055 }
2056 module->removeOutputProfile(address);
2057 module->removeInputProfile(address);
2058 }
2059 return NO_ERROR;
2060}
2061
Eric Laurente552edb2014-03-10 17:42:56 -07002062
Eric Laurente0720872014-03-11 09:30:41 -07002063status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002064{
2065 const size_t SIZE = 256;
2066 char buffer[SIZE];
2067 String8 result;
2068
2069 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2070 result.append(buffer);
2071
Eric Laurent87ffa392015-05-22 10:32:38 -07002072 snprintf(buffer, SIZE, " Primary Output: %d\n",
2073 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002074 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002075 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002076 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002077 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002078 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002079 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002080 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002081 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002082 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002083 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002084 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002085 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002086 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002087 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002088 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002089 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002090 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002091 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2092 result.append(buffer);
Andy Hung2ddee192015-12-18 17:34:44 -08002093 snprintf(buffer, SIZE, " Master mono: %s\n", mMasterMono ? "on" : "off");
2094 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002095
François Gaffie2110e042015-03-24 08:41:51 +01002096 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002097
François Gaffie112b0af2015-11-19 16:13:25 +01002098 mAvailableOutputDevices.dump(fd, String8("Available output"));
2099 mAvailableInputDevices.dump(fd, String8("Available input"));
François Gaffie53615e22015-03-19 09:24:12 +01002100 mHwModules.dump(fd);
2101 mOutputs.dump(fd);
2102 mInputs.dump(fd);
François Gaffiedfd74092015-03-19 12:10:59 +01002103 mStreams.dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002104 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002105 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002106
2107 return NO_ERROR;
2108}
2109
2110// This function checks for the parameters which can be offloaded.
2111// This can be enhanced depending on the capability of the DSP and policy
2112// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002113bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002114{
2115 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002116 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002117 offloadInfo.sample_rate, offloadInfo.channel_mask,
2118 offloadInfo.format,
2119 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2120 offloadInfo.has_video);
2121
Andy Hung2ddee192015-12-18 17:34:44 -08002122 if (mMasterMono) {
2123 return false; // no offloading if mono is set.
2124 }
2125
Eric Laurente552edb2014-03-10 17:42:56 -07002126 // Check if offload has been disabled
2127 char propValue[PROPERTY_VALUE_MAX];
2128 if (property_get("audio.offload.disable", propValue, "0")) {
2129 if (atoi(propValue) != 0) {
2130 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2131 return false;
2132 }
2133 }
2134
2135 // Check if stream type is music, then only allow offload as of now.
2136 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2137 {
2138 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2139 return false;
2140 }
2141
2142 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002143 const bool allowOffloadWithVideo =
2144 property_get_bool("audio.offload.video", false /* default_value */);
2145 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002146 ALOGV("isOffloadSupported: has_video == true, returning false");
2147 return false;
2148 }
2149
2150 //If duration is less than minimum value defined in property, return false
2151 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2152 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2153 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2154 return false;
2155 }
2156 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2157 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2158 return false;
2159 }
2160
2161 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2162 // creating an offloaded track and tearing it down immediately after start when audioflinger
2163 // detects there is an active non offloadable effect.
2164 // FIXME: We should check the audio session here but we do not have it in this context.
2165 // This may prevent offloading in rare situations where effects are left active by apps
2166 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002167 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002168 return false;
2169 }
2170
2171 // See if there is a profile to support this.
2172 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002173 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002174 offloadInfo.sample_rate,
2175 offloadInfo.format,
2176 offloadInfo.channel_mask,
2177 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002178 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2179 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002180}
2181
Eric Laurent6a94d692014-05-20 11:18:06 -07002182status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2183 audio_port_type_t type,
2184 unsigned int *num_ports,
2185 struct audio_port *ports,
2186 unsigned int *generation)
2187{
2188 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2189 generation == NULL) {
2190 return BAD_VALUE;
2191 }
2192 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2193 if (ports == NULL) {
2194 *num_ports = 0;
2195 }
2196
2197 size_t portsWritten = 0;
2198 size_t portsMax = *num_ports;
2199 *num_ports = 0;
2200 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2201 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2202 for (size_t i = 0;
2203 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2204 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2205 }
2206 *num_ports += mAvailableOutputDevices.size();
2207 }
2208 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2209 for (size_t i = 0;
2210 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2211 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2212 }
2213 *num_ports += mAvailableInputDevices.size();
2214 }
2215 }
2216 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2217 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2218 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2219 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2220 }
2221 *num_ports += mInputs.size();
2222 }
2223 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002224 size_t numOutputs = 0;
2225 for (size_t i = 0; i < mOutputs.size(); i++) {
2226 if (!mOutputs[i]->isDuplicated()) {
2227 numOutputs++;
2228 if (portsWritten < portsMax) {
2229 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2230 }
2231 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002232 }
Eric Laurent84c70242014-06-23 08:46:27 -07002233 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002234 }
2235 }
2236 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002237 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002238 return NO_ERROR;
2239}
2240
2241status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2242{
2243 return NO_ERROR;
2244}
2245
Eric Laurent6a94d692014-05-20 11:18:06 -07002246status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2247 audio_patch_handle_t *handle,
2248 uid_t uid)
2249{
2250 ALOGV("createAudioPatch()");
2251
2252 if (handle == NULL || patch == NULL) {
2253 return BAD_VALUE;
2254 }
2255 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2256
Eric Laurent874c42872014-08-08 15:13:39 -07002257 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2258 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2259 return BAD_VALUE;
2260 }
2261 // only one source per audio patch supported for now
2262 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002263 return INVALID_OPERATION;
2264 }
Eric Laurent874c42872014-08-08 15:13:39 -07002265
2266 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002267 return INVALID_OPERATION;
2268 }
Eric Laurent874c42872014-08-08 15:13:39 -07002269 for (size_t i = 0; i < patch->num_sinks; i++) {
2270 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2271 return INVALID_OPERATION;
2272 }
2273 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002274
2275 sp<AudioPatch> patchDesc;
2276 ssize_t index = mAudioPatches.indexOfKey(*handle);
2277
Eric Laurent6a94d692014-05-20 11:18:06 -07002278 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2279 patch->sources[0].role,
2280 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002281#if LOG_NDEBUG == 0
2282 for (size_t i = 0; i < patch->num_sinks; i++) {
Eric Laurent7b279bb2015-12-14 10:18:23 -08002283 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
Eric Laurent874c42872014-08-08 15:13:39 -07002284 patch->sinks[i].role,
2285 patch->sinks[i].type);
2286 }
2287#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002288
2289 if (index >= 0) {
2290 patchDesc = mAudioPatches.valueAt(index);
2291 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2292 mUidCached, patchDesc->mUid, uid);
2293 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2294 return INVALID_OPERATION;
2295 }
2296 } else {
2297 *handle = 0;
2298 }
2299
2300 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002301 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002302 if (outputDesc == NULL) {
2303 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2304 return BAD_VALUE;
2305 }
Eric Laurent84c70242014-06-23 08:46:27 -07002306 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2307 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002308 if (patchDesc != 0) {
2309 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2310 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2311 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2312 return BAD_VALUE;
2313 }
2314 }
Eric Laurent874c42872014-08-08 15:13:39 -07002315 DeviceVector devices;
2316 for (size_t i = 0; i < patch->num_sinks; i++) {
2317 // Only support mix to devices connection
2318 // TODO add support for mix to mix connection
2319 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2320 ALOGV("createAudioPatch() source mix but sink is not a device");
2321 return INVALID_OPERATION;
2322 }
2323 sp<DeviceDescriptor> devDesc =
2324 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2325 if (devDesc == 0) {
2326 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2327 return BAD_VALUE;
2328 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002329
François Gaffie53615e22015-03-19 09:24:12 +01002330 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002331 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002332 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002333 NULL, // updatedSamplingRate
2334 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002335 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002336 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002337 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002338 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002339 ALOGV("createAudioPatch() profile not supported for device %08x",
2340 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002341 return INVALID_OPERATION;
2342 }
2343 devices.add(devDesc);
2344 }
2345 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002346 return INVALID_OPERATION;
2347 }
Eric Laurent874c42872014-08-08 15:13:39 -07002348
Eric Laurent6a94d692014-05-20 11:18:06 -07002349 // TODO: reconfigure output format and channels here
2350 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002351 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002352 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002353 index = mAudioPatches.indexOfKey(*handle);
2354 if (index >= 0) {
2355 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2356 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2357 }
2358 patchDesc = mAudioPatches.valueAt(index);
2359 patchDesc->mUid = uid;
2360 ALOGV("createAudioPatch() success");
2361 } else {
2362 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2363 return INVALID_OPERATION;
2364 }
2365 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2366 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2367 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002368 // only one sink supported when connecting an input device to a mix
2369 if (patch->num_sinks > 1) {
2370 return INVALID_OPERATION;
2371 }
François Gaffie53615e22015-03-19 09:24:12 +01002372 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002373 if (inputDesc == NULL) {
2374 return BAD_VALUE;
2375 }
2376 if (patchDesc != 0) {
2377 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2378 return BAD_VALUE;
2379 }
2380 }
2381 sp<DeviceDescriptor> devDesc =
2382 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2383 if (devDesc == 0) {
2384 return BAD_VALUE;
2385 }
2386
François Gaffie53615e22015-03-19 09:24:12 +01002387 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002388 devDesc->mAddress,
2389 patch->sinks[0].sample_rate,
2390 NULL, /*updatedSampleRate*/
2391 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002392 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002393 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002394 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002395 // FIXME for the parameter type,
2396 // and the NONE
2397 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002398 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002399 return INVALID_OPERATION;
2400 }
2401 // TODO: reconfigure output format and channels here
2402 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002403 devDesc->type(), inputDesc->mIoHandle);
2404 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002405 index = mAudioPatches.indexOfKey(*handle);
2406 if (index >= 0) {
2407 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2408 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2409 }
2410 patchDesc = mAudioPatches.valueAt(index);
2411 patchDesc->mUid = uid;
2412 ALOGV("createAudioPatch() success");
2413 } else {
2414 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2415 return INVALID_OPERATION;
2416 }
2417 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2418 // device to device connection
2419 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002420 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002421 return BAD_VALUE;
2422 }
2423 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002424 sp<DeviceDescriptor> srcDeviceDesc =
2425 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002426 if (srcDeviceDesc == 0) {
2427 return BAD_VALUE;
2428 }
Eric Laurent874c42872014-08-08 15:13:39 -07002429
Eric Laurent6a94d692014-05-20 11:18:06 -07002430 //update source and sink with our own data as the data passed in the patch may
2431 // be incomplete.
2432 struct audio_patch newPatch = *patch;
2433 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002434
Eric Laurent874c42872014-08-08 15:13:39 -07002435 for (size_t i = 0; i < patch->num_sinks; i++) {
2436 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2437 ALOGV("createAudioPatch() source device but one sink is not a device");
2438 return INVALID_OPERATION;
2439 }
2440
2441 sp<DeviceDescriptor> sinkDeviceDesc =
2442 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2443 if (sinkDeviceDesc == 0) {
2444 return BAD_VALUE;
2445 }
2446 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2447
Eric Laurent3bcf8592015-04-03 12:13:24 -07002448 // create a software bridge in PatchPanel if:
2449 // - source and sink devices are on differnt HW modules OR
2450 // - audio HAL version is < 3.0
2451 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002452 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002453 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002454 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002455 return INVALID_OPERATION;
2456 }
Eric Laurent874c42872014-08-08 15:13:39 -07002457 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002458 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002459 // if the sink device is reachable via an opened output stream, request to go via
2460 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002461 audio_io_handle_t output = selectOutput(outputs,
2462 AUDIO_OUTPUT_FLAG_NONE,
2463 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002464 if (output != AUDIO_IO_HANDLE_NONE) {
2465 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2466 if (outputDesc->isDuplicated()) {
2467 return INVALID_OPERATION;
2468 }
2469 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002470 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002471 newPatch.num_sources = 2;
2472 }
Eric Laurent83b88082014-06-20 18:31:16 -07002473 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002474 }
2475 // TODO: check from routing capabilities in config file and other conflicting patches
2476
2477 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2478 if (index >= 0) {
2479 afPatchHandle = patchDesc->mAfPatchHandle;
2480 }
2481
2482 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2483 &afPatchHandle,
2484 0);
2485 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2486 status, afPatchHandle);
2487 if (status == NO_ERROR) {
2488 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002489 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002490 addAudioPatch(patchDesc->mHandle, patchDesc);
2491 } else {
2492 patchDesc->mPatch = newPatch;
2493 }
2494 patchDesc->mAfPatchHandle = afPatchHandle;
2495 *handle = patchDesc->mHandle;
2496 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002497 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002498 } else {
2499 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2500 status);
2501 return INVALID_OPERATION;
2502 }
2503 } else {
2504 return BAD_VALUE;
2505 }
2506 } else {
2507 return BAD_VALUE;
2508 }
2509 return NO_ERROR;
2510}
2511
2512status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2513 uid_t uid)
2514{
2515 ALOGV("releaseAudioPatch() patch %d", handle);
2516
2517 ssize_t index = mAudioPatches.indexOfKey(handle);
2518
2519 if (index < 0) {
2520 return BAD_VALUE;
2521 }
2522 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2523 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2524 mUidCached, patchDesc->mUid, uid);
2525 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2526 return INVALID_OPERATION;
2527 }
2528
2529 struct audio_patch *patch = &patchDesc->mPatch;
2530 patchDesc->mUid = mUidCached;
2531 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002533 if (outputDesc == NULL) {
2534 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2535 return BAD_VALUE;
2536 }
2537
Eric Laurentc75307b2015-03-17 15:29:32 -07002538 setOutputDevice(outputDesc,
2539 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002540 true,
2541 0,
2542 NULL);
2543 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2544 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002545 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002546 if (inputDesc == NULL) {
2547 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2548 return BAD_VALUE;
2549 }
2550 setInputDevice(inputDesc->mIoHandle,
2551 getNewInputDevice(inputDesc->mIoHandle),
2552 true,
2553 NULL);
2554 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2555 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2556 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2557 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2558 status, patchDesc->mAfPatchHandle);
2559 removeAudioPatch(patchDesc->mHandle);
2560 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002561 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002562 } else {
2563 return BAD_VALUE;
2564 }
2565 } else {
2566 return BAD_VALUE;
2567 }
2568 return NO_ERROR;
2569}
2570
2571status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2572 struct audio_patch *patches,
2573 unsigned int *generation)
2574{
François Gaffie53615e22015-03-19 09:24:12 +01002575 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002576 return BAD_VALUE;
2577 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002578 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002579 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002580}
2581
Eric Laurente1715a42014-05-20 11:30:42 -07002582status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002583{
Eric Laurente1715a42014-05-20 11:30:42 -07002584 ALOGV("setAudioPortConfig()");
2585
2586 if (config == NULL) {
2587 return BAD_VALUE;
2588 }
2589 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2590 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002591 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2592 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002593 }
2594
Eric Laurenta121f902014-06-03 13:32:54 -07002595 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002596 if (config->type == AUDIO_PORT_TYPE_MIX) {
2597 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002598 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002599 if (outputDesc == NULL) {
2600 return BAD_VALUE;
2601 }
Eric Laurent84c70242014-06-23 08:46:27 -07002602 ALOG_ASSERT(!outputDesc->isDuplicated(),
2603 "setAudioPortConfig() called on duplicated output %d",
2604 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002605 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002606 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002607 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002608 if (inputDesc == NULL) {
2609 return BAD_VALUE;
2610 }
Eric Laurenta121f902014-06-03 13:32:54 -07002611 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002612 } else {
2613 return BAD_VALUE;
2614 }
2615 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2616 sp<DeviceDescriptor> deviceDesc;
2617 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2618 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2619 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2620 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2621 } else {
2622 return BAD_VALUE;
2623 }
2624 if (deviceDesc == NULL) {
2625 return BAD_VALUE;
2626 }
Eric Laurenta121f902014-06-03 13:32:54 -07002627 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002628 } else {
2629 return BAD_VALUE;
2630 }
2631
Eric Laurenta121f902014-06-03 13:32:54 -07002632 struct audio_port_config backupConfig;
2633 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2634 if (status == NO_ERROR) {
2635 struct audio_port_config newConfig;
2636 audioPortConfig->toAudioPortConfig(&newConfig, config);
2637 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002638 }
Eric Laurenta121f902014-06-03 13:32:54 -07002639 if (status != NO_ERROR) {
2640 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002641 }
Eric Laurente1715a42014-05-20 11:30:42 -07002642
2643 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002644}
2645
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002646void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2647{
Eric Laurentd60560a2015-04-10 11:31:20 -07002648 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002649 clearAudioPatches(uid);
2650 clearSessionRoutes(uid);
2651}
2652
Eric Laurent6a94d692014-05-20 11:18:06 -07002653void AudioPolicyManager::clearAudioPatches(uid_t uid)
2654{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002655 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002656 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2657 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002658 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002659 }
2660 }
2661}
2662
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002663void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2664 audio_io_handle_t ouptutToSkip)
2665{
2666 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2667 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2668 for (size_t j = 0; j < mOutputs.size(); j++) {
2669 if (mOutputs.keyAt(j) == ouptutToSkip) {
2670 continue;
2671 }
2672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2673 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2674 continue;
2675 }
2676 // If the default device for this strategy is on another output mix,
2677 // invalidate all tracks in this strategy to force re connection.
2678 // Otherwise select new device on the output mix.
2679 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
2680 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
2681 if (stream == AUDIO_STREAM_PATCH) {
2682 continue;
2683 }
2684 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2685 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2686 }
2687 }
2688 } else {
2689 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2690 setOutputDevice(outputDesc, newDevice, false);
2691 }
2692 }
2693}
2694
2695void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2696{
2697 // remove output routes associated with this uid
2698 SortedVector<routing_strategy> affectedStrategies;
2699 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2700 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2701 if (route->mUid == uid) {
2702 mOutputRoutes.removeItemsAt(i);
2703 if (route->mDeviceDescriptor != 0) {
2704 affectedStrategies.add(getStrategy(route->mStreamType));
2705 }
2706 }
2707 }
2708 // reroute outputs if necessary
2709 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2710 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2711 }
2712
2713 // remove input routes associated with this uid
2714 SortedVector<audio_source_t> affectedSources;
2715 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2716 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2717 if (route->mUid == uid) {
2718 mInputRoutes.removeItemsAt(i);
2719 if (route->mDeviceDescriptor != 0) {
2720 affectedSources.add(route->mSource);
2721 }
2722 }
2723 }
2724 // reroute inputs if necessary
2725 SortedVector<audio_io_handle_t> inputsToClose;
2726 for (size_t i = 0; i < mInputs.size(); i++) {
2727 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08002728 if (affectedSources.indexOf(inputDesc->inputSource()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002729 inputsToClose.add(inputDesc->mIoHandle);
2730 }
2731 }
2732 for (size_t i = 0; i < inputsToClose.size(); i++) {
2733 closeInput(inputsToClose[i]);
2734 }
2735}
2736
Eric Laurentd60560a2015-04-10 11:31:20 -07002737void AudioPolicyManager::clearAudioSources(uid_t uid)
2738{
2739 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2740 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2741 if (sourceDesc->mUid == uid) {
2742 stopAudioSource(mAudioSources.keyAt(i));
2743 }
2744 }
2745}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002746
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002747status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2748 audio_io_handle_t *ioHandle,
2749 audio_devices_t *device)
2750{
2751 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2752 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002753 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002754
François Gaffiedf372692015-03-19 10:43:27 +01002755 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002756}
2757
Eric Laurentd60560a2015-04-10 11:31:20 -07002758status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2759 const audio_attributes_t *attributes,
2760 audio_io_handle_t *handle,
2761 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002762{
Eric Laurentd60560a2015-04-10 11:31:20 -07002763 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2764 if (source == NULL || attributes == NULL || handle == NULL) {
2765 return BAD_VALUE;
2766 }
2767
2768 *handle = AUDIO_IO_HANDLE_NONE;
2769
2770 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2771 source->type != AUDIO_PORT_TYPE_DEVICE) {
2772 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2773 return INVALID_OPERATION;
2774 }
2775
2776 sp<DeviceDescriptor> srcDeviceDesc =
2777 mAvailableInputDevices.getDevice(source->ext.device.type,
2778 String8(source->ext.device.address));
2779 if (srcDeviceDesc == 0) {
2780 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2781 return BAD_VALUE;
2782 }
2783 sp<AudioSourceDescriptor> sourceDesc =
2784 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2785
2786 struct audio_patch dummyPatch;
2787 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2788 sourceDesc->mPatchDesc = patchDesc;
2789
2790 status_t status = connectAudioSource(sourceDesc);
2791 if (status == NO_ERROR) {
2792 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2793 *handle = sourceDesc->getHandle();
2794 }
2795 return status;
2796}
2797
2798status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2799{
2800 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2801
2802 // make sure we only have one patch per source.
2803 disconnectAudioSource(sourceDesc);
2804
2805 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2806 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2807 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2808
2809 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2810 sp<DeviceDescriptor> sinkDeviceDesc =
2811 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2812
2813 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2814 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2815
2816 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2817 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002818 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002819 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2820 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2821 // create patch between src device and output device
2822 // create Hwoutput and add to mHwOutputs
2823 } else {
2824 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2825 audio_io_handle_t output =
2826 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2827 if (output == AUDIO_IO_HANDLE_NONE) {
2828 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2829 return INVALID_OPERATION;
2830 }
2831 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2832 if (outputDesc->isDuplicated()) {
2833 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2834 return INVALID_OPERATION;
2835 }
2836 // create a special patch with no sink and two sources:
2837 // - the second source indicates to PatchPanel through which output mix this patch should
2838 // be connected as well as the stream type for volume control
2839 // - the sink is defined by whatever output device is currently selected for the output
2840 // though which this patch is routed.
2841 patch->num_sinks = 0;
2842 patch->num_sources = 2;
2843 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2844 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2845 patch->sources[1].ext.mix.usecase.stream = stream;
2846 status_t status = mpClientInterface->createAudioPatch(patch,
2847 &afPatchHandle,
2848 0);
2849 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
2850 status, afPatchHandle);
2851 if (status != NO_ERROR) {
2852 ALOGW("%s patch panel could not connect device patch, error %d",
2853 __FUNCTION__, status);
2854 return INVALID_OPERATION;
2855 }
2856 uint32_t delayMs = 0;
2857 status = startSource(outputDesc, stream, sinkDevice, &delayMs);
2858
2859 if (status != NO_ERROR) {
2860 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
2861 return status;
2862 }
2863 sourceDesc->mSwOutput = outputDesc;
2864 if (delayMs != 0) {
2865 usleep(delayMs * 1000);
2866 }
2867 }
2868
2869 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
2870 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
2871
2872 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07002873}
2874
Eric Laurent493404d2015-04-21 15:07:36 -07002875status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002876{
Eric Laurentd60560a2015-04-10 11:31:20 -07002877 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
2878 ALOGV("%s handle %d", __FUNCTION__, handle);
2879 if (sourceDesc == 0) {
2880 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
2881 return BAD_VALUE;
2882 }
2883 status_t status = disconnectAudioSource(sourceDesc);
2884
2885 mAudioSources.removeItem(handle);
2886 return status;
2887}
2888
Andy Hung2ddee192015-12-18 17:34:44 -08002889status_t AudioPolicyManager::setMasterMono(bool mono)
2890{
2891 if (mMasterMono == mono) {
2892 return NO_ERROR;
2893 }
2894 mMasterMono = mono;
2895 // if enabling mono we close all offloaded devices, which will invalidate the
2896 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
2897 // for recreating the new AudioTrack as non-offloaded PCM.
2898 //
2899 // If disabling mono, we leave all tracks as is: we don't know which clients
2900 // and tracks are able to be recreated as offloaded. The next "song" should
2901 // play back offloaded.
2902 if (mMasterMono) {
2903 Vector<audio_io_handle_t> offloaded;
2904 for (size_t i = 0; i < mOutputs.size(); ++i) {
2905 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2906 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
2907 offloaded.push(desc->mIoHandle);
2908 }
2909 }
2910 for (size_t i = 0; i < offloaded.size(); ++i) {
2911 closeOutput(offloaded[i]);
2912 }
2913 }
2914 // update master mono for all remaining outputs
2915 for (size_t i = 0; i < mOutputs.size(); ++i) {
2916 updateMono(mOutputs.keyAt(i));
2917 }
2918 return NO_ERROR;
2919}
2920
2921status_t AudioPolicyManager::getMasterMono(bool *mono)
2922{
2923 *mono = mMasterMono;
2924 return NO_ERROR;
2925}
2926
Eric Laurentd60560a2015-04-10 11:31:20 -07002927status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2928{
2929 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2930
2931 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
2932 if (patchDesc == 0) {
2933 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
2934 sourceDesc->mPatchDesc->mHandle);
2935 return BAD_VALUE;
2936 }
2937 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
2938
2939 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2940 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
2941 if (swOutputDesc != 0) {
2942 stopSource(swOutputDesc, stream, false);
2943 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2944 } else {
2945 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
2946 if (hwOutputDesc != 0) {
2947 // release patch between src device and output device
2948 // close Hwoutput and remove from mHwOutputs
2949 } else {
2950 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
2951 }
2952 }
2953 return NO_ERROR;
2954}
2955
2956sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
2957 audio_io_handle_t output, routing_strategy strategy)
2958{
2959 sp<AudioSourceDescriptor> source;
2960 for (size_t i = 0; i < mAudioSources.size(); i++) {
2961 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2962 routing_strategy sourceStrategy =
2963 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2964 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
2965 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
2966 source = sourceDesc;
2967 break;
2968 }
2969 }
2970 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07002971}
2972
Eric Laurente552edb2014-03-10 17:42:56 -07002973// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002974// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002975// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07002976uint32_t AudioPolicyManager::nextAudioPortGeneration()
2977{
2978 return android_atomic_inc(&mAudioPortGeneration);
2979}
2980
Eric Laurente0720872014-03-11 09:30:41 -07002981AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002982 :
2983#ifdef AUDIO_POLICY_TEST
2984 Thread(false),
2985#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07002986 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002987 mA2dpSuspended(false),
Paul McLeane743a472015-01-28 11:07:31 -08002988 mSpeakerDrcEnabled(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002989 mAudioPortGeneration(1),
2990 mBeaconMuteRefCount(0),
2991 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07002992 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08002993 mTtsOutputAvailable(false),
2994 mMasterMono(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002995{
François Gaffie2110e042015-03-24 08:41:51 +01002996 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
2997 if (!engineInstance) {
2998 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
2999 return;
3000 }
3001 // Retrieve the Policy Manager Interface
3002 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
3003 if (mEngine == NULL) {
3004 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
3005 return;
3006 }
3007 mEngine->setObserver(this);
3008 status_t status = mEngine->initCheck();
3009 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
3010
Eric Laurent6a94d692014-05-20 11:18:06 -07003011 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003012 mpClientInterface = clientInterface;
3013
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003014 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
3015 mDefaultOutputDevice, mSpeakerDrcEnabled);
3016
3017 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
3018 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
3019
3020 ALOGE("could not load audio policy configuration file, setting defaults");
3021 config.setDefault();
Eric Laurente552edb2014-03-10 17:42:56 -07003022 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003023 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003024
François Gaffie2110e042015-03-24 08:41:51 +01003025 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
3026 mEngine->initializeVolumeCurves(mSpeakerDrcEnabled);
Eric Laurente552edb2014-03-10 17:42:56 -07003027
3028 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003029 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3030 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003031 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003032 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003033 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003034 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07003035 continue;
3036 }
3037 // open all output streams needed to access attached devices
3038 // except for direct output streams that are only opened when they are actually
3039 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003040 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003041 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3042 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003043 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003044
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003045 if (!outProfile->hasSupportedDevices()) {
3046 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003047 continue;
3048 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003049 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07003050 mTtsOutputAvailable = true;
3051 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003052
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003053 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07003054 continue;
3055 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003056 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01003057 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
3058 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07003059 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003060 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003061 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003062 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003063 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003064 if ((profileType & outputDeviceTypes) == 0) {
3065 continue;
3066 }
Eric Laurentc75307b2015-03-17 15:29:32 -07003067 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
3068 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07003069
3070 outputDesc->mDevice = profileType;
3071 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3072 config.sample_rate = outputDesc->mSamplingRate;
3073 config.channel_mask = outputDesc->mChannelMask;
3074 config.format = outputDesc->mFormat;
3075 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003076 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003077 &output,
3078 &config,
3079 &outputDesc->mDevice,
3080 String8(""),
3081 &outputDesc->mLatency,
3082 outputDesc->mFlags);
3083
3084 if (status != NO_ERROR) {
3085 ALOGW("Cannot open output stream for device %08x on hw module %s",
3086 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003087 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003088 } else {
3089 outputDesc->mSamplingRate = config.sample_rate;
3090 outputDesc->mChannelMask = config.channel_mask;
3091 outputDesc->mFormat = config.format;
3092
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003093 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
3094 for (size_t k = 0; k < supportedDevices.size(); k++) {
3095 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003096 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08003097 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
3098 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003099 }
3100 }
3101 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003102 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003103 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003104 }
3105 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003106 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003107 outputDesc->mDevice,
3108 true);
3109 }
Eric Laurente552edb2014-03-10 17:42:56 -07003110 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003111 // open input streams needed to access attached devices to validate
3112 // mAvailableInputDevices list
3113 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3114 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003115 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003116
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003117 if (!inProfile->hasSupportedDevices()) {
3118 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003119 continue;
3120 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003121 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003122 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003123 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3124
Eric Laurentd78f1532014-09-16 16:38:20 -07003125 if ((profileType & inputDeviceTypes) == 0) {
3126 continue;
3127 }
Jean-Michel Trivi2f4fe9f2015-12-04 16:20:59 -08003128 sp<AudioInputDescriptor> inputDesc =
3129 new AudioInputDescriptor(inProfile);
Eric Laurentd78f1532014-09-16 16:38:20 -07003130
Eric Laurentd78f1532014-09-16 16:38:20 -07003131 inputDesc->mDevice = profileType;
3132
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003133 // find the address
3134 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3135 // the inputs vector must be of size 1, but we don't want to crash here
3136 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3137 : String8("");
3138 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3139 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3140
Eric Laurentd78f1532014-09-16 16:38:20 -07003141 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3142 config.sample_rate = inputDesc->mSamplingRate;
3143 config.channel_mask = inputDesc->mChannelMask;
3144 config.format = inputDesc->mFormat;
3145 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003146 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003147 &input,
3148 &config,
3149 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003150 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003151 AUDIO_SOURCE_MIC,
3152 AUDIO_INPUT_FLAG_NONE);
3153
3154 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003155 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3156 for (size_t k = 0; k < supportedDevices.size(); k++) {
3157 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003158 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003159 if (index >= 0) {
3160 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3161 if (!devDesc->isAttached()) {
3162 devDesc->attach(mHwModules[i]);
3163 devDesc->importAudioPort(inProfile);
3164 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003165 }
3166 }
3167 mpClientInterface->closeInput(input);
3168 } else {
3169 ALOGW("Cannot open input stream for device %08x on hw module %s",
3170 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003171 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003172 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003173 }
3174 }
3175 // make sure all attached devices have been allocated a unique ID
3176 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003177 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003178 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003179 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3180 continue;
3181 }
François Gaffie2110e042015-03-24 08:41:51 +01003182 // The device is now validated and can be appended to the available devices of the engine
3183 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3184 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003185 i++;
3186 }
3187 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003188 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003189 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003190 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3191 continue;
3192 }
François Gaffie2110e042015-03-24 08:41:51 +01003193 // The device is now validated and can be appended to the available devices of the engine
3194 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3195 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003196 i++;
3197 }
3198 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003199 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003200 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003201 }
Eric Laurente552edb2014-03-10 17:42:56 -07003202
3203 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3204
3205 updateDevicesAndOutputs();
3206
3207#ifdef AUDIO_POLICY_TEST
3208 if (mPrimaryOutput != 0) {
3209 AudioParameter outputCmd = AudioParameter();
3210 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003211 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003212
3213 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3214 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003215 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3216 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003217 mTestLatencyMs = 0;
3218 mCurOutput = 0;
3219 mDirectOutput = false;
3220 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3221 mTestOutputs[i] = 0;
3222 }
3223
3224 const size_t SIZE = 256;
3225 char buffer[SIZE];
3226 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3227 run(buffer, ANDROID_PRIORITY_AUDIO);
3228 }
3229#endif //AUDIO_POLICY_TEST
3230}
3231
Eric Laurente0720872014-03-11 09:30:41 -07003232AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003233{
3234#ifdef AUDIO_POLICY_TEST
3235 exit();
3236#endif //AUDIO_POLICY_TEST
3237 for (size_t i = 0; i < mOutputs.size(); i++) {
3238 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003239 }
3240 for (size_t i = 0; i < mInputs.size(); i++) {
3241 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003242 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003243 mAvailableOutputDevices.clear();
3244 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003245 mOutputs.clear();
3246 mInputs.clear();
3247 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003248}
3249
Eric Laurente0720872014-03-11 09:30:41 -07003250status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003251{
Eric Laurent87ffa392015-05-22 10:32:38 -07003252 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003253}
3254
3255#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003256bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003257{
3258 ALOGV("entering threadLoop()");
3259 while (!exitPending())
3260 {
3261 String8 command;
3262 int valueInt;
3263 String8 value;
3264
3265 Mutex::Autolock _l(mLock);
3266 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3267
3268 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3269 AudioParameter param = AudioParameter(command);
3270
3271 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3272 valueInt != 0) {
3273 ALOGV("Test command %s received", command.string());
3274 String8 target;
3275 if (param.get(String8("target"), target) != NO_ERROR) {
3276 target = "Manager";
3277 }
3278 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3279 param.remove(String8("test_cmd_policy_output"));
3280 mCurOutput = valueInt;
3281 }
3282 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3283 param.remove(String8("test_cmd_policy_direct"));
3284 if (value == "false") {
3285 mDirectOutput = false;
3286 } else if (value == "true") {
3287 mDirectOutput = true;
3288 }
3289 }
3290 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3291 param.remove(String8("test_cmd_policy_input"));
3292 mTestInput = valueInt;
3293 }
3294
3295 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3296 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003297 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003298 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003299 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003300 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003301 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003302 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003303 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003304 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003305 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003306 if (target == "Manager") {
3307 mTestFormat = format;
3308 } else if (mTestOutputs[mCurOutput] != 0) {
3309 AudioParameter outputParam = AudioParameter();
3310 outputParam.addInt(String8("format"), format);
3311 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3312 }
3313 }
3314 }
3315 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3316 param.remove(String8("test_cmd_policy_channels"));
3317 int channels = 0;
3318
3319 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003320 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003321 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003322 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003323 }
3324 if (channels != 0) {
3325 if (target == "Manager") {
3326 mTestChannels = channels;
3327 } else if (mTestOutputs[mCurOutput] != 0) {
3328 AudioParameter outputParam = AudioParameter();
3329 outputParam.addInt(String8("channels"), channels);
3330 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3331 }
3332 }
3333 }
3334 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3335 param.remove(String8("test_cmd_policy_sampleRate"));
3336 if (valueInt >= 0 && valueInt <= 96000) {
3337 int samplingRate = valueInt;
3338 if (target == "Manager") {
3339 mTestSamplingRate = samplingRate;
3340 } else if (mTestOutputs[mCurOutput] != 0) {
3341 AudioParameter outputParam = AudioParameter();
3342 outputParam.addInt(String8("sampling_rate"), samplingRate);
3343 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3344 }
3345 }
3346 }
3347
3348 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3349 param.remove(String8("test_cmd_policy_reopen"));
3350
Eric Laurentc75307b2015-03-17 15:29:32 -07003351 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003352
Eric Laurentc75307b2015-03-17 15:29:32 -07003353 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003354
Eric Laurentc75307b2015-03-17 15:29:32 -07003355 removeOutput(mPrimaryOutput->mIoHandle);
3356 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3357 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003358 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003359 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3360 config.sample_rate = outputDesc->mSamplingRate;
3361 config.channel_mask = outputDesc->mChannelMask;
3362 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003363 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003364 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003365 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003366 &config,
3367 &outputDesc->mDevice,
3368 String8(""),
3369 &outputDesc->mLatency,
3370 outputDesc->mFlags);
3371 if (status != NO_ERROR) {
3372 ALOGE("Failed to reopen hardware output stream, "
3373 "samplingRate: %d, format %d, channels %d",
3374 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003375 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003376 outputDesc->mSamplingRate = config.sample_rate;
3377 outputDesc->mChannelMask = config.channel_mask;
3378 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003379 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003380 AudioParameter outputCmd = AudioParameter();
3381 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003382 mpClientInterface->setParameters(handle, outputCmd.toString());
3383 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003384 }
3385 }
3386
3387
3388 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3389 }
3390 }
3391 return false;
3392}
3393
Eric Laurente0720872014-03-11 09:30:41 -07003394void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003395{
3396 {
3397 AutoMutex _l(mLock);
3398 requestExit();
3399 mWaitWorkCV.signal();
3400 }
3401 requestExitAndWait();
3402}
3403
Eric Laurente0720872014-03-11 09:30:41 -07003404int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003405{
3406 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3407 if (output == mTestOutputs[i]) return i;
3408 }
3409 return 0;
3410}
3411#endif //AUDIO_POLICY_TEST
3412
3413// ---
3414
Eric Laurentc75307b2015-03-17 15:29:32 -07003415void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003416{
François Gaffie98cc1912015-03-18 17:52:40 +01003417 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003418 mOutputs.add(output, outputDesc);
Andy Hung2ddee192015-12-18 17:34:44 -08003419 updateMono(output); // update mono status when adding to output list
Eric Laurent6a94d692014-05-20 11:18:06 -07003420 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003421}
3422
François Gaffie53615e22015-03-19 09:24:12 +01003423void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3424{
3425 mOutputs.removeItem(output);
3426}
3427
Eric Laurent1f2f2232014-06-02 12:01:23 -07003428void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003429{
François Gaffie98cc1912015-03-18 17:52:40 +01003430 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003431 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003432 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003433}
Eric Laurente552edb2014-03-10 17:42:56 -07003434
Eric Laurentc75307b2015-03-17 15:29:32 -07003435void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003436 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003437 const String8 address /*in*/,
3438 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003439 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003440 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003441 if (devDesc != 0) {
3442 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3443 desc->mIoHandle, address.string());
3444 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003445 }
3446}
3447
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003448status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003449 audio_policy_dev_state_t state,
3450 SortedVector<audio_io_handle_t>& outputs,
3451 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003452{
François Gaffie53615e22015-03-19 09:24:12 +01003453 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003454 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003455
3456 if (audio_device_is_digital(device)) {
3457 // erase all current sample rates, formats and channel masks
3458 devDesc->clearCapabilities();
3459 }
Eric Laurente552edb2014-03-10 17:42:56 -07003460
Eric Laurent3b73df72014-03-11 09:06:29 -07003461 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003462 // first list already open outputs that can be routed to this device
3463 for (size_t i = 0; i < mOutputs.size(); i++) {
3464 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003465 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003466 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003467 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3468 outputs.add(mOutputs.keyAt(i));
3469 } else {
3470 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003471 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003472 }
Eric Laurente552edb2014-03-10 17:42:56 -07003473 }
3474 }
3475 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003476 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003477 for (size_t i = 0; i < mHwModules.size(); i++)
3478 {
3479 if (mHwModules[i]->mHandle == 0) {
3480 continue;
3481 }
3482 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3483 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003484 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003485 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003486 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003487 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003488 profiles.add(profile);
3489 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3490 }
Eric Laurente552edb2014-03-10 17:42:56 -07003491 }
3492 }
3493 }
3494
Eric Laurent7b279bb2015-12-14 10:18:23 -08003495 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003496
Eric Laurente552edb2014-03-10 17:42:56 -07003497 if (profiles.isEmpty() && outputs.isEmpty()) {
3498 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3499 return BAD_VALUE;
3500 }
3501
3502 // open outputs for matching profiles if needed. Direct outputs are also opened to
3503 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3504 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003505 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003506
3507 // nothing to do if one output is already opened for this profile
3508 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003509 for (j = 0; j < outputs.size(); j++) {
3510 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003511 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003512 // matching profile: save the sample rates, format and channel masks supported
3513 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003514 if (audio_device_is_digital(device)) {
3515 devDesc->importAudioPort(profile);
3516 }
Eric Laurente552edb2014-03-10 17:42:56 -07003517 break;
3518 }
3519 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003520 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003521 continue;
3522 }
3523
Eric Laurent83b88082014-06-20 18:31:16 -07003524 ALOGV("opening output for device %08x with params %s profile %p",
3525 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003526 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003527 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003528 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3529 config.sample_rate = desc->mSamplingRate;
3530 config.channel_mask = desc->mChannelMask;
3531 config.format = desc->mFormat;
3532 config.offload_info.sample_rate = desc->mSamplingRate;
3533 config.offload_info.channel_mask = desc->mChannelMask;
3534 config.offload_info.format = desc->mFormat;
3535 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003536 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003537 &output,
3538 &config,
3539 &desc->mDevice,
3540 address,
3541 &desc->mLatency,
3542 desc->mFlags);
3543 if (status == NO_ERROR) {
3544 desc->mSamplingRate = config.sample_rate;
3545 desc->mChannelMask = config.channel_mask;
3546 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003547
Eric Laurentd4692962014-05-05 18:13:44 -07003548 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003549 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003550 char *param = audio_device_address_to_parameter(device, address);
3551 mpClientInterface->setParameters(output, String8(param));
3552 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003553 }
François Gaffie112b0af2015-11-19 16:13:25 +01003554 updateAudioProfiles(output, profile->getAudioProfiles());
3555 if (!profile->hasValidAudioProfile()) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003556 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003557 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003558 output = AUDIO_IO_HANDLE_NONE;
François Gaffie112b0af2015-11-19 16:13:25 +01003559 } else if (profile->hasDynamicAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003560 mpClientInterface->closeOutput(output);
François Gaffie112b0af2015-11-19 16:13:25 +01003561 profile->pickAudioProfile(config.sample_rate, config.channel_mask, config.format);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003562 config.offload_info.sample_rate = config.sample_rate;
3563 config.offload_info.channel_mask = config.channel_mask;
3564 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003565 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003566 &output,
3567 &config,
3568 &desc->mDevice,
3569 address,
3570 &desc->mLatency,
3571 desc->mFlags);
3572 if (status == NO_ERROR) {
3573 desc->mSamplingRate = config.sample_rate;
3574 desc->mChannelMask = config.channel_mask;
3575 desc->mFormat = config.format;
3576 } else {
3577 output = AUDIO_IO_HANDLE_NONE;
3578 }
Eric Laurentd4692962014-05-05 18:13:44 -07003579 }
3580
Eric Laurentcf2c0212014-07-25 16:20:43 -07003581 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003582 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003583 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003584 sp<AudioPolicyMix> policyMix;
3585 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003586 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3587 address.string());
3588 }
François Gaffie036e1e92015-03-19 10:16:24 +01003589 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003590 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003591
Eric Laurent87ffa392015-05-22 10:32:38 -07003592 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3593 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003594 // no duplicated output for direct outputs and
3595 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003596 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003597
Eric Laurentd4692962014-05-05 18:13:44 -07003598 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003599 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003600
Eric Laurentd4692962014-05-05 18:13:44 -07003601 //TODO: configure audio effect output stage here
3602
3603 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003604 duplicatedOutput =
3605 mpClientInterface->openDuplicateOutput(output,
3606 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003607 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003608 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003609 sp<SwAudioOutputDescriptor> dupOutputDesc =
3610 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3611 dupOutputDesc->mOutput1 = mPrimaryOutput;
3612 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003613 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3614 dupOutputDesc->mFormat = desc->mFormat;
3615 dupOutputDesc->mChannelMask = desc->mChannelMask;
3616 dupOutputDesc->mLatency = desc->mLatency;
3617 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003618 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003619 } else {
3620 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003621 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003622 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003623 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003624 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003625 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003626 }
Eric Laurente552edb2014-03-10 17:42:56 -07003627 }
3628 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003629 } else {
3630 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003631 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003632 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003633 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003634 profiles.removeAt(profile_index);
3635 profile_index--;
3636 } else {
3637 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003638 // Load digital format info only for digital devices
3639 if (audio_device_is_digital(device)) {
3640 devDesc->importAudioPort(profile);
3641 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003642
François Gaffie53615e22015-03-19 09:24:12 +01003643 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003644 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3645 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003646 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003647 NULL/*patch handle*/, address.string());
3648 }
Eric Laurente552edb2014-03-10 17:42:56 -07003649 ALOGV("checkOutputsForDevice(): adding output %d", output);
3650 }
3651 }
3652
3653 if (profiles.isEmpty()) {
3654 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3655 return BAD_VALUE;
3656 }
Eric Laurentd4692962014-05-05 18:13:44 -07003657 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003658 // check if one opened output is not needed any more after disconnecting one device
3659 for (size_t i = 0; i < mOutputs.size(); i++) {
3660 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003661 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003662 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003663 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003664 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003665 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003666 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003667 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3668 mOutputs.keyAt(i));
3669 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003670 }
Eric Laurente552edb2014-03-10 17:42:56 -07003671 }
3672 }
Eric Laurentd4692962014-05-05 18:13:44 -07003673 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003674 for (size_t i = 0; i < mHwModules.size(); i++)
3675 {
3676 if (mHwModules[i]->mHandle == 0) {
3677 continue;
3678 }
3679 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3680 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003681 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003682 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003683 ALOGV("checkOutputsForDevice(): "
3684 "clearing direct output profile %zu on module %zu", j, i);
François Gaffie112b0af2015-11-19 16:13:25 +01003685 profile->clearAudioProfiles();
Eric Laurente552edb2014-03-10 17:42:56 -07003686 }
3687 }
3688 }
3689 }
3690 return NO_ERROR;
3691}
3692
Paul McLean9080a4c2015-06-18 08:24:02 -07003693status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003694 audio_policy_dev_state_t state,
3695 SortedVector<audio_io_handle_t>& inputs,
3696 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003697{
Paul McLean9080a4c2015-06-18 08:24:02 -07003698 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003699 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003700
3701 if (audio_device_is_digital(device)) {
3702 // erase all current sample rates, formats and channel masks
3703 devDesc->clearCapabilities();
3704 }
3705
Eric Laurentd4692962014-05-05 18:13:44 -07003706 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3707 // first list already open inputs that can be routed to this device
3708 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3709 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003710 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003711 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3712 inputs.add(mInputs.keyAt(input_index));
3713 }
3714 }
3715
3716 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003717 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003718 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3719 {
3720 if (mHwModules[module_idx]->mHandle == 0) {
3721 continue;
3722 }
3723 for (size_t profile_index = 0;
3724 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3725 profile_index++)
3726 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003727 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3728
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003729 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003730 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003731 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003732 profiles.add(profile);
3733 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3734 profile_index, module_idx);
3735 }
Eric Laurentd4692962014-05-05 18:13:44 -07003736 }
3737 }
3738 }
3739
3740 if (profiles.isEmpty() && inputs.isEmpty()) {
3741 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3742 return BAD_VALUE;
3743 }
3744
3745 // open inputs for matching profiles if needed. Direct inputs are also opened to
3746 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3747 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3748
Eric Laurent1c333e22014-05-20 10:48:17 -07003749 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003750 // nothing to do if one input is already opened for this profile
3751 size_t input_index;
3752 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3753 desc = mInputs.valueAt(input_index);
3754 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003755 if (audio_device_is_digital(device)) {
3756 devDesc->importAudioPort(profile);
3757 }
Eric Laurentd4692962014-05-05 18:13:44 -07003758 break;
3759 }
3760 }
3761 if (input_index != mInputs.size()) {
3762 continue;
3763 }
3764
3765 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3766 desc = new AudioInputDescriptor(profile);
3767 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003768 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3769 config.sample_rate = desc->mSamplingRate;
3770 config.channel_mask = desc->mChannelMask;
3771 config.format = desc->mFormat;
3772 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003773 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003774 &input,
3775 &config,
3776 &desc->mDevice,
3777 address,
3778 AUDIO_SOURCE_MIC,
3779 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003780
Eric Laurentcf2c0212014-07-25 16:20:43 -07003781 if (status == NO_ERROR) {
3782 desc->mSamplingRate = config.sample_rate;
3783 desc->mChannelMask = config.channel_mask;
3784 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003785
Eric Laurentd4692962014-05-05 18:13:44 -07003786 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003787 char *param = audio_device_address_to_parameter(device, address);
3788 mpClientInterface->setParameters(input, String8(param));
3789 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003790 }
François Gaffie112b0af2015-11-19 16:13:25 +01003791 updateAudioProfiles(input, profile->getAudioProfiles());
3792 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07003793 ALOGW("checkInputsForDevice() direct input missing param");
3794 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003795 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003796 }
3797
3798 if (input != 0) {
3799 addInput(input, desc);
3800 }
3801 } // endif input != 0
3802
Eric Laurentcf2c0212014-07-25 16:20:43 -07003803 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003804 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003805 profiles.removeAt(profile_index);
3806 profile_index--;
3807 } else {
3808 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003809 if (audio_device_is_digital(device)) {
3810 devDesc->importAudioPort(profile);
3811 }
Eric Laurentd4692962014-05-05 18:13:44 -07003812 ALOGV("checkInputsForDevice(): adding input %d", input);
3813 }
3814 } // end scan profiles
3815
3816 if (profiles.isEmpty()) {
3817 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3818 return BAD_VALUE;
3819 }
3820 } else {
3821 // Disconnect
3822 // check if one opened input is not needed any more after disconnecting one device
3823 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3824 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003825 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003826 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3827 mInputs.keyAt(input_index));
3828 inputs.add(mInputs.keyAt(input_index));
3829 }
3830 }
3831 // Clear any profiles associated with the disconnected device.
3832 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3833 if (mHwModules[module_index]->mHandle == 0) {
3834 continue;
3835 }
3836 for (size_t profile_index = 0;
3837 profile_index < mHwModules[module_index]->mInputProfiles.size();
3838 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003840 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003841 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003842 profile_index, module_index);
François Gaffie112b0af2015-11-19 16:13:25 +01003843 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07003844 }
3845 }
3846 }
3847 } // end disconnect
3848
3849 return NO_ERROR;
3850}
3851
3852
Eric Laurente0720872014-03-11 09:30:41 -07003853void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003854{
3855 ALOGV("closeOutput(%d)", output);
3856
Eric Laurentc75307b2015-03-17 15:29:32 -07003857 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003858 if (outputDesc == NULL) {
3859 ALOGW("closeOutput() unknown output %d", output);
3860 return;
3861 }
François Gaffie036e1e92015-03-19 10:16:24 +01003862 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003863
Eric Laurente552edb2014-03-10 17:42:56 -07003864 // look for duplicated outputs connected to the output being removed.
3865 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003866 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003867 if (dupOutputDesc->isDuplicated() &&
3868 (dupOutputDesc->mOutput1 == outputDesc ||
3869 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003870 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003871 if (dupOutputDesc->mOutput1 == outputDesc) {
3872 outputDesc2 = dupOutputDesc->mOutput2;
3873 } else {
3874 outputDesc2 = dupOutputDesc->mOutput1;
3875 }
3876 // As all active tracks on duplicated output will be deleted,
3877 // and as they were also referenced on the other output, the reference
3878 // count for their stream type must be adjusted accordingly on
3879 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003880 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003881 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003882 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003883 }
3884 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3885 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3886
3887 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01003888 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003889 }
3890 }
3891
Eric Laurent05b90f82014-08-27 15:32:29 -07003892 nextAudioPortGeneration();
3893
3894 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3895 if (index >= 0) {
3896 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3897 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3898 mAudioPatches.removeItemsAt(index);
3899 mpClientInterface->onAudioPatchListUpdate();
3900 }
3901
Eric Laurente552edb2014-03-10 17:42:56 -07003902 AudioParameter param;
3903 param.add(String8("closing"), String8("true"));
3904 mpClientInterface->setParameters(output, param.toString());
3905
3906 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003907 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003908 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003909}
3910
3911void AudioPolicyManager::closeInput(audio_io_handle_t input)
3912{
3913 ALOGV("closeInput(%d)", input);
3914
3915 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3916 if (inputDesc == NULL) {
3917 ALOGW("closeInput() unknown input %d", input);
3918 return;
3919 }
3920
Eric Laurent6a94d692014-05-20 11:18:06 -07003921 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003922
3923 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3924 if (index >= 0) {
3925 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3926 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3927 mAudioPatches.removeItemsAt(index);
3928 mpClientInterface->onAudioPatchListUpdate();
3929 }
3930
3931 mpClientInterface->closeInput(input);
3932 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003933}
3934
Eric Laurentc75307b2015-03-17 15:29:32 -07003935SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
3936 audio_devices_t device,
3937 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003938{
3939 SortedVector<audio_io_handle_t> outputs;
3940
3941 ALOGVV("getOutputsForDevice() device %04x", device);
3942 for (size_t i = 0; i < openOutputs.size(); i++) {
3943 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003944 i, openOutputs.valueAt(i)->isDuplicated(),
3945 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07003946 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3947 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3948 outputs.add(openOutputs.keyAt(i));
3949 }
3950 }
3951 return outputs;
3952}
3953
Eric Laurente0720872014-03-11 09:30:41 -07003954bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01003955 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07003956{
3957 if (outputs1.size() != outputs2.size()) {
3958 return false;
3959 }
3960 for (size_t i = 0; i < outputs1.size(); i++) {
3961 if (outputs1[i] != outputs2[i]) {
3962 return false;
3963 }
3964 }
3965 return true;
3966}
3967
Eric Laurente0720872014-03-11 09:30:41 -07003968void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003969{
3970 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3971 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3972 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3973 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3974
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003975 // also take into account external policy-related changes: add all outputs which are
3976 // associated with policies in the "before" and "after" output vectors
3977 ALOGVV("checkOutputForStrategy(): policy related outputs");
3978 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003979 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003980 if (desc != 0 && desc->mPolicyMix != NULL) {
3981 srcOutputs.add(desc->mIoHandle);
3982 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
3983 }
3984 }
3985 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003986 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003987 if (desc != 0 && desc->mPolicyMix != NULL) {
3988 dstOutputs.add(desc->mIoHandle);
3989 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
3990 }
3991 }
3992
Eric Laurente552edb2014-03-10 17:42:56 -07003993 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3994 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3995 strategy, srcOutputs[0], dstOutputs[0]);
3996 // mute strategy while moving tracks from one output to another
3997 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003998 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01003999 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004000 setStrategyMute(strategy, true, desc);
4001 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004002 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004003 sp<AudioSourceDescriptor> source =
4004 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4005 if (source != 0){
4006 connectAudioSource(source);
4007 }
Eric Laurente552edb2014-03-10 17:42:56 -07004008 }
4009
4010 // Move effects associated to this strategy from previous output to new output
4011 if (strategy == STRATEGY_MEDIA) {
4012 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4013 SortedVector<audio_io_handle_t> moved;
4014 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004015 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4016 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4017 effectDesc->mIo != fxOutput) {
4018 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004019 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4020 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004021 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004022 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004023 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004024 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004025 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004026 }
4027 }
4028 }
4029 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004030 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004031 if (i == AUDIO_STREAM_PATCH) {
4032 continue;
4033 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004034 if (getStrategy((audio_stream_type_t)i) == strategy) {
4035 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004036 }
4037 }
4038 }
4039}
4040
Eric Laurente0720872014-03-11 09:30:41 -07004041void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004042{
François Gaffie2110e042015-03-24 08:41:51 +01004043 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004044 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004045 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004046 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004047 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004048 checkOutputForStrategy(STRATEGY_SONIFICATION);
4049 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004050 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004051 checkOutputForStrategy(STRATEGY_MEDIA);
4052 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004053 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004054}
4055
Eric Laurente0720872014-03-11 09:30:41 -07004056void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004057{
François Gaffie53615e22015-03-19 09:24:12 +01004058 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004059 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004060 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004061 return;
4062 }
4063
Eric Laurent3a4311c2014-03-17 12:00:47 -07004064 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004065 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4066 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4067 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004068 // suspend A2DP output if:
4069 // (NOT already suspended) &&
4070 // ((SCO device is connected &&
4071 // (forced usage for communication || for record is SCO))) ||
4072 // (phone state is ringing || in call)
4073 //
4074 // restore A2DP output if:
4075 // (Already suspended) &&
4076 // ((SCO device is NOT connected ||
4077 // (forced usage NOT for communication && NOT for record is SCO))) &&
4078 // (phone state is NOT ringing && NOT in call)
4079 //
4080 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004081 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004082 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4083 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4084 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4085 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004086
4087 mpClientInterface->restoreOutput(a2dpOutput);
4088 mA2dpSuspended = false;
4089 }
4090 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004091 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004092 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4093 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4094 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4095 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004096
4097 mpClientInterface->suspendOutput(a2dpOutput);
4098 mA2dpSuspended = true;
4099 }
4100 }
4101}
4102
Eric Laurentc75307b2015-03-17 15:29:32 -07004103audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4104 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004105{
4106 audio_devices_t device = AUDIO_DEVICE_NONE;
4107
Eric Laurent6a94d692014-05-20 11:18:06 -07004108 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4109 if (index >= 0) {
4110 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4111 if (patchDesc->mUid != mUidCached) {
4112 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4113 outputDesc->device(), outputDesc->mPatchHandle);
4114 return outputDesc->device();
4115 }
4116 }
4117
Eric Laurente552edb2014-03-10 17:42:56 -07004118 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004119 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004120 // use device for strategy enforced audible
4121 // 2: we are in call or the strategy phone is active on the output:
4122 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004123 // 3: the strategy for enforced audible is active but not enforced on the output:
4124 // use the device for strategy enforced audible
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004125 // 4: the strategy accessibility is active on the output:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004126 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004127 // 5: the strategy sonification is active on the output:
4128 // use device for strategy sonification
4129 // 6: the strategy "respectful" sonification is active on the output:
4130 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004131 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004132 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004133 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004134 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004135 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004136 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004137 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004138 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004139 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4140 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004141 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004142 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004143 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004144 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004145 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4146 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004147 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004148 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004149 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004150 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004151 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004152 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004153 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004154 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004155 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004156 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004157 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004158 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004159 }
4160
Eric Laurent1c333e22014-05-20 10:48:17 -07004161 ALOGV("getNewOutputDevice() selected device %x", device);
4162 return device;
4163}
4164
4165audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4166{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004167 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004168
4169 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4170 if (index >= 0) {
4171 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4172 if (patchDesc->mUid != mUidCached) {
4173 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4174 inputDesc->mDevice, inputDesc->mPatchHandle);
4175 return inputDesc->mDevice;
4176 }
4177 }
4178
Eric Laurent599c7582015-12-07 18:05:55 -08004179 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->inputSource());
Eric Laurent1c333e22014-05-20 10:48:17 -07004180
Eric Laurente552edb2014-03-10 17:42:56 -07004181 return device;
4182}
4183
Eric Laurente0720872014-03-11 09:30:41 -07004184uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004185 return (uint32_t)getStrategy(stream);
4186}
4187
Eric Laurente0720872014-03-11 09:30:41 -07004188audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004189 // By checking the range of stream before calling getStrategy, we avoid
4190 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4191 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004192 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 return AUDIO_DEVICE_NONE;
4194 }
4195 audio_devices_t devices;
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004196 routing_strategy strategy = getStrategy(stream);
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4198 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4199 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004200 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004201 if (isStrategyActive(outputDesc, strategy)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004202 devices = outputDesc->device();
4203 break;
4204 }
Eric Laurente552edb2014-03-10 17:42:56 -07004205 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004206
4207 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4208 and doesn't really need to.*/
4209 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4210 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4211 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4212 }
4213
Eric Laurente552edb2014-03-10 17:42:56 -07004214 return devices;
4215}
4216
François Gaffie2110e042015-03-24 08:41:51 +01004217routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4218{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004219 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004220 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004221}
4222
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004223uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4224 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004225 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4226 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4227 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004228 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4229 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4230 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004231 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004232 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004233}
4234
Eric Laurente0720872014-03-11 09:30:41 -07004235void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004236 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004237 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004238 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4239 updateDevicesAndOutputs();
4240 break;
4241 default:
4242 break;
4243 }
4244}
4245
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004246uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004247
4248 // skip beacon mute management if a dedicated TTS output is available
4249 if (mTtsOutputAvailable) {
4250 return 0;
4251 }
4252
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004253 switch(event) {
4254 case STARTING_OUTPUT:
4255 mBeaconMuteRefCount++;
4256 break;
4257 case STOPPING_OUTPUT:
4258 if (mBeaconMuteRefCount > 0) {
4259 mBeaconMuteRefCount--;
4260 }
4261 break;
4262 case STARTING_BEACON:
4263 mBeaconPlayingRefCount++;
4264 break;
4265 case STOPPING_BEACON:
4266 if (mBeaconPlayingRefCount > 0) {
4267 mBeaconPlayingRefCount--;
4268 }
4269 break;
4270 }
4271
4272 if (mBeaconMuteRefCount > 0) {
4273 // any playback causes beacon to be muted
4274 return setBeaconMute(true);
4275 } else {
4276 // no other playback: unmute when beacon starts playing, mute when it stops
4277 return setBeaconMute(mBeaconPlayingRefCount == 0);
4278 }
4279}
4280
4281uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4282 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4283 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4284 // keep track of muted state to avoid repeating mute/unmute operations
4285 if (mBeaconMuted != mute) {
4286 // mute/unmute AUDIO_STREAM_TTS on all outputs
4287 ALOGV("\t muting %d", mute);
4288 uint32_t maxLatency = 0;
4289 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004291 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004292 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004293 0 /*delay*/, AUDIO_DEVICE_NONE);
4294 const uint32_t latency = desc->latency() * 2;
4295 if (latency > maxLatency) {
4296 maxLatency = latency;
4297 }
4298 }
4299 mBeaconMuted = mute;
4300 return maxLatency;
4301 }
4302 return 0;
4303}
4304
Eric Laurente0720872014-03-11 09:30:41 -07004305audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004306 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004307{
Paul McLeanaa981192015-03-21 09:55:15 -07004308 // Routing
4309 // see if we have an explicit route
4310 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4311 // (getStrategy(stream)).
4312 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4313 // and activity count is non-zero
4314 // the device = the device from the descriptor in the RouteMap, and exit.
4315 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4316 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4317 routing_strategy strat = getStrategy(route->mStreamType);
Eric Laurent093a20c2015-06-11 12:33:29 -07004318 // Special case for accessibility strategy which must follow any strategy it is
4319 // currently remapped to
4320 bool strategyMatch = (strat == strategy) ||
4321 ((strategy == STRATEGY_ACCESSIBILITY) &&
4322 ((mEngine->getStrategyForUsage(
4323 AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) == strat) ||
4324 (strat == STRATEGY_MEDIA)));
4325 if (strategyMatch && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004326 return route->mDeviceDescriptor->type();
4327 }
4328 }
4329
Eric Laurente552edb2014-03-10 17:42:56 -07004330 if (fromCache) {
4331 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4332 strategy, mDeviceForStrategy[strategy]);
4333 return mDeviceForStrategy[strategy];
4334 }
François Gaffie2110e042015-03-24 08:41:51 +01004335 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004336}
4337
Eric Laurente0720872014-03-11 09:30:41 -07004338void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004339{
4340 for (int i = 0; i < NUM_STRATEGIES; i++) {
4341 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4342 }
4343 mPreviousOutputs = mOutputs;
4344}
4345
Eric Laurent1f2f2232014-06-02 12:01:23 -07004346uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004347 audio_devices_t prevDevice,
4348 uint32_t delayMs)
4349{
4350 // mute/unmute strategies using an incompatible device combination
4351 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4352 // if unmuting, unmute only after the specified delay
4353 if (outputDesc->isDuplicated()) {
4354 return 0;
4355 }
4356
4357 uint32_t muteWaitMs = 0;
4358 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004360
4361 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4362 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004363 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004364 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4365 bool doMute = false;
4366
4367 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4368 doMute = true;
4369 outputDesc->mStrategyMutedByDevice[i] = true;
4370 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4371 doMute = true;
4372 outputDesc->mStrategyMutedByDevice[i] = false;
4373 }
Eric Laurent99401132014-05-07 19:48:15 -07004374 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004375 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004376 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004377 // skip output if it does not share any device with current output
4378 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4379 == AUDIO_DEVICE_NONE) {
4380 continue;
4381 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004382 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4383 mute ? "muting" : "unmuting", i, curDevice);
4384 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004385 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004386 if (mute) {
4387 // FIXME: should not need to double latency if volume could be applied
4388 // immediately by the audioflinger mixer. We must account for the delay
4389 // between now and the next time the audioflinger thread for this output
4390 // will process a buffer (which corresponds to one buffer size,
4391 // usually 1/2 or 1/4 of the latency).
4392 if (muteWaitMs < desc->latency() * 2) {
4393 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004394 }
4395 }
4396 }
4397 }
4398 }
4399 }
4400
Eric Laurent99401132014-05-07 19:48:15 -07004401 // temporary mute output if device selection changes to avoid volume bursts due to
4402 // different per device volumes
4403 if (outputDesc->isActive() && (device != prevDevice)) {
4404 if (muteWaitMs < outputDesc->latency() * 2) {
4405 muteWaitMs = outputDesc->latency() * 2;
4406 }
4407 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004408 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004409 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004410 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004411 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004412 muteWaitMs *2, device);
4413 }
4414 }
4415 }
4416
Eric Laurente552edb2014-03-10 17:42:56 -07004417 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4418 if (muteWaitMs > delayMs) {
4419 muteWaitMs -= delayMs;
4420 usleep(muteWaitMs * 1000);
4421 return muteWaitMs;
4422 }
4423 return 0;
4424}
4425
Eric Laurentc75307b2015-03-17 15:29:32 -07004426uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004427 audio_devices_t device,
4428 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004429 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004430 audio_patch_handle_t *patchHandle,
4431 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004432{
Eric Laurentc75307b2015-03-17 15:29:32 -07004433 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004434 AudioParameter param;
4435 uint32_t muteWaitMs;
4436
4437 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004438 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4439 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004440 return muteWaitMs;
4441 }
4442 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4443 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004444 if ((device != AUDIO_DEVICE_NONE) &&
4445 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004446 return 0;
4447 }
4448
4449 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004450 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004451
4452 audio_devices_t prevDevice = outputDesc->mDevice;
4453
Paul McLeanaa981192015-03-21 09:55:15 -07004454 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004455
4456 if (device != AUDIO_DEVICE_NONE) {
4457 outputDesc->mDevice = device;
4458 }
4459 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4460
4461 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004462 // the requested device is AUDIO_DEVICE_NONE
4463 // OR the requested device is the same as current device
4464 // AND force is not specified
4465 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004466 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004467 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4468 !force &&
4469 outputDesc->mPatchHandle != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004470 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004471 return muteWaitMs;
4472 }
4473
4474 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004475
Eric Laurente552edb2014-03-10 17:42:56 -07004476 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004477 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004478 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004479 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004480 DeviceVector deviceList = (address == NULL) ?
4481 mAvailableOutputDevices.getDevicesFromType(device)
4482 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004483 if (!deviceList.isEmpty()) {
4484 struct audio_patch patch;
4485 outputDesc->toAudioPortConfig(&patch.sources[0]);
4486 patch.num_sources = 1;
4487 patch.num_sinks = 0;
4488 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4489 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004490 patch.num_sinks++;
4491 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 ssize_t index;
4493 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4494 index = mAudioPatches.indexOfKey(*patchHandle);
4495 } else {
4496 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4497 }
4498 sp< AudioPatch> patchDesc;
4499 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4500 if (index >= 0) {
4501 patchDesc = mAudioPatches.valueAt(index);
4502 afPatchHandle = patchDesc->mAfPatchHandle;
4503 }
4504
Eric Laurent1c333e22014-05-20 10:48:17 -07004505 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 &afPatchHandle,
4507 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004508 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4509 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004510 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004511 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004512 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004513 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004514 addAudioPatch(patchDesc->mHandle, patchDesc);
4515 } else {
4516 patchDesc->mPatch = patch;
4517 }
4518 patchDesc->mAfPatchHandle = afPatchHandle;
4519 patchDesc->mUid = mUidCached;
4520 if (patchHandle) {
4521 *patchHandle = patchDesc->mHandle;
4522 }
4523 outputDesc->mPatchHandle = patchDesc->mHandle;
4524 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004525 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004526 }
4527 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004528
4529 // inform all input as well
4530 for (size_t i = 0; i < mInputs.size(); i++) {
4531 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004532 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004533 AudioParameter inputCmd = AudioParameter();
4534 ALOGV("%s: inform input %d of device:%d", __func__,
4535 inputDescriptor->mIoHandle, device);
4536 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4537 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4538 inputCmd.toString(),
4539 delayMs);
4540 }
4541 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004542 }
Eric Laurente552edb2014-03-10 17:42:56 -07004543
4544 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004545 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004546
4547 return muteWaitMs;
4548}
4549
Eric Laurentc75307b2015-03-17 15:29:32 -07004550status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004551 int delayMs,
4552 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004553{
Eric Laurent6a94d692014-05-20 11:18:06 -07004554 ssize_t index;
4555 if (patchHandle) {
4556 index = mAudioPatches.indexOfKey(*patchHandle);
4557 } else {
4558 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4559 }
4560 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004561 return INVALID_OPERATION;
4562 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004563 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4564 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004565 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4566 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004567 removeAudioPatch(patchDesc->mHandle);
4568 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004569 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004570 return status;
4571}
4572
4573status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4574 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004575 bool force,
4576 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004577{
4578 status_t status = NO_ERROR;
4579
Eric Laurent1f2f2232014-06-02 12:01:23 -07004580 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004581 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4582 inputDesc->mDevice = device;
4583
4584 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4585 if (!deviceList.isEmpty()) {
4586 struct audio_patch patch;
4587 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004588 // AUDIO_SOURCE_HOTWORD is for internal use only:
4589 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004590 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
Eric Laurent599c7582015-12-07 18:05:55 -08004591 !inputDesc->isSoundTrigger()) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004592 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4593 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004594 patch.num_sinks = 1;
4595 //only one input device for now
4596 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004597 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004598 ssize_t index;
4599 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4600 index = mAudioPatches.indexOfKey(*patchHandle);
4601 } else {
4602 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4603 }
4604 sp< AudioPatch> patchDesc;
4605 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4606 if (index >= 0) {
4607 patchDesc = mAudioPatches.valueAt(index);
4608 afPatchHandle = patchDesc->mAfPatchHandle;
4609 }
4610
Eric Laurent1c333e22014-05-20 10:48:17 -07004611 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004612 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004613 0);
4614 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004615 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004616 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004617 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004618 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004619 addAudioPatch(patchDesc->mHandle, patchDesc);
4620 } else {
4621 patchDesc->mPatch = patch;
4622 }
4623 patchDesc->mAfPatchHandle = afPatchHandle;
4624 patchDesc->mUid = mUidCached;
4625 if (patchHandle) {
4626 *patchHandle = patchDesc->mHandle;
4627 }
4628 inputDesc->mPatchHandle = patchDesc->mHandle;
4629 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004630 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004631 }
4632 }
4633 }
4634 return status;
4635}
4636
Eric Laurent6a94d692014-05-20 11:18:06 -07004637status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4638 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004639{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004640 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004641 ssize_t index;
4642 if (patchHandle) {
4643 index = mAudioPatches.indexOfKey(*patchHandle);
4644 } else {
4645 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4646 }
4647 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004648 return INVALID_OPERATION;
4649 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4651 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004652 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4653 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004654 removeAudioPatch(patchDesc->mHandle);
4655 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004656 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004657 return status;
4658}
4659
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004660sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004661 String8 address,
4662 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004663 audio_format_t& format,
4664 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004665 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004666{
4667 // Choose an input profile based on the requested capture parameters: select the first available
4668 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004669 //
4670 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4671 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004672
4673 for (size_t i = 0; i < mHwModules.size(); i++)
4674 {
4675 if (mHwModules[i]->mHandle == 0) {
4676 continue;
4677 }
4678 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4679 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004680 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004681 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004682 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004683 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004684 format,
4685 &format /*updatedFormat*/,
4686 channelMask,
4687 &channelMask /*updatedChannelMask*/,
4688 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004689
Eric Laurente552edb2014-03-10 17:42:56 -07004690 return profile;
4691 }
4692 }
4693 }
4694 return NULL;
4695}
4696
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004697
4698audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004699 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004700{
François Gaffie036e1e92015-03-19 10:16:24 +01004701 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4702 audio_devices_t selectedDeviceFromMix =
4703 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004704
François Gaffie036e1e92015-03-19 10:16:24 +01004705 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4706 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004707 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004708 return getDeviceForInputSource(inputSource);
4709}
4710
4711audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4712{
Paul McLean466dc8e2015-04-17 13:15:36 -06004713 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4714 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004715 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004716 return route->mDeviceDescriptor->type();
4717 }
4718 }
4719
4720 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004721}
4722
Eric Laurente0720872014-03-11 09:30:41 -07004723float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004724 int index,
4725 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004726{
Eric Laurentffbc80f2015-03-18 18:30:19 -07004727 float volumeDb = mEngine->volIndexToDb(Volume::getDeviceCategory(device), stream, index);
Eric Laurente552edb2014-03-10 17:42:56 -07004728
4729 // if a headset is connected, apply the following rules to ring tones and notifications
4730 // to avoid sound level bursts in user's ears:
4731 // - always attenuate ring tones and notifications volume by 6dB
4732 // - if music is playing, always limit the volume to current music volume,
4733 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004734 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004735 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4736 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4737 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4738 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4739 ((stream_strategy == STRATEGY_SONIFICATION)
4740 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004741 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004742 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004743 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
4744 mStreams.canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004745 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004746 // when the phone is ringing we must consider that music could have been paused just before
4747 // by the music application and behave as if music was active if the last music track was
4748 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004749 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004750 mLimitRingtoneVolume) {
4751 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004752 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
4753 mStreams.valueFor(AUDIO_STREAM_MUSIC).getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004754 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004755 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4756 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4757 if (volumeDb > minVolDB) {
4758 volumeDb = minVolDB;
4759 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004760 }
4761 }
4762 }
4763
Eric Laurentffbc80f2015-03-18 18:30:19 -07004764 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004765}
4766
Eric Laurente0720872014-03-11 09:30:41 -07004767status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004768 int index,
4769 const sp<AudioOutputDescriptor>& outputDesc,
4770 audio_devices_t device,
4771 int delayMs,
4772 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004773{
Eric Laurente552edb2014-03-10 17:42:56 -07004774 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004775 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004776 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004777 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004778 return NO_ERROR;
4779 }
François Gaffie2110e042015-03-24 08:41:51 +01004780 audio_policy_forced_cfg_t forceUseForComm =
4781 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004782 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004783 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4784 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004785 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004786 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004787 return INVALID_OPERATION;
4788 }
4789
Eric Laurentc75307b2015-03-17 15:29:32 -07004790 if (device == AUDIO_DEVICE_NONE) {
4791 device = outputDesc->device();
4792 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004793
Eric Laurentffbc80f2015-03-18 18:30:19 -07004794 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004795 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004796 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004797 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004798
Eric Laurentffbc80f2015-03-18 18:30:19 -07004799 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004800
Eric Laurent3b73df72014-03-11 09:06:29 -07004801 if (stream == AUDIO_STREAM_VOICE_CALL ||
4802 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004803 float voiceVolume;
4804 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004805 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004806 voiceVolume = (float)index/(float)mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07004807 } else {
4808 voiceVolume = 1.0;
4809 }
4810
Eric Laurentc75307b2015-03-17 15:29:32 -07004811 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004812 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4813 mLastVoiceVolume = voiceVolume;
4814 }
4815 }
4816
4817 return NO_ERROR;
4818}
4819
Eric Laurentc75307b2015-03-17 15:29:32 -07004820void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4821 audio_devices_t device,
4822 int delayMs,
4823 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004824{
Eric Laurentc75307b2015-03-17 15:29:32 -07004825 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004826
Eric Laurent3b73df72014-03-11 09:06:29 -07004827 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004828 if (stream == AUDIO_STREAM_PATCH) {
4829 continue;
4830 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004831 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004832 mStreams.valueFor((audio_stream_type_t)stream).getVolumeIndex(device),
4833 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004834 device,
4835 delayMs,
4836 force);
4837 }
4838}
4839
Eric Laurente0720872014-03-11 09:30:41 -07004840void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07004841 bool on,
4842 const sp<AudioOutputDescriptor>& outputDesc,
4843 int delayMs,
4844 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004845{
Eric Laurent72249d52015-06-08 11:12:15 -07004846 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
4847 strategy, on, outputDesc->getId());
Eric Laurent3b73df72014-03-11 09:06:29 -07004848 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004849 if (stream == AUDIO_STREAM_PATCH) {
4850 continue;
4851 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004852 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004853 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004854 }
4855 }
4856}
4857
Eric Laurente0720872014-03-11 09:30:41 -07004858void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004859 bool on,
4860 const sp<AudioOutputDescriptor>& outputDesc,
4861 int delayMs,
4862 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004863{
Eric Laurentc75307b2015-03-17 15:29:32 -07004864 const StreamDescriptor& streamDesc = mStreams.valueFor(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004865 if (device == AUDIO_DEVICE_NONE) {
4866 device = outputDesc->device();
4867 }
4868
Eric Laurentc75307b2015-03-17 15:29:32 -07004869 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
4870 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07004871
4872 if (on) {
4873 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffiedfd74092015-03-19 12:10:59 +01004874 if (streamDesc.canBeMuted() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004875 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01004876 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004877 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004878 }
4879 }
4880 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4881 outputDesc->mMuteCount[stream]++;
4882 } else {
4883 if (outputDesc->mMuteCount[stream] == 0) {
4884 ALOGV("setStreamMute() unmuting non muted stream!");
4885 return;
4886 }
4887 if (--outputDesc->mMuteCount[stream] == 0) {
4888 checkAndSetVolume(stream,
4889 streamDesc.getVolumeIndex(device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004890 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004891 device,
4892 delayMs);
4893 }
4894 }
4895}
4896
Eric Laurente0720872014-03-11 09:30:41 -07004897void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004898 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004899{
Eric Laurent87ffa392015-05-22 10:32:38 -07004900 if(!hasPrimaryOutput()) {
4901 return;
4902 }
4903
Eric Laurente552edb2014-03-10 17:42:56 -07004904 // if the stream pertains to sonification strategy and we are in call we must
4905 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4906 // in the device used for phone strategy and play the tone if the selected device does not
4907 // interfere with the device used for phone strategy
4908 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4909 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004910 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004911 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4912 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004913 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004914 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4915 stream, starting, outputDesc->mDevice, stateChange);
4916 if (outputDesc->mRefCount[stream]) {
4917 int muteCount = 1;
4918 if (stateChange) {
4919 muteCount = outputDesc->mRefCount[stream];
4920 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004921 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004922 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4923 for (int i = 0; i < muteCount; i++) {
4924 setStreamMute(stream, starting, mPrimaryOutput);
4925 }
4926 } else {
4927 ALOGV("handleIncallSonification() high visibility");
4928 if (outputDesc->device() &
4929 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4930 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4931 for (int i = 0; i < muteCount; i++) {
4932 setStreamMute(stream, starting, mPrimaryOutput);
4933 }
4934 }
4935 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004936 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4937 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004938 } else {
4939 mpClientInterface->stopTone();
4940 }
4941 }
4942 }
4943 }
4944}
4945
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004946audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
4947{
4948 // flags to stream type mapping
4949 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4950 return AUDIO_STREAM_ENFORCED_AUDIBLE;
4951 }
4952 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
4953 return AUDIO_STREAM_BLUETOOTH_SCO;
4954 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08004955 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4956 return AUDIO_STREAM_TTS;
4957 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004958
4959 // usage to stream type mapping
4960 switch (attr->usage) {
4961 case AUDIO_USAGE_MEDIA:
4962 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004963 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4964 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004965 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08004966 if (isStreamActive(AUDIO_STREAM_ALARM)) {
4967 return AUDIO_STREAM_ALARM;
4968 }
4969 if (isStreamActive(AUDIO_STREAM_RING)) {
4970 return AUDIO_STREAM_RING;
4971 }
4972 if (isInCall()) {
4973 return AUDIO_STREAM_VOICE_CALL;
4974 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08004975 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004976 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4977 return AUDIO_STREAM_SYSTEM;
4978 case AUDIO_USAGE_VOICE_COMMUNICATION:
4979 return AUDIO_STREAM_VOICE_CALL;
4980
4981 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4982 return AUDIO_STREAM_DTMF;
4983
4984 case AUDIO_USAGE_ALARM:
4985 return AUDIO_STREAM_ALARM;
4986 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4987 return AUDIO_STREAM_RING;
4988
4989 case AUDIO_USAGE_NOTIFICATION:
4990 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4991 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4992 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4993 case AUDIO_USAGE_NOTIFICATION_EVENT:
4994 return AUDIO_STREAM_NOTIFICATION;
4995
4996 case AUDIO_USAGE_UNKNOWN:
4997 default:
4998 return AUDIO_STREAM_MUSIC;
4999 }
5000}
Eric Laurente83b55d2014-11-14 10:06:21 -08005001
François Gaffie53615e22015-03-19 09:24:12 +01005002bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5003{
Eric Laurente83b55d2014-11-14 10:06:21 -08005004 // has flags that map to a strategy?
5005 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5006 return true;
5007 }
5008
5009 // has known usage?
5010 switch (paa->usage) {
5011 case AUDIO_USAGE_UNKNOWN:
5012 case AUDIO_USAGE_MEDIA:
5013 case AUDIO_USAGE_VOICE_COMMUNICATION:
5014 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5015 case AUDIO_USAGE_ALARM:
5016 case AUDIO_USAGE_NOTIFICATION:
5017 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5018 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5019 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5020 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5021 case AUDIO_USAGE_NOTIFICATION_EVENT:
5022 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5023 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5024 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5025 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005026 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005027 break;
5028 default:
5029 return false;
5030 }
5031 return true;
5032}
5033
François Gaffiead3183e2015-03-18 16:55:35 +01005034bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5035 routing_strategy strategy, uint32_t inPastMs,
5036 nsecs_t sysTime) const
5037{
5038 if ((sysTime == 0) && (inPastMs != 0)) {
5039 sysTime = systemTime();
5040 }
5041 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5042 if (i == AUDIO_STREAM_PATCH) {
5043 continue;
5044 }
5045 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5046 (NUM_STRATEGIES == strategy)) &&
5047 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5048 return true;
5049 }
5050 }
5051 return false;
5052}
5053
François Gaffie2110e042015-03-24 08:41:51 +01005054audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5055{
5056 return mEngine->getForceUse(usage);
5057}
5058
5059bool AudioPolicyManager::isInCall()
5060{
5061 return isStateInCall(mEngine->getPhoneState());
5062}
5063
5064bool AudioPolicyManager::isStateInCall(int state)
5065{
5066 return is_state_in_call(state);
5067}
5068
Eric Laurentd60560a2015-04-10 11:31:20 -07005069void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5070{
5071 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5072 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5073 if (sourceDesc->mDevice->equals(deviceDesc)) {
5074 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5075 stopAudioSource(sourceDesc->getHandle());
5076 }
5077 }
5078
5079 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5080 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5081 bool release = false;
5082 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5083 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5084 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5085 source->ext.device.type == deviceDesc->type()) {
5086 release = true;
5087 }
5088 }
5089 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5090 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5091 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5092 sink->ext.device.type == deviceDesc->type()) {
5093 release = true;
5094 }
5095 }
5096 if (release) {
5097 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5098 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5099 }
5100 }
5101}
5102
François Gaffie112b0af2015-11-19 16:13:25 +01005103void AudioPolicyManager::updateAudioProfiles(audio_io_handle_t ioHandle,
5104 AudioProfileVector &profiles)
5105{
5106 String8 reply;
5107 char *value;
5108 // Format MUST be checked first to update the list of AudioProfile
5109 if (profiles.hasDynamicFormat()) {
5110 reply = mpClientInterface->getParameters(ioHandle,
5111 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
5112 ALOGV("%s: supported formats %s", __FUNCTION__, reply.string());
5113 value = strpbrk((char *)reply.string(), "=");
5114 if (value == NULL) {
5115 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
5116 return;
5117 }
5118 profiles.setFormats(formatsFromString(value + 1));
5119 }
5120 const FormatVector &supportedFormats = profiles.getSupportedFormats();
5121
5122 for(size_t formatIndex = 0; formatIndex < supportedFormats.size(); formatIndex++) {
5123 audio_format_t format = supportedFormats[formatIndex];
5124 AudioParameter requestedParameters;
5125 requestedParameters.addInt(String8(AUDIO_PARAMETER_STREAM_FORMAT), format);
5126
5127 if (profiles.hasDynamicRateFor(format)) {
5128 reply = mpClientInterface->getParameters(ioHandle,
5129 requestedParameters.toString() + ";" +
5130 AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES);
5131 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
5132 value = strpbrk((char *)reply.string(), "=");
5133 if (value != NULL) {
5134 profiles.setSampleRatesFor(samplingRatesFromString(value + 1), format);
5135 }
5136 }
5137 if (profiles.hasDynamicChannelsFor(format)) {
5138 reply = mpClientInterface->getParameters(ioHandle,
5139 requestedParameters.toString() + ";" +
5140 AUDIO_PARAMETER_STREAM_SUP_CHANNELS);
5141 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
5142 value = strpbrk((char *)reply.string(), "=");
5143 if (value != NULL) {
5144 profiles.setChannelsFor(channelMasksFromString(value + 1), format);
5145 }
5146 }
5147 }
5148}
Eric Laurentd60560a2015-04-10 11:31:20 -07005149
Eric Laurente552edb2014-03-10 17:42:56 -07005150}; // namespace android