blob: 4d905467908b6a173c71c0f1f4a1a8ff1efbbd14 [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()) {
421 audio_session_t activeSession = activeDesc->mSessions.itemAt(0);
422 stopInput(activeInput, activeSession);
423 releaseInput(activeInput, activeSession);
424 }
425 }
426
Eric Laurentc2730ba2014-07-20 15:47:07 -0700427 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
428 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
429 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
430 status);
431 if (status == NO_ERROR) {
François Gaffie98cc1912015-03-18 17:52:40 +0100432 mCallTxPatch = new AudioPatch(&patch, mUidCached);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700433 mCallTxPatch->mAfPatchHandle = afPatchHandle;
434 mCallTxPatch->mUid = mUidCached;
435 }
436 }
437}
438
Eric Laurente0720872014-03-11 09:30:41 -0700439void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700440{
441 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100442 // store previous phone state for management of sonification strategy below
443 int oldState = mEngine->getPhoneState();
444
445 if (mEngine->setPhoneState(state) != NO_ERROR) {
446 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700447 return;
448 }
François Gaffie2110e042015-03-24 08:41:51 +0100449 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurente552edb2014-03-10 17:42:56 -0700450 // if leaving call state, handle special case of active streams
451 // pertaining to sonification strategy see handleIncallSonification()
Eric Laurent63dea1d2015-07-02 17:10:28 -0700452 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700453 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700454 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800455 if (stream == AUDIO_STREAM_PATCH) {
456 continue;
457 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700458 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700459 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800460
Eric Laurent63dea1d2015-07-02 17:10:28 -0700461 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800462 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700463 }
464
François Gaffie2110e042015-03-24 08:41:51 +0100465 /**
466 * Switching to or from incall state or switching between telephony and VoIP lead to force
467 * routing command.
468 */
469 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
470 || (is_state_in_call(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700471
472 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700473 checkA2dpSuspend();
474 checkOutputForAllStrategies();
475 updateDevicesAndOutputs();
476
Eric Laurente552edb2014-03-10 17:42:56 -0700477 int delayMs = 0;
478 if (isStateInCall(state)) {
479 nsecs_t sysTime = systemTime();
480 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700481 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700482 // mute media and sonification strategies and delay device switch by the largest
483 // latency of any output where either strategy is active.
484 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiead3183e2015-03-18 16:55:35 +0100485 if ((isStrategyActive(desc, STRATEGY_MEDIA,
486 SONIFICATION_HEADSET_MUSIC_DELAY,
487 sysTime) ||
488 isStrategyActive(desc, STRATEGY_SONIFICATION,
489 SONIFICATION_HEADSET_MUSIC_DELAY,
490 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700491 (delayMs < (int)desc->latency()*2)) {
492 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700493 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700494 setStrategyMute(STRATEGY_MEDIA, true, desc);
495 setStrategyMute(STRATEGY_MEDIA, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700496 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
Eric Laurentc75307b2015-03-17 15:29:32 -0700497 setStrategyMute(STRATEGY_SONIFICATION, true, desc);
498 setStrategyMute(STRATEGY_SONIFICATION, false, desc, MUTE_TIME_MS,
Eric Laurente552edb2014-03-10 17:42:56 -0700499 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
500 }
501 }
502
Eric Laurent87ffa392015-05-22 10:32:38 -0700503 if (hasPrimaryOutput()) {
504 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
505 // the device returned is not necessarily reachable via this output
506 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
507 // force routing command to audio hardware when ending call
508 // even if no device change is needed
509 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
510 rxDevice = mPrimaryOutput->device();
511 }
Eric Laurente552edb2014-03-10 17:42:56 -0700512
Eric Laurent87ffa392015-05-22 10:32:38 -0700513 if (state == AUDIO_MODE_IN_CALL) {
514 updateCallRouting(rxDevice, delayMs);
515 } else if (oldState == AUDIO_MODE_IN_CALL) {
516 if (mCallRxPatch != 0) {
517 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
518 mCallRxPatch.clear();
519 }
520 if (mCallTxPatch != 0) {
521 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
522 mCallTxPatch.clear();
523 }
524 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
525 } else {
526 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700527 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700528 }
Eric Laurente552edb2014-03-10 17:42:56 -0700529 // if entering in call state, handle special case of active streams
530 // pertaining to sonification strategy see handleIncallSonification()
531 if (isStateInCall(state)) {
532 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700533 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800534 if (stream == AUDIO_STREAM_PATCH) {
535 continue;
536 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700537 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700538 }
Eric Laurent63dea1d2015-07-02 17:10:28 -0700539
540 // force reevaluating accessibility routing when call starts
541 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700542 }
543
544 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700545 if (state == AUDIO_MODE_RINGTONE &&
546 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700547 mLimitRingtoneVolume = true;
548 } else {
549 mLimitRingtoneVolume = false;
550 }
551}
552
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700553audio_mode_t AudioPolicyManager::getPhoneState() {
554 return mEngine->getPhoneState();
555}
556
Eric Laurente0720872014-03-11 09:30:41 -0700557void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700558 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700559{
François Gaffie2110e042015-03-24 08:41:51 +0100560 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -0700561
François Gaffie2110e042015-03-24 08:41:51 +0100562 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
563 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
564 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700565 }
François Gaffie2110e042015-03-24 08:41:51 +0100566 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
567 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
568 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700569
570 // check for device and output changes triggered by new force usage
571 checkA2dpSuspend();
572 checkOutputForAllStrategies();
573 updateDevicesAndOutputs();
Eric Laurent87ffa392015-05-22 10:32:38 -0700574 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700575 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
576 updateCallRouting(newDevice);
577 }
Eric Laurente552edb2014-03-10 17:42:56 -0700578 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700579 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
580 audio_devices_t newDevice = getNewOutputDevice(outputDesc, true /*fromCache*/);
581 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
582 setOutputDevice(outputDesc, newDevice, (newDevice != AUDIO_DEVICE_NONE));
Eric Laurentc2730ba2014-07-20 15:47:07 -0700583 }
Eric Laurente552edb2014-03-10 17:42:56 -0700584 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700585 applyStreamVolumes(outputDesc, newDevice, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700586 }
587 }
588
François Gaffie53615e22015-03-19 09:24:12 +0100589 audio_io_handle_t activeInput = mInputs.getActiveInput();
Eric Laurente552edb2014-03-10 17:42:56 -0700590 if (activeInput != 0) {
Eric Laurentc171c7c2015-09-25 12:21:06 -0700591 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
592 audio_devices_t newDevice = getNewInputDevice(activeInput);
593 // Force new input selection if the new device can not be reached via current input
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100594 if (activeDesc->mProfile->getSupportedDevices().types() & (newDevice & ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentc171c7c2015-09-25 12:21:06 -0700595 setInputDevice(activeInput, newDevice);
596 } else {
597 closeInput(activeInput);
598 }
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
Eric Laurente552edb2014-03-10 17:42:56 -0700600}
601
Eric Laurente0720872014-03-11 09:30:41 -0700602void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700603{
604 ALOGV("setSystemProperty() property %s, value %s", property, value);
605}
606
607// Find a direct output profile compatible with the parameters passed, even if the input flags do
608// not explicitly request a direct output
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -0800609sp<IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700610 audio_devices_t device,
611 uint32_t samplingRate,
612 audio_format_t format,
613 audio_channel_mask_t channelMask,
614 audio_output_flags_t flags)
615{
Eric Laurent861a6282015-05-18 15:40:16 -0700616 // only retain flags that will drive the direct output profile selection
617 // if explicitly requested
618 static const uint32_t kRelevantFlags =
619 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
620 flags =
621 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
622
623 sp<IOProfile> profile;
624
Eric Laurente552edb2014-03-10 17:42:56 -0700625 for (size_t i = 0; i < mHwModules.size(); i++) {
626 if (mHwModules[i]->mHandle == 0) {
627 continue;
628 }
629 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent861a6282015-05-18 15:40:16 -0700630 sp<IOProfile> curProfile = mHwModules[i]->mOutputProfiles[j];
631 if (!curProfile->isCompatibleProfile(device, String8(""),
Andy Hungf129b032015-04-07 13:45:50 -0700632 samplingRate, NULL /*updatedSamplingRate*/,
633 format, NULL /*updatedFormat*/,
634 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700635 flags)) {
636 continue;
637 }
638 // reject profiles not corresponding to a device currently available
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100639 if ((mAvailableOutputDevices.types() & curProfile->getSupportedDevicesType()) == 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700640 continue;
641 }
642 // if several profiles are compatible, give priority to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100643 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700644 continue;
645 }
646 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100647 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700648 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700649 }
Eric Laurente552edb2014-03-10 17:42:56 -0700650 }
651 }
Eric Laurent861a6282015-05-18 15:40:16 -0700652 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700653}
654
Eric Laurente0720872014-03-11 09:30:41 -0700655audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +0100656 uint32_t samplingRate,
657 audio_format_t format,
658 audio_channel_mask_t channelMask,
659 audio_output_flags_t flags,
660 const audio_offload_info_t *offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -0700661{
Eric Laurent3b73df72014-03-11 09:06:29 -0700662 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700663 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
664 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
665 device, stream, samplingRate, format, channelMask, flags);
666
Eric Laurente83b55d2014-11-14 10:06:21 -0800667 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
668 stream, samplingRate,format, channelMask,
669 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700670}
671
Eric Laurente83b55d2014-11-14 10:06:21 -0800672status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
673 audio_io_handle_t *output,
674 audio_session_t session,
675 audio_stream_type_t *stream,
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700676 uid_t uid,
Eric Laurente83b55d2014-11-14 10:06:21 -0800677 uint32_t samplingRate,
678 audio_format_t format,
679 audio_channel_mask_t channelMask,
680 audio_output_flags_t flags,
Paul McLeanaa981192015-03-21 09:55:15 -0700681 audio_port_handle_t selectedDeviceId,
Eric Laurente83b55d2014-11-14 10:06:21 -0800682 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700683{
Eric Laurente83b55d2014-11-14 10:06:21 -0800684 audio_attributes_t attributes;
685 if (attr != NULL) {
686 if (!isValidAttributes(attr)) {
687 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
688 attr->usage, attr->content_type, attr->flags,
689 attr->tags);
690 return BAD_VALUE;
691 }
692 attributes = *attr;
693 } else {
694 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
695 ALOGE("getOutputForAttr(): invalid stream type");
696 return BAD_VALUE;
697 }
698 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700699 }
Eric Laurentc75307b2015-03-17 15:29:32 -0700700 sp<SwAudioOutputDescriptor> desc;
François Gaffie036e1e92015-03-19 10:16:24 +0100701 if (mPolicyMixes.getOutputForAttr(attributes, desc) == NO_ERROR) {
702 ALOG_ASSERT(desc != 0, "Invalid desc returned by getOutputForAttr");
703 if (!audio_is_linear_pcm(format)) {
704 return BAD_VALUE;
Eric Laurent275e8e92014-11-30 15:14:47 -0800705 }
François Gaffie036e1e92015-03-19 10:16:24 +0100706 *stream = streamTypefromAttributesInt(&attributes);
707 *output = desc->mIoHandle;
708 ALOGV("getOutputForAttr() returns output %d", *output);
709 return NO_ERROR;
Eric Laurent275e8e92014-11-30 15:14:47 -0800710 }
711 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
712 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
713 return BAD_VALUE;
714 }
715
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700716 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x"
717 " session %d selectedDeviceId %d",
718 attributes.usage, attributes.content_type, attributes.tags, attributes.flags,
719 session, selectedDeviceId);
720
721 *stream = streamTypefromAttributesInt(&attributes);
722
723 // Explicit routing?
724 sp<DeviceDescriptor> deviceDesc;
725 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
726 if (mAvailableOutputDevices[i]->getId() == selectedDeviceId) {
727 deviceDesc = mAvailableOutputDevices[i];
728 break;
729 }
730 }
731 mOutputRoutes.addRoute(session, *stream, SessionRoute::SOURCE_TYPE_NA, deviceDesc, uid);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700732
Eric Laurente83b55d2014-11-14 10:06:21 -0800733 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700734 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700735
Eric Laurente83b55d2014-11-14 10:06:21 -0800736 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700737 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
738 }
739
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700740 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700741 device, samplingRate, format, channelMask, flags);
742
Eric Laurente83b55d2014-11-14 10:06:21 -0800743 *output = getOutputForDevice(device, session, *stream,
744 samplingRate, format, channelMask,
745 flags, offloadInfo);
746 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -0700747 mOutputRoutes.removeRoute(session);
Eric Laurente83b55d2014-11-14 10:06:21 -0800748 return INVALID_OPERATION;
749 }
Paul McLeanaa981192015-03-21 09:55:15 -0700750
Eric Laurente83b55d2014-11-14 10:06:21 -0800751 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700752}
753
754audio_io_handle_t AudioPolicyManager::getOutputForDevice(
755 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800756 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700757 audio_stream_type_t stream,
758 uint32_t samplingRate,
759 audio_format_t format,
760 audio_channel_mask_t channelMask,
761 audio_output_flags_t flags,
762 const audio_offload_info_t *offloadInfo)
763{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700764 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700765 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700766 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700767
Eric Laurente552edb2014-03-10 17:42:56 -0700768#ifdef AUDIO_POLICY_TEST
769 if (mCurOutput != 0) {
770 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
771 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
772
773 if (mTestOutputs[mCurOutput] == 0) {
774 ALOGV("getOutput() opening test output");
Eric Laurentc75307b2015-03-17 15:29:32 -0700775 sp<AudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(NULL,
776 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700777 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700778 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700779 outputDesc->mFlags =
780 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700781 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700782 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
783 config.sample_rate = mTestSamplingRate;
784 config.channel_mask = mTestChannels;
785 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -0700786 if (offloadInfo != NULL) {
787 config.offload_info = *offloadInfo;
788 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700789 status = mpClientInterface->openOutput(0,
790 &mTestOutputs[mCurOutput],
791 &config,
792 &outputDesc->mDevice,
793 String8(""),
794 &outputDesc->mLatency,
795 outputDesc->mFlags);
796 if (status == NO_ERROR) {
797 outputDesc->mSamplingRate = config.sample_rate;
798 outputDesc->mFormat = config.format;
799 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700800 AudioParameter outputCmd = AudioParameter();
801 outputCmd.addInt(String8("set_id"),mCurOutput);
802 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
803 addOutput(mTestOutputs[mCurOutput], outputDesc);
804 }
805 }
806 return mTestOutputs[mCurOutput];
807 }
808#endif //AUDIO_POLICY_TEST
809
810 // open a direct output if required by specified parameters
811 //force direct flag if offload flag is set: offloading implies a direct output stream
812 // and all common behaviors are driven by checking only the direct flag
813 // this should normally be set appropriately in the policy configuration file
814 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700815 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700816 }
Eric Laurent93c3d412014-08-01 14:48:35 -0700817 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
818 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
819 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800820 // only allow deep buffering for music stream type
821 if (stream != AUDIO_STREAM_MUSIC) {
822 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -0700823 } else if (/* stream == AUDIO_STREAM_MUSIC && */
824 flags == AUDIO_OUTPUT_FLAG_NONE &&
825 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
826 // use DEEP_BUFFER as default output for music stream type
827 flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -0800828 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -0700829 if (stream == AUDIO_STREAM_TTS) {
830 flags = AUDIO_OUTPUT_FLAG_TTS;
831 }
Eric Laurente552edb2014-03-10 17:42:56 -0700832
Eric Laurentb732cf52014-09-24 19:08:21 -0700833 sp<IOProfile> profile;
834
835 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -0700836 // and not explicitly requested
837 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
838 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -0700839 audio_channel_count_from_out_mask(channelMask) <= 2) {
840 goto non_direct_output;
841 }
842
Eric Laurente552edb2014-03-10 17:42:56 -0700843 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
844 // creating an offloaded track and tearing it down immediately after start when audioflinger
845 // detects there is an active non offloadable effect.
846 // FIXME: We should check the audio session here but we do not have it in this context.
847 // This may prevent offloading in rare situations where effects are left active by apps
848 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -0700849
Eric Laurente552edb2014-03-10 17:42:56 -0700850 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
François Gaffie45ed3b02015-03-19 10:35:14 +0100851 !mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -0700852 profile = getProfileForDirectOutput(device,
853 samplingRate,
854 format,
855 channelMask,
856 (audio_output_flags_t)flags);
857 }
858
Eric Laurent1c333e22014-05-20 10:48:17 -0700859 if (profile != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700860 sp<SwAudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700861
862 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700863 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
865 outputDesc = desc;
866 // reuse direct output if currently open and configured with same parameters
867 if ((samplingRate == outputDesc->mSamplingRate) &&
868 (format == outputDesc->mFormat) &&
869 (channelMask == outputDesc->mChannelMask)) {
870 outputDesc->mDirectOpenCount++;
871 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
872 return mOutputs.keyAt(i);
873 }
874 }
875 }
876 // close direct output if currently open and configured with different parameters
877 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700878 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700879 }
Eric Laurent861a6282015-05-18 15:40:16 -0700880
881 // if the selected profile is offloaded and no offload info was specified,
882 // create a default one
883 audio_offload_info_t defaultOffloadInfo = AUDIO_INFO_INITIALIZER;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100884 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) && !offloadInfo) {
Eric Laurent861a6282015-05-18 15:40:16 -0700885 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
886 defaultOffloadInfo.sample_rate = samplingRate;
887 defaultOffloadInfo.channel_mask = channelMask;
888 defaultOffloadInfo.format = format;
889 defaultOffloadInfo.stream_type = stream;
890 defaultOffloadInfo.bit_rate = 0;
891 defaultOffloadInfo.duration_us = -1;
892 defaultOffloadInfo.has_video = true; // conservative
893 defaultOffloadInfo.is_streaming = true; // likely
894 offloadInfo = &defaultOffloadInfo;
895 }
896
Eric Laurentc75307b2015-03-17 15:29:32 -0700897 outputDesc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -0700898 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700899 outputDesc->mLatency = 0;
Eric Laurent861a6282015-05-18 15:40:16 -0700900 outputDesc->mFlags = (audio_output_flags_t)(outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700901 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
902 config.sample_rate = samplingRate;
903 config.channel_mask = channelMask;
904 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -0700905 if (offloadInfo != NULL) {
906 config.offload_info = *offloadInfo;
907 }
Eric Laurent322b4d22015-04-03 15:57:54 -0700908 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -0700909 &output,
910 &config,
911 &outputDesc->mDevice,
912 String8(""),
913 &outputDesc->mLatency,
914 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700915
916 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700917 if (status != NO_ERROR ||
918 (samplingRate != 0 && samplingRate != config.sample_rate) ||
919 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
920 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700921 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
922 "format %d %d, channelMask %04x %04x", output, samplingRate,
923 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
924 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700925 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700926 mpClientInterface->closeOutput(output);
927 }
Eric Laurenta82797f2015-01-30 11:49:43 -0800928 // fall back to mixer output if possible when the direct output could not be open
929 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
930 goto non_direct_output;
931 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700932 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700934 outputDesc->mSamplingRate = config.sample_rate;
935 outputDesc->mChannelMask = config.channel_mask;
936 outputDesc->mFormat = config.format;
937 outputDesc->mRefCount[stream] = 0;
938 outputDesc->mStopTime[stream] = 0;
939 outputDesc->mDirectOpenCount = 1;
940
Eric Laurente552edb2014-03-10 17:42:56 -0700941 audio_io_handle_t srcOutput = getOutputForEffect();
942 addOutput(output, outputDesc);
943 audio_io_handle_t dstOutput = getOutputForEffect();
944 if (dstOutput == output) {
945 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
946 }
947 mPreviousOutputs = mOutputs;
948 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700949 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700950 return output;
951 }
952
Eric Laurentb732cf52014-09-24 19:08:21 -0700953non_direct_output:
Eric Laurente552edb2014-03-10 17:42:56 -0700954 // ignoring channel mask due to downmix capability in mixer
955
956 // open a non direct output
957
958 // for non direct outputs, only PCM is supported
959 if (audio_is_linear_pcm(format)) {
960 // get which output is suitable for the specified stream. The actual
961 // routing change will happen when startOutput() will be called
962 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
963
Eric Laurent8838a382014-09-08 16:44:28 -0700964 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
965 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
966 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
968 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
969 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
970
Paul McLeanaa981192015-03-21 09:55:15 -0700971 ALOGV(" getOutputForDevice() returns output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -0700972
973 return output;
974}
975
Eric Laurente0720872014-03-11 09:30:41 -0700976audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -0700977 audio_output_flags_t flags,
978 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -0700979{
980 // select one output among several that provide a path to a particular device or set of
981 // devices (the list was previously build by getOutputsForDevice()).
982 // The priority is as follows:
983 // 1: the output with the highest number of requested policy flags
984 // 2: the primary output
985 // 3: the first output in the list
986
987 if (outputs.size() == 0) {
988 return 0;
989 }
990 if (outputs.size() == 1) {
991 return outputs[0];
992 }
993
994 int maxCommonFlags = 0;
995 audio_io_handle_t outputFlags = 0;
996 audio_io_handle_t outputPrimary = 0;
997
998 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700999 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001000 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001001 // if a valid format is specified, skip output if not compatible
1002 if (format != AUDIO_FORMAT_INVALID) {
1003 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1004 if (format != outputDesc->mFormat) {
1005 continue;
1006 }
1007 } else if (!audio_is_linear_pcm(format)) {
1008 continue;
1009 }
1010 }
1011
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001012 int commonFlags = popcount(outputDesc->mProfile->getFlags() & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001013 if (commonFlags > maxCommonFlags) {
1014 outputFlags = outputs[i];
1015 maxCommonFlags = commonFlags;
1016 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1017 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01001018 if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurente552edb2014-03-10 17:42:56 -07001019 outputPrimary = outputs[i];
1020 }
1021 }
1022 }
1023
1024 if (outputFlags != 0) {
1025 return outputFlags;
1026 }
1027 if (outputPrimary != 0) {
1028 return outputPrimary;
1029 }
1030
1031 return outputs[0];
1032}
1033
Eric Laurente0720872014-03-11 09:30:41 -07001034status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001035 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001036 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001037{
Paul McLeanaa981192015-03-21 09:55:15 -07001038 ALOGV("startOutput() output %d, stream %d, session %d",
1039 output, stream, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001040 ssize_t index = mOutputs.indexOfKey(output);
1041 if (index < 0) {
1042 ALOGW("startOutput() unknown output %d", output);
1043 return BAD_VALUE;
1044 }
1045
Eric Laurentc75307b2015-03-17 15:29:32 -07001046 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1047
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001048 // Routing?
1049 mOutputRoutes.incRouteActivity(session);
1050
Eric Laurentc75307b2015-03-17 15:29:32 -07001051 audio_devices_t newDevice;
1052 if (outputDesc->mPolicyMix != NULL) {
1053 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent493404d2015-04-21 15:07:36 -07001054 } else if (mOutputRoutes.hasRouteChanged(session)) {
1055 newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001056 checkStrategyRoute(getStrategy(stream), output);
Eric Laurentc75307b2015-03-17 15:29:32 -07001057 } else {
1058 newDevice = AUDIO_DEVICE_NONE;
1059 }
1060
1061 uint32_t delayMs = 0;
1062
Eric Laurentc75307b2015-03-17 15:29:32 -07001063 status_t status = startSource(outputDesc, stream, newDevice, &delayMs);
1064
1065 if (status != NO_ERROR) {
1066 mOutputRoutes.decRouteActivity(session);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001067 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001068 }
1069 // Automatically enable the remote submix input when output is started on a re routing mix
1070 // of type MIX_TYPE_RECORDERS
1071 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1072 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1073 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1074 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1075 outputDesc->mPolicyMix->mRegistrationId,
1076 "remote-submix");
1077 }
1078
1079 if (delayMs != 0) {
1080 usleep(delayMs * 1000);
1081 }
1082
1083 return status;
1084}
1085
1086status_t AudioPolicyManager::startSource(sp<AudioOutputDescriptor> outputDesc,
1087 audio_stream_type_t stream,
1088 audio_devices_t device,
1089 uint32_t *delayMs)
1090{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001091 // cannot start playback of STREAM_TTS if any other output is being used
1092 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001093
1094 *delayMs = 0;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001095 if (stream == AUDIO_STREAM_TTS) {
1096 ALOGV("\t found BEACON stream");
Eric Laurent9459fb02015-08-12 18:36:32 -07001097 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001098 return INVALID_OPERATION;
1099 } else {
1100 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1101 }
1102 } else {
1103 // some playback other than beacon starts
1104 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1105 }
1106
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001107 // check active before incrementing usage count
1108 bool force = !outputDesc->isActive();
1109
Eric Laurente552edb2014-03-10 17:42:56 -07001110 // increment usage count for this stream on the requested output:
1111 // NOTE that the usage count is the same for duplicated output and hardware output which is
1112 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1113 outputDesc->changeRefCount(stream, 1);
1114
Eric Laurent493404d2015-04-21 15:07:36 -07001115 if (outputDesc->mRefCount[stream] == 1 || device != AUDIO_DEVICE_NONE) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001116 // starting an output being rerouted?
Eric Laurentc75307b2015-03-17 15:29:32 -07001117 if (device == AUDIO_DEVICE_NONE) {
1118 device = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001119 }
Eric Laurente552edb2014-03-10 17:42:56 -07001120 routing_strategy strategy = getStrategy(stream);
1121 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001122 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1123 (beaconMuteLatency > 0);
1124 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001125 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001126 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001127 if (desc != outputDesc) {
1128 // force a device change if any other output is managed by the same hw
1129 // module and has a current device selection that differs from selected device.
1130 // In this case, the audio HAL must receive the new device selection so that it can
1131 // change the device currently selected by the other active output.
1132 if (outputDesc->sharesHwModuleWith(desc) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07001133 desc->device() != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07001134 force = true;
1135 }
1136 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001137 // a notification so that audio focus effect can propagate, or that a mute/unmute
1138 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001139 uint32_t latency = desc->latency();
1140 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1141 waitMs = latency;
1142 }
1143 }
1144 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001145 uint32_t muteWaitMs = setOutputDevice(outputDesc, device, force);
Eric Laurente552edb2014-03-10 17:42:56 -07001146
1147 // handle special case for sonification while in call
1148 if (isInCall()) {
1149 handleIncallSonification(stream, true, false);
1150 }
1151
1152 // apply volume rules for current stream and device if necessary
1153 checkAndSetVolume(stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07001154 mStreams.valueFor(stream).getVolumeIndex(device),
1155 outputDesc,
1156 device);
Eric Laurente552edb2014-03-10 17:42:56 -07001157
1158 // update the outputs if starting an output with a stream that can affect notification
1159 // routing
1160 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001161
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001162 // force reevaluating accessibility routing when ringtone or alarm starts
1163 if (strategy == STRATEGY_SONIFICATION) {
1164 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1165 }
Eric Laurente552edb2014-03-10 17:42:56 -07001166 }
1167 return NO_ERROR;
1168}
1169
1170
Eric Laurente0720872014-03-11 09:30:41 -07001171status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001172 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001173 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001174{
1175 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1176 ssize_t index = mOutputs.indexOfKey(output);
1177 if (index < 0) {
1178 ALOGW("stopOutput() unknown output %d", output);
1179 return BAD_VALUE;
1180 }
1181
Eric Laurentc75307b2015-03-17 15:29:32 -07001182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001183
Eric Laurentc75307b2015-03-17 15:29:32 -07001184 if (outputDesc->mRefCount[stream] == 1) {
1185 // Automatically disable the remote submix input when output is stopped on a
1186 // re routing mix of type MIX_TYPE_RECORDERS
1187 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1188 outputDesc->mPolicyMix != NULL &&
1189 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
1190 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1191 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1192 outputDesc->mPolicyMix->mRegistrationId,
1193 "remote-submix");
1194 }
1195 }
1196
1197 // Routing?
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001198 bool forceDeviceUpdate = false;
Eric Laurentc75307b2015-03-17 15:29:32 -07001199 if (outputDesc->mRefCount[stream] > 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001200 int activityCount = mOutputRoutes.decRouteActivity(session);
1201 forceDeviceUpdate = (mOutputRoutes.hasRoute(session) && (activityCount == 0));
1202
1203 if (forceDeviceUpdate) {
1204 checkStrategyRoute(getStrategy(stream), AUDIO_IO_HANDLE_NONE);
1205 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001206 }
1207
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001208 return stopSource(outputDesc, stream, forceDeviceUpdate);
Eric Laurentc75307b2015-03-17 15:29:32 -07001209}
1210
1211status_t AudioPolicyManager::stopSource(sp<AudioOutputDescriptor> outputDesc,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001212 audio_stream_type_t stream,
1213 bool forceDeviceUpdate)
Eric Laurentc75307b2015-03-17 15:29:32 -07001214{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001215 // always handle stream stop, check which stream type is stopping
1216 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1217
Eric Laurente552edb2014-03-10 17:42:56 -07001218 // handle special case for sonification while in call
1219 if (isInCall()) {
1220 handleIncallSonification(stream, false, false);
1221 }
1222
1223 if (outputDesc->mRefCount[stream] > 0) {
1224 // decrement usage count of this stream on the output
1225 outputDesc->changeRefCount(stream, -1);
Paul McLeanaa981192015-03-21 09:55:15 -07001226
Eric Laurente552edb2014-03-10 17:42:56 -07001227 // store time at which the stream was stopped - see isStreamActive()
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001228 if (outputDesc->mRefCount[stream] == 0 || forceDeviceUpdate) {
Eric Laurente552edb2014-03-10 17:42:56 -07001229 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentc75307b2015-03-17 15:29:32 -07001230 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001231 // delay the device switch by twice the latency because stopOutput() is executed when
1232 // the track stop() command is received and at that time the audio track buffer can
1233 // still contain data that needs to be drained. The latency only covers the audio HAL
1234 // and kernel buffers. Also the latency does not always include additional delay in the
1235 // audio path (audio DSP, CODEC ...)
Eric Laurentc75307b2015-03-17 15:29:32 -07001236 setOutputDevice(outputDesc, newDevice, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001237
1238 // force restoring the device selection on other active outputs if it differs from the
1239 // one being selected for this output
1240 for (size_t i = 0; i < mOutputs.size(); i++) {
1241 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001242 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07001243 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07001244 desc->isActive() &&
1245 outputDesc->sharesHwModuleWith(desc) &&
1246 (newDevice != desc->device())) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001247 setOutputDevice(desc,
1248 getNewOutputDevice(desc, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001249 true,
Eric Laurentc75307b2015-03-17 15:29:32 -07001250 outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07001251 }
1252 }
1253 // update the outputs if stopping one with a stream that can affect notification routing
1254 handleNotificationRoutingForStream(stream);
1255 }
1256 return NO_ERROR;
1257 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07001258 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07001259 return INVALID_OPERATION;
1260 }
1261}
1262
Eric Laurente83b55d2014-11-14 10:06:21 -08001263void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001264 audio_stream_type_t stream __unused,
1265 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001266{
1267 ALOGV("releaseOutput() %d", output);
1268 ssize_t index = mOutputs.indexOfKey(output);
1269 if (index < 0) {
1270 ALOGW("releaseOutput() releasing unknown output %d", output);
1271 return;
1272 }
1273
1274#ifdef AUDIO_POLICY_TEST
1275 int testIndex = testOutputIndex(output);
1276 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001277 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001278 if (outputDesc->isActive()) {
1279 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01001280 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001281 mTestOutputs[testIndex] = 0;
1282 }
1283 return;
1284 }
1285#endif //AUDIO_POLICY_TEST
1286
Paul McLeanaa981192015-03-21 09:55:15 -07001287 // Routing
1288 mOutputRoutes.removeRoute(session);
1289
Eric Laurentc75307b2015-03-17 15:29:32 -07001290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001291 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001292 if (desc->mDirectOpenCount <= 0) {
1293 ALOGW("releaseOutput() invalid open count %d for output %d",
1294 desc->mDirectOpenCount, output);
1295 return;
1296 }
1297 if (--desc->mDirectOpenCount == 0) {
1298 closeOutput(output);
1299 // If effects where present on the output, audioflinger moved them to the primary
1300 // output by default: move them back to the appropriate output.
1301 audio_io_handle_t dstOutput = getOutputForEffect();
Eric Laurent87ffa392015-05-22 10:32:38 -07001302 if (hasPrimaryOutput() && dstOutput != mPrimaryOutput->mIoHandle) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001303 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX,
1304 mPrimaryOutput->mIoHandle, dstOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07001305 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001306 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001307 }
1308 }
1309}
1310
1311
Eric Laurentcaf7f482014-11-25 17:50:47 -08001312status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1313 audio_io_handle_t *input,
1314 audio_session_t session,
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001315 uid_t uid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001316 uint32_t samplingRate,
1317 audio_format_t format,
1318 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001319 audio_input_flags_t flags,
Paul McLean466dc8e2015-04-17 13:15:36 -06001320 audio_port_handle_t selectedDeviceId,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001321 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001322{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001323 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1324 "session %d, flags %#x",
1325 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001326
Eric Laurentcaf7f482014-11-25 17:50:47 -08001327 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001328 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001329 audio_devices_t device;
1330 // handle legacy remote submix case where the address was not always specified
1331 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001332 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001333 audio_source_t inputSource = attr->source;
1334 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001335 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001336
Eric Laurentc447ded2015-01-06 08:47:05 -08001337 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1338 inputSource = AUDIO_SOURCE_MIC;
1339 }
1340 halInputSource = inputSource;
1341
Paul McLean466dc8e2015-04-17 13:15:36 -06001342 // Explicit routing?
1343 sp<DeviceDescriptor> deviceDesc;
1344 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1345 if (mAvailableInputDevices[i]->getId() == selectedDeviceId) {
1346 deviceDesc = mAvailableInputDevices[i];
1347 break;
1348 }
1349 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001350 mInputRoutes.addRoute(session, SessionRoute::STREAM_TYPE_NA, inputSource, deviceDesc, uid);
Paul McLean466dc8e2015-04-17 13:15:36 -06001351
Eric Laurentc447ded2015-01-06 08:47:05 -08001352 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001353 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001354 status_t ret = mPolicyMixes.getInputMixForAttr(*attr, &policyMix);
François Gaffie036e1e92015-03-19 10:16:24 +01001355 if (ret != NO_ERROR) {
1356 return ret;
1357 }
1358 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001359 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1360 address = String8(attr->tags + strlen("addr="));
Eric Laurent275e8e92014-11-30 15:14:47 -08001361 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001362 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001363 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001364 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001365 return BAD_VALUE;
1366 }
Eric Laurentc722f302014-12-10 11:21:49 -08001367 if (policyMix != NULL) {
1368 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001369 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1370 // there is an external policy, but this input is attached to a mix of recorders,
1371 // meaning it receives audio injected into the framework, so the recorder doesn't
1372 // know about it and is therefore considered "legacy"
1373 *inputType = API_INPUT_LEGACY;
1374 } else {
1375 // recording a mix of players defined by an external policy, we're rerouting for
1376 // an external policy
1377 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1378 }
Eric Laurentc722f302014-12-10 11:21:49 -08001379 } else if (audio_is_remote_submix_device(device)) {
1380 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001381 *inputType = API_INPUT_MIX_CAPTURE;
Eric Laurent82db2692015-08-07 13:59:42 -07001382 } else if (device == AUDIO_DEVICE_IN_TELEPHONY_RX) {
1383 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001384 } else {
1385 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001386 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07001387
Eric Laurentc447ded2015-01-06 08:47:05 -08001388 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001389 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1390 if (index >= 0) {
1391 *input = mSoundTriggerSessions.valueFor(session);
1392 isSoundTrigger = true;
1393 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1394 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1395 } else {
1396 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1397 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001398 }
1399 }
1400
Andy Hungf129b032015-04-07 13:45:50 -07001401 // find a compatible input profile (not necessarily identical in parameters)
1402 sp<IOProfile> profile;
1403 // samplingRate and flags may be updated by getInputProfile
1404 uint32_t profileSamplingRate = samplingRate;
1405 audio_format_t profileFormat = format;
1406 audio_channel_mask_t profileChannelMask = channelMask;
1407 audio_input_flags_t profileFlags = flags;
1408 for (;;) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001409 profile = getInputProfile(device, address,
Andy Hungf129b032015-04-07 13:45:50 -07001410 profileSamplingRate, profileFormat, profileChannelMask,
1411 profileFlags);
1412 if (profile != 0) {
1413 break; // success
1414 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
1415 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
1416 } else { // fail
Eric Laurentcaf7f482014-11-25 17:50:47 -08001417 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1418 "format %#x, channelMask 0x%X, flags %#x",
Andy Hungf129b032015-04-07 13:45:50 -07001419 device, samplingRate, format, channelMask, flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001420 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001421 }
Eric Laurente552edb2014-03-10 17:42:56 -07001422 }
1423
Eric Laurent322b4d22015-04-03 15:57:54 -07001424 if (profile->getModuleHandle() == 0) {
1425 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurentcaf7f482014-11-25 17:50:47 -08001426 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001427 }
1428
1429 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
Andy Hungf129b032015-04-07 13:45:50 -07001430 config.sample_rate = profileSamplingRate;
1431 config.channel_mask = profileChannelMask;
1432 config.format = profileFormat;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001433
Eric Laurent322b4d22015-04-03 15:57:54 -07001434 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcaf7f482014-11-25 17:50:47 -08001435 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001436 &config,
1437 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001438 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001439 halInputSource,
Andy Hungf129b032015-04-07 13:45:50 -07001440 profileFlags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001441
1442 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001443 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Andy Hungf129b032015-04-07 13:45:50 -07001444 (profileSamplingRate != config.sample_rate) ||
1445 (profileFormat != config.format) ||
1446 (profileChannelMask != config.channel_mask)) {
1447 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d,"
1448 " channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001449 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001450 if (*input != AUDIO_IO_HANDLE_NONE) {
1451 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001452 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001453 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001454 }
1455
Eric Laurent1f2f2232014-06-02 12:01:23 -07001456 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001457 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001458 inputDesc->mRefCount = 0;
1459 inputDesc->mOpenRefCount = 1;
Andy Hungf129b032015-04-07 13:45:50 -07001460 inputDesc->mSamplingRate = profileSamplingRate;
1461 inputDesc->mFormat = profileFormat;
1462 inputDesc->mChannelMask = profileChannelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001463 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001464 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001465 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001466 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001467
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07001468 ALOGV("getInputForAttr() returns input type = %d", *inputType);
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001469
Eric Laurentcaf7f482014-11-25 17:50:47 -08001470 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001471 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06001472
Eric Laurentcaf7f482014-11-25 17:50:47 -08001473 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001474}
1475
Eric Laurent4dc68062014-07-28 17:26:49 -07001476status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1477 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001478{
1479 ALOGV("startInput() input %d", input);
1480 ssize_t index = mInputs.indexOfKey(input);
1481 if (index < 0) {
1482 ALOGW("startInput() unknown input %d", input);
1483 return BAD_VALUE;
1484 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001485 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001486
Eric Laurentc722f302014-12-10 11:21:49 -08001487 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001488 if (index < 0) {
1489 ALOGW("startInput() unknown session %d on input %d", session, input);
1490 return BAD_VALUE;
1491 }
1492
Glenn Kasten74a8e252014-07-24 14:09:55 -07001493 // virtual input devices are compatible with other input devices
François Gaffie53615e22015-03-19 09:24:12 +01001494 if (!is_virtual_input_device(inputDesc->mDevice)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001495
1496 // for a non-virtual input device, check if there is another (non-virtual) active input
François Gaffie53615e22015-03-19 09:24:12 +01001497 audio_io_handle_t activeInput = mInputs.getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001498 if (activeInput != 0 && activeInput != input) {
1499
1500 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1501 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001502 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurent64265b22015-09-18 18:32:07 -07001503 if ((activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) &&
1504 !activeDesc->hasPreemptedSession(session)) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001505 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent64265b22015-09-18 18:32:07 -07001506 audio_session_t activeSession = activeDesc->mSessions.itemAt(0);
1507 SortedVector<audio_session_t> sessions = activeDesc->getPreemptedSessions();
1508 sessions.add(activeSession);
1509 inputDesc->setPreemptedSessions(sessions);
1510 stopInput(activeInput, activeSession);
1511 releaseInput(activeInput, activeSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001512 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001513 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001514 return INVALID_OPERATION;
1515 }
1516 }
Eric Laurentc0a889f2015-10-14 14:36:34 -07001517
1518 // Do not allow capture if an active voice call is using a software patch and
1519 // the call TX source device is on the same HW module.
1520 // FIXME: would be better to refine to only inputs whose profile connects to the
1521 // call TX device but this information is not in the audio patch
1522 if (mCallTxPatch != 0 &&
1523 inputDesc->getModuleHandle() == mCallTxPatch->mPatch.sources[0].ext.device.hw_module) {
1524 return INVALID_OPERATION;
1525 }
Eric Laurente552edb2014-03-10 17:42:56 -07001526 }
1527
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001528 // Routing?
1529 mInputRoutes.incRouteActivity(session);
1530
Paul McLean466dc8e2015-04-17 13:15:36 -06001531 if (inputDesc->mRefCount == 0 || mInputRoutes.hasRouteChanged(session)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001532 // if input maps to a dynamic policy with an activity listener, notify of state change
1533 if ((inputDesc->mPolicyMix != NULL)
Jean-Michel Trivif613d422015-04-23 18:41:29 -07001534 && ((inputDesc->mPolicyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
Jean-Michel Trivi2b0c1fc2015-04-15 17:29:28 -07001535 mpClientInterface->onDynamicPolicyMixStateUpdate(inputDesc->mPolicyMix->mRegistrationId,
1536 MIX_STATE_MIXING);
1537 }
1538
François Gaffie53615e22015-03-19 09:24:12 +01001539 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001540 SoundTrigger::setCaptureState(true);
1541 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001542 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001543
Eric Laurentc722f302014-12-10 11:21:49 -08001544 // automatically enable the remote submix output when input is started if not
1545 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001546 // For remote submix (a virtual device), we open only one input per capture request.
1547 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001548 String8 address = String8("");
1549 if (inputDesc->mPolicyMix == NULL) {
1550 address = String8("0");
1551 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1552 address = inputDesc->mPolicyMix->mRegistrationId;
1553 }
1554 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001555 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001556 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001557 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001558 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001559 }
Eric Laurente552edb2014-03-10 17:42:56 -07001560 }
1561
Eric Laurente552edb2014-03-10 17:42:56 -07001562 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1563
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001564 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001565 return NO_ERROR;
1566}
1567
Eric Laurent4dc68062014-07-28 17:26:49 -07001568status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1569 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001570{
1571 ALOGV("stopInput() input %d", input);
1572 ssize_t index = mInputs.indexOfKey(input);
1573 if (index < 0) {
1574 ALOGW("stopInput() unknown input %d", input);
1575 return BAD_VALUE;
1576 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001577 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001578
Eric Laurentc722f302014-12-10 11:21:49 -08001579 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001580 if (index < 0) {
1581 ALOGW("stopInput() unknown session %d on input %d", session, input);
1582 return BAD_VALUE;
1583 }
1584
Eric Laurente552edb2014-03-10 17:42:56 -07001585 if (inputDesc->mRefCount == 0) {
1586 ALOGW("stopInput() input %d already stopped", input);
1587 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001588 }
1589
1590 inputDesc->mRefCount--;
Paul McLean466dc8e2015-04-17 13:15:36 -06001591
1592 // Routing?
1593 mInputRoutes.decRouteActivity(session);
1594
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001595 if (inputDesc->mRefCount == 0) {
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_IDLE);
1601 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001602
Eric Laurentc722f302014-12-10 11:21:49 -08001603 // automatically disable the remote submix output when input is stopped if not
1604 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001605 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001606 String8 address = String8("");
1607 if (inputDesc->mPolicyMix == NULL) {
1608 address = String8("0");
1609 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1610 address = inputDesc->mPolicyMix->mRegistrationId;
1611 }
1612 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001613 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001614 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001615 address, "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001616 }
Eric Laurente552edb2014-03-10 17:42:56 -07001617 }
1618
Eric Laurent1c333e22014-05-20 10:48:17 -07001619 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001620
François Gaffie53615e22015-03-19 09:24:12 +01001621 if (mInputs.activeInputsCount() == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001622 SoundTrigger::setCaptureState(false);
1623 }
Eric Laurent64265b22015-09-18 18:32:07 -07001624 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07001625 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001626 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001627}
1628
Eric Laurent4dc68062014-07-28 17:26:49 -07001629void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1630 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001631{
1632 ALOGV("releaseInput() %d", input);
1633 ssize_t index = mInputs.indexOfKey(input);
1634 if (index < 0) {
1635 ALOGW("releaseInput() releasing unknown input %d", input);
1636 return;
1637 }
Paul McLean466dc8e2015-04-17 13:15:36 -06001638
1639 // Routing
1640 mInputRoutes.removeRoute(session);
1641
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001642 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1643 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001644
Eric Laurentc722f302014-12-10 11:21:49 -08001645 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001646 if (index < 0) {
1647 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1648 return;
1649 }
Eric Laurentc722f302014-12-10 11:21:49 -08001650 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001651 if (inputDesc->mOpenRefCount == 0) {
1652 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1653 return;
1654 }
1655 inputDesc->mOpenRefCount--;
1656 if (inputDesc->mOpenRefCount > 0) {
1657 ALOGV("releaseInput() exit > 0");
1658 return;
1659 }
1660
Eric Laurent05b90f82014-08-27 15:32:29 -07001661 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001662 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001663 ALOGV("releaseInput() exit");
1664}
1665
Eric Laurentd4692962014-05-05 18:13:44 -07001666void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001667 bool patchRemoved = false;
1668
Eric Laurentd4692962014-05-05 18:13:44 -07001669 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001670 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1671 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1672 if (patch_index >= 0) {
1673 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1674 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1675 mAudioPatches.removeItemsAt(patch_index);
1676 patchRemoved = true;
1677 }
Eric Laurentd4692962014-05-05 18:13:44 -07001678 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1679 }
1680 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001681 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001682
1683 if (patchRemoved) {
1684 mpClientInterface->onAudioPatchListUpdate();
1685 }
Eric Laurentd4692962014-05-05 18:13:44 -07001686}
1687
Eric Laurente0720872014-03-11 09:30:41 -07001688void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001689 int indexMin,
1690 int indexMax)
1691{
1692 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
François Gaffie2110e042015-03-24 08:41:51 +01001693 mEngine->initStreamVolume(stream, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001694 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1695 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffie2110e042015-03-24 08:41:51 +01001696 mEngine->initStreamVolume(AUDIO_STREAM_ACCESSIBILITY, indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001697 }
Eric Laurente552edb2014-03-10 17:42:56 -07001698}
1699
Eric Laurente0720872014-03-11 09:30:41 -07001700status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01001701 int index,
1702 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07001703{
1704
Eric Laurentc75307b2015-03-17 15:29:32 -07001705 if ((index < mStreams.valueFor(stream).getVolumeIndexMin()) ||
1706 (index > mStreams.valueFor(stream).getVolumeIndexMax())) {
Eric Laurente552edb2014-03-10 17:42:56 -07001707 return BAD_VALUE;
1708 }
1709 if (!audio_is_output_device(device)) {
1710 return BAD_VALUE;
1711 }
1712
1713 // Force max volume if stream cannot be muted
Eric Laurentc75307b2015-03-17 15:29:32 -07001714 if (!mStreams.canBeMuted(stream)) index = mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07001715
1716 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1717 stream, device, index);
1718
1719 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1720 // clear all device specific values
1721 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
François Gaffiedfd74092015-03-19 12:10:59 +01001722 mStreams.clearCurrentVolumeIndex(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07001723 }
François Gaffiedfd74092015-03-19 12:10:59 +01001724 mStreams.addCurrentVolumeIndex(stream, device, index);
Eric Laurente552edb2014-03-10 17:42:56 -07001725
Eric Laurent31551f82014-10-10 18:21:56 -07001726 // update volume on all outputs whose current device is also selected by the same
1727 // strategy as the device specified by the caller
1728 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001729
1730
1731 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1732 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1733 if (stream == AUDIO_STREAM_MUSIC) {
François Gaffiedfd74092015-03-19 12:10:59 +01001734 mStreams.addCurrentVolumeIndex(AUDIO_STREAM_ACCESSIBILITY, device, index);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001735 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1736 }
1737 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1738 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001739 return NO_ERROR;
1740 }
Eric Laurente552edb2014-03-10 17:42:56 -07001741 status_t status = NO_ERROR;
1742 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001743 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1744 audio_devices_t curDevice = Volume::getDeviceForVolume(desc->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001745 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001746 status_t volStatus = checkAndSetVolume(stream, index, desc, curDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07001747 if (volStatus != NO_ERROR) {
1748 status = volStatus;
1749 }
1750 }
Jean-Michel Triviaf20bc22015-09-14 16:37:07 -07001751 if ((accessibilityDevice != AUDIO_DEVICE_NONE) &&
1752 ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)))
1753 {
Eric Laurent223fd5c2014-11-11 13:43:36 -08001754 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
Eric Laurentc75307b2015-03-17 15:29:32 -07001755 index, desc, curDevice);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001756 }
Eric Laurente552edb2014-03-10 17:42:56 -07001757 }
1758 return status;
1759}
1760
Eric Laurente0720872014-03-11 09:30:41 -07001761status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001762 int *index,
1763 audio_devices_t device)
1764{
1765 if (index == NULL) {
1766 return BAD_VALUE;
1767 }
1768 if (!audio_is_output_device(device)) {
1769 return BAD_VALUE;
1770 }
1771 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1772 // the strategy the stream belongs to.
1773 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1774 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1775 }
François Gaffiedfd74092015-03-19 12:10:59 +01001776 device = Volume::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001777
Eric Laurentc75307b2015-03-17 15:29:32 -07001778 *index = mStreams.valueFor(stream).getVolumeIndex(device);
Eric Laurente552edb2014-03-10 17:42:56 -07001779 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1780 return NO_ERROR;
1781}
1782
Eric Laurente0720872014-03-11 09:30:41 -07001783audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001784 const SortedVector<audio_io_handle_t>& outputs)
1785{
1786 // select one output among several suitable for global effects.
1787 // The priority is as follows:
1788 // 1: An offloaded output. If the effect ends up not being offloadable,
1789 // AudioFlinger will invalidate the track and the offloaded output
1790 // will be closed causing the effect to be moved to a PCM output.
1791 // 2: A deep buffer output
1792 // 3: the first output in the list
1793
1794 if (outputs.size() == 0) {
1795 return 0;
1796 }
1797
1798 audio_io_handle_t outputOffloaded = 0;
1799 audio_io_handle_t outputDeepBuffer = 0;
1800
1801 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07001802 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001803 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001804 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1805 outputOffloaded = outputs[i];
1806 }
1807 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1808 outputDeepBuffer = outputs[i];
1809 }
1810 }
1811
1812 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1813 outputOffloaded, outputDeepBuffer);
1814 if (outputOffloaded != 0) {
1815 return outputOffloaded;
1816 }
1817 if (outputDeepBuffer != 0) {
1818 return outputDeepBuffer;
1819 }
1820
1821 return outputs[0];
1822}
1823
Eric Laurente0720872014-03-11 09:30:41 -07001824audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001825{
1826 // apply simple rule where global effects are attached to the same output as MUSIC streams
1827
Eric Laurent3b73df72014-03-11 09:06:29 -07001828 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001829 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1830 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1831
1832 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1833 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1834 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1835
1836 return output;
1837}
1838
Eric Laurente0720872014-03-11 09:30:41 -07001839status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001840 audio_io_handle_t io,
1841 uint32_t strategy,
1842 int session,
1843 int id)
1844{
1845 ssize_t index = mOutputs.indexOfKey(io);
1846 if (index < 0) {
1847 index = mInputs.indexOfKey(io);
1848 if (index < 0) {
1849 ALOGW("registerEffect() unknown io %d", io);
1850 return INVALID_OPERATION;
1851 }
1852 }
François Gaffie45ed3b02015-03-19 10:35:14 +01001853 return mEffects.registerEffect(desc, io, strategy, session, id);
Eric Laurente552edb2014-03-10 17:42:56 -07001854}
1855
Eric Laurentc75307b2015-03-17 15:29:32 -07001856bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1857{
1858 return mOutputs.isStreamActive(stream, inPastMs);
1859}
1860
1861bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
1862{
1863 return mOutputs.isStreamActiveRemotely(stream, inPastMs);
1864}
1865
Eric Laurente0720872014-03-11 09:30:41 -07001866bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001867{
1868 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001869 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08001870 if (inputDescriptor->mRefCount == 0) {
1871 continue;
1872 }
1873 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07001874 return true;
1875 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08001876 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
1877 // corresponds to an active capture triggered by a hardware hotword recognition
1878 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
1879 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
1880 // FIXME: we should not assume that the first session is the active one and keep
1881 // activity count per session. Same in startInput().
1882 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
1883 if (index >= 0) {
1884 return true;
1885 }
1886 }
Eric Laurente552edb2014-03-10 17:42:56 -07001887 }
1888 return false;
1889}
1890
Eric Laurent275e8e92014-11-30 15:14:47 -08001891// Register a list of custom mixes with their attributes and format.
1892// When a mix is registered, corresponding input and output profiles are
1893// added to the remote submix hw module. The profile contains only the
1894// parameters (sampling rate, format...) specified by the mix.
1895// The corresponding input remote submix device is also connected.
1896//
1897// When a remote submix device is connected, the address is checked to select the
1898// appropriate profile and the corresponding input or output stream is opened.
1899//
1900// When capture starts, getInputForAttr() will:
1901// - 1 look for a mix matching the address passed in attribtutes tags if any
1902// - 2 if none found, getDeviceForInputSource() will:
1903// - 2.1 look for a mix matching the attributes source
1904// - 2.2 if none found, default to device selection by policy rules
1905// At this time, the corresponding output remote submix device is also connected
1906// and active playback use cases can be transferred to this mix if needed when reconnecting
1907// after AudioTracks are invalidated
1908//
1909// When playback starts, getOutputForAttr() will:
1910// - 1 look for a mix matching the address passed in attribtutes tags if any
1911// - 2 if none found, look for a mix matching the attributes usage
1912// - 3 if none found, default to device and output selection by policy rules.
1913
1914status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
1915{
1916 sp<HwModule> module;
1917 for (size_t i = 0; i < mHwModules.size(); i++) {
1918 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1919 mHwModules[i]->mHandle != 0) {
1920 module = mHwModules[i];
1921 break;
1922 }
1923 }
1924
1925 if (module == 0) {
1926 return INVALID_OPERATION;
1927 }
1928
1929 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
1930
1931 for (size_t i = 0; i < mixes.size(); i++) {
1932 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01001933
1934 if (mPolicyMixes.registerMix(address, mixes[i]) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001935 continue;
1936 }
1937 audio_config_t outputConfig = mixes[i].mFormat;
1938 audio_config_t inputConfig = mixes[i].mFormat;
1939 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
1940 // stereo and let audio flinger do the channel conversion if needed.
1941 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
1942 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
1943 module->addOutputProfile(address, &outputConfig,
1944 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
1945 module->addInputProfile(address, &inputConfig,
1946 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01001947
Eric Laurentc722f302014-12-10 11:21:49 -08001948 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001949 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001950 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001951 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001952 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001953 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001954 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001955 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001956 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001957 }
1958 return NO_ERROR;
1959}
1960
1961status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
1962{
1963 sp<HwModule> module;
1964 for (size_t i = 0; i < mHwModules.size(); i++) {
1965 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
1966 mHwModules[i]->mHandle != 0) {
1967 module = mHwModules[i];
1968 break;
1969 }
1970 }
1971
1972 if (module == 0) {
1973 return INVALID_OPERATION;
1974 }
1975
1976 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
1977
1978 for (size_t i = 0; i < mixes.size(); i++) {
1979 String8 address = mixes[i].mRegistrationId;
François Gaffie036e1e92015-03-19 10:16:24 +01001980
1981 if (mPolicyMixes.unregisterMix(address) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001982 continue;
1983 }
1984
Eric Laurentc722f302014-12-10 11:21:49 -08001985 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
1986 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
1987 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001988 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001989 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001990 address.string(), "remote-submix");
Eric Laurentc722f302014-12-10 11:21:49 -08001991 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001992
1993 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
1994 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
1995 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001996 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08001997 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Paul McLeane743a472015-01-28 11:07:31 -08001998 address.string(), "remote-submix");
Eric Laurent275e8e92014-11-30 15:14:47 -08001999 }
2000 module->removeOutputProfile(address);
2001 module->removeInputProfile(address);
2002 }
2003 return NO_ERROR;
2004}
2005
Eric Laurente552edb2014-03-10 17:42:56 -07002006
Eric Laurente0720872014-03-11 09:30:41 -07002007status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002008{
2009 const size_t SIZE = 256;
2010 char buffer[SIZE];
2011 String8 result;
2012
2013 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2014 result.append(buffer);
2015
Eric Laurent87ffa392015-05-22 10:32:38 -07002016 snprintf(buffer, SIZE, " Primary Output: %d\n",
2017 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -07002018 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002019 snprintf(buffer, SIZE, " Phone state: %d\n", mEngine->getPhoneState());
Eric Laurente552edb2014-03-10 17:42:56 -07002020 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002021 snprintf(buffer, SIZE, " Force use for communications %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002022 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07002023 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002024 snprintf(buffer, SIZE, " Force use for media %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_MEDIA));
Eric Laurente552edb2014-03-10 17:42:56 -07002025 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002026 snprintf(buffer, SIZE, " Force use for record %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD));
Eric Laurente552edb2014-03-10 17:42:56 -07002027 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002028 snprintf(buffer, SIZE, " Force use for dock %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_DOCK));
Eric Laurente552edb2014-03-10 17:42:56 -07002029 result.append(buffer);
François Gaffie2110e042015-03-24 08:41:51 +01002030 snprintf(buffer, SIZE, " Force use for system %d\n", mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM));
Eric Laurente552edb2014-03-10 17:42:56 -07002031 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002032 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
François Gaffie2110e042015-03-24 08:41:51 +01002033 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO));
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002034 result.append(buffer);
Eric Laurent9459fb02015-08-12 18:36:32 -07002035 snprintf(buffer, SIZE, " TTS output %s\n", mTtsOutputAvailable ? "available" : "not available");
2036 result.append(buffer);
2037
François Gaffie2110e042015-03-24 08:41:51 +01002038 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07002039
François Gaffie53615e22015-03-19 09:24:12 +01002040 mAvailableOutputDevices.dump(fd, String8("output"));
2041 mAvailableInputDevices.dump(fd, String8("input"));
2042 mHwModules.dump(fd);
2043 mOutputs.dump(fd);
2044 mInputs.dump(fd);
François Gaffiedfd74092015-03-19 12:10:59 +01002045 mStreams.dump(fd);
François Gaffie45ed3b02015-03-19 10:35:14 +01002046 mEffects.dump(fd);
François Gaffie53615e22015-03-19 09:24:12 +01002047 mAudioPatches.dump(fd);
Eric Laurente552edb2014-03-10 17:42:56 -07002048
2049 return NO_ERROR;
2050}
2051
2052// This function checks for the parameters which can be offloaded.
2053// This can be enhanced depending on the capability of the DSP and policy
2054// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002055bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002056{
2057 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002058 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002059 offloadInfo.sample_rate, offloadInfo.channel_mask,
2060 offloadInfo.format,
2061 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2062 offloadInfo.has_video);
2063
2064 // Check if offload has been disabled
2065 char propValue[PROPERTY_VALUE_MAX];
2066 if (property_get("audio.offload.disable", propValue, "0")) {
2067 if (atoi(propValue) != 0) {
2068 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2069 return false;
2070 }
2071 }
2072
2073 // Check if stream type is music, then only allow offload as of now.
2074 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2075 {
2076 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2077 return false;
2078 }
2079
2080 //TODO: enable audio offloading with video when ready
Andy Hung08945c42015-05-31 21:36:46 -07002081 const bool allowOffloadWithVideo =
2082 property_get_bool("audio.offload.video", false /* default_value */);
2083 if (offloadInfo.has_video && !allowOffloadWithVideo) {
Eric Laurente552edb2014-03-10 17:42:56 -07002084 ALOGV("isOffloadSupported: has_video == true, returning false");
2085 return false;
2086 }
2087
2088 //If duration is less than minimum value defined in property, return false
2089 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2090 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2091 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2092 return false;
2093 }
2094 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2095 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2096 return false;
2097 }
2098
2099 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2100 // creating an offloaded track and tearing it down immediately after start when audioflinger
2101 // detects there is an active non offloadable effect.
2102 // FIXME: We should check the audio session here but we do not have it in this context.
2103 // This may prevent offloading in rare situations where effects are left active by apps
2104 // in the background.
François Gaffie45ed3b02015-03-19 10:35:14 +01002105 if (mEffects.isNonOffloadableEffectEnabled()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002106 return false;
2107 }
2108
2109 // See if there is a profile to support this.
2110 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002111 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002112 offloadInfo.sample_rate,
2113 offloadInfo.format,
2114 offloadInfo.channel_mask,
2115 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002116 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2117 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002118}
2119
Eric Laurent6a94d692014-05-20 11:18:06 -07002120status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2121 audio_port_type_t type,
2122 unsigned int *num_ports,
2123 struct audio_port *ports,
2124 unsigned int *generation)
2125{
2126 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2127 generation == NULL) {
2128 return BAD_VALUE;
2129 }
2130 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2131 if (ports == NULL) {
2132 *num_ports = 0;
2133 }
2134
2135 size_t portsWritten = 0;
2136 size_t portsMax = *num_ports;
2137 *num_ports = 0;
2138 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2139 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2140 for (size_t i = 0;
2141 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2142 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2143 }
2144 *num_ports += mAvailableOutputDevices.size();
2145 }
2146 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2147 for (size_t i = 0;
2148 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2149 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2150 }
2151 *num_ports += mAvailableInputDevices.size();
2152 }
2153 }
2154 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2155 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2156 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2157 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2158 }
2159 *num_ports += mInputs.size();
2160 }
2161 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002162 size_t numOutputs = 0;
2163 for (size_t i = 0; i < mOutputs.size(); i++) {
2164 if (!mOutputs[i]->isDuplicated()) {
2165 numOutputs++;
2166 if (portsWritten < portsMax) {
2167 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2168 }
2169 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002170 }
Eric Laurent84c70242014-06-23 08:46:27 -07002171 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002172 }
2173 }
2174 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002175 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002176 return NO_ERROR;
2177}
2178
2179status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2180{
2181 return NO_ERROR;
2182}
2183
Eric Laurent6a94d692014-05-20 11:18:06 -07002184status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2185 audio_patch_handle_t *handle,
2186 uid_t uid)
2187{
2188 ALOGV("createAudioPatch()");
2189
2190 if (handle == NULL || patch == NULL) {
2191 return BAD_VALUE;
2192 }
2193 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2194
Eric Laurent874c42872014-08-08 15:13:39 -07002195 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2196 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2197 return BAD_VALUE;
2198 }
2199 // only one source per audio patch supported for now
2200 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002201 return INVALID_OPERATION;
2202 }
Eric Laurent874c42872014-08-08 15:13:39 -07002203
2204 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002205 return INVALID_OPERATION;
2206 }
Eric Laurent874c42872014-08-08 15:13:39 -07002207 for (size_t i = 0; i < patch->num_sinks; i++) {
2208 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2209 return INVALID_OPERATION;
2210 }
2211 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002212
2213 sp<AudioPatch> patchDesc;
2214 ssize_t index = mAudioPatches.indexOfKey(*handle);
2215
Eric Laurent6a94d692014-05-20 11:18:06 -07002216 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2217 patch->sources[0].role,
2218 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002219#if LOG_NDEBUG == 0
2220 for (size_t i = 0; i < patch->num_sinks; i++) {
2221 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2222 patch->sinks[i].role,
2223 patch->sinks[i].type);
2224 }
2225#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002226
2227 if (index >= 0) {
2228 patchDesc = mAudioPatches.valueAt(index);
2229 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2230 mUidCached, patchDesc->mUid, uid);
2231 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2232 return INVALID_OPERATION;
2233 }
2234 } else {
2235 *handle = 0;
2236 }
2237
2238 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002240 if (outputDesc == NULL) {
2241 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2242 return BAD_VALUE;
2243 }
Eric Laurent84c70242014-06-23 08:46:27 -07002244 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2245 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002246 if (patchDesc != 0) {
2247 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2248 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2249 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2250 return BAD_VALUE;
2251 }
2252 }
Eric Laurent874c42872014-08-08 15:13:39 -07002253 DeviceVector devices;
2254 for (size_t i = 0; i < patch->num_sinks; i++) {
2255 // Only support mix to devices connection
2256 // TODO add support for mix to mix connection
2257 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2258 ALOGV("createAudioPatch() source mix but sink is not a device");
2259 return INVALID_OPERATION;
2260 }
2261 sp<DeviceDescriptor> devDesc =
2262 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2263 if (devDesc == 0) {
2264 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2265 return BAD_VALUE;
2266 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002267
François Gaffie53615e22015-03-19 09:24:12 +01002268 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002269 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002270 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01002271 NULL, // updatedSamplingRate
2272 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002273 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01002274 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002275 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01002276 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Andy Hungf129b032015-04-07 13:45:50 -07002277 ALOGV("createAudioPatch() profile not supported for device %08x",
2278 devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07002279 return INVALID_OPERATION;
2280 }
2281 devices.add(devDesc);
2282 }
2283 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002284 return INVALID_OPERATION;
2285 }
Eric Laurent874c42872014-08-08 15:13:39 -07002286
Eric Laurent6a94d692014-05-20 11:18:06 -07002287 // TODO: reconfigure output format and channels here
2288 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002289 devices.types(), outputDesc->mIoHandle);
Eric Laurentc75307b2015-03-17 15:29:32 -07002290 setOutputDevice(outputDesc, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002291 index = mAudioPatches.indexOfKey(*handle);
2292 if (index >= 0) {
2293 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2294 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2295 }
2296 patchDesc = mAudioPatches.valueAt(index);
2297 patchDesc->mUid = uid;
2298 ALOGV("createAudioPatch() success");
2299 } else {
2300 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2301 return INVALID_OPERATION;
2302 }
2303 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2304 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2305 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002306 // only one sink supported when connecting an input device to a mix
2307 if (patch->num_sinks > 1) {
2308 return INVALID_OPERATION;
2309 }
François Gaffie53615e22015-03-19 09:24:12 +01002310 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002311 if (inputDesc == NULL) {
2312 return BAD_VALUE;
2313 }
2314 if (patchDesc != 0) {
2315 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2316 return BAD_VALUE;
2317 }
2318 }
2319 sp<DeviceDescriptor> devDesc =
2320 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2321 if (devDesc == 0) {
2322 return BAD_VALUE;
2323 }
2324
François Gaffie53615e22015-03-19 09:24:12 +01002325 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->type(),
Eric Laurent275e8e92014-11-30 15:14:47 -08002326 devDesc->mAddress,
2327 patch->sinks[0].sample_rate,
2328 NULL, /*updatedSampleRate*/
2329 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07002330 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002331 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07002332 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08002333 // FIXME for the parameter type,
2334 // and the NONE
2335 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002336 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002337 return INVALID_OPERATION;
2338 }
2339 // TODO: reconfigure output format and channels here
2340 ALOGV("createAudioPatch() setting device %08x on output %d",
François Gaffie53615e22015-03-19 09:24:12 +01002341 devDesc->type(), inputDesc->mIoHandle);
2342 setInputDevice(inputDesc->mIoHandle, devDesc->type(), true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002343 index = mAudioPatches.indexOfKey(*handle);
2344 if (index >= 0) {
2345 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2346 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2347 }
2348 patchDesc = mAudioPatches.valueAt(index);
2349 patchDesc->mUid = uid;
2350 ALOGV("createAudioPatch() success");
2351 } else {
2352 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2353 return INVALID_OPERATION;
2354 }
2355 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2356 // device to device connection
2357 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002358 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002359 return BAD_VALUE;
2360 }
2361 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002362 sp<DeviceDescriptor> srcDeviceDesc =
2363 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002364 if (srcDeviceDesc == 0) {
2365 return BAD_VALUE;
2366 }
Eric Laurent874c42872014-08-08 15:13:39 -07002367
Eric Laurent6a94d692014-05-20 11:18:06 -07002368 //update source and sink with our own data as the data passed in the patch may
2369 // be incomplete.
2370 struct audio_patch newPatch = *patch;
2371 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002372
Eric Laurent874c42872014-08-08 15:13:39 -07002373 for (size_t i = 0; i < patch->num_sinks; i++) {
2374 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2375 ALOGV("createAudioPatch() source device but one sink is not a device");
2376 return INVALID_OPERATION;
2377 }
2378
2379 sp<DeviceDescriptor> sinkDeviceDesc =
2380 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2381 if (sinkDeviceDesc == 0) {
2382 return BAD_VALUE;
2383 }
2384 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2385
Eric Laurent3bcf8592015-04-03 12:13:24 -07002386 // create a software bridge in PatchPanel if:
2387 // - source and sink devices are on differnt HW modules OR
2388 // - audio HAL version is < 3.0
2389 if ((srcDeviceDesc->getModuleHandle() != sinkDeviceDesc->getModuleHandle()) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002390 (srcDeviceDesc->mModule->getHalVersion() < AUDIO_DEVICE_API_VERSION_3_0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07002391 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07002392 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002393 return INVALID_OPERATION;
2394 }
Eric Laurent874c42872014-08-08 15:13:39 -07002395 SortedVector<audio_io_handle_t> outputs =
François Gaffie53615e22015-03-19 09:24:12 +01002396 getOutputsForDevice(sinkDeviceDesc->type(), mOutputs);
Eric Laurent874c42872014-08-08 15:13:39 -07002397 // if the sink device is reachable via an opened output stream, request to go via
2398 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002399 audio_io_handle_t output = selectOutput(outputs,
2400 AUDIO_OUTPUT_FLAG_NONE,
2401 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002402 if (output != AUDIO_IO_HANDLE_NONE) {
2403 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2404 if (outputDesc->isDuplicated()) {
2405 return INVALID_OPERATION;
2406 }
2407 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
Eric Laurent3bcf8592015-04-03 12:13:24 -07002408 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
Eric Laurent874c42872014-08-08 15:13:39 -07002409 newPatch.num_sources = 2;
2410 }
Eric Laurent83b88082014-06-20 18:31:16 -07002411 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002412 }
2413 // TODO: check from routing capabilities in config file and other conflicting patches
2414
2415 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2416 if (index >= 0) {
2417 afPatchHandle = patchDesc->mAfPatchHandle;
2418 }
2419
2420 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2421 &afPatchHandle,
2422 0);
2423 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2424 status, afPatchHandle);
2425 if (status == NO_ERROR) {
2426 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01002427 patchDesc = new AudioPatch(&newPatch, uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002428 addAudioPatch(patchDesc->mHandle, patchDesc);
2429 } else {
2430 patchDesc->mPatch = newPatch;
2431 }
2432 patchDesc->mAfPatchHandle = afPatchHandle;
2433 *handle = patchDesc->mHandle;
2434 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002435 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002436 } else {
2437 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2438 status);
2439 return INVALID_OPERATION;
2440 }
2441 } else {
2442 return BAD_VALUE;
2443 }
2444 } else {
2445 return BAD_VALUE;
2446 }
2447 return NO_ERROR;
2448}
2449
2450status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2451 uid_t uid)
2452{
2453 ALOGV("releaseAudioPatch() patch %d", handle);
2454
2455 ssize_t index = mAudioPatches.indexOfKey(handle);
2456
2457 if (index < 0) {
2458 return BAD_VALUE;
2459 }
2460 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2461 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2462 mUidCached, patchDesc->mUid, uid);
2463 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2464 return INVALID_OPERATION;
2465 }
2466
2467 struct audio_patch *patch = &patchDesc->mPatch;
2468 patchDesc->mUid = mUidCached;
2469 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002470 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002471 if (outputDesc == NULL) {
2472 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2473 return BAD_VALUE;
2474 }
2475
Eric Laurentc75307b2015-03-17 15:29:32 -07002476 setOutputDevice(outputDesc,
2477 getNewOutputDevice(outputDesc, true /*fromCache*/),
Eric Laurent6a94d692014-05-20 11:18:06 -07002478 true,
2479 0,
2480 NULL);
2481 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2482 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01002483 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002484 if (inputDesc == NULL) {
2485 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2486 return BAD_VALUE;
2487 }
2488 setInputDevice(inputDesc->mIoHandle,
2489 getNewInputDevice(inputDesc->mIoHandle),
2490 true,
2491 NULL);
2492 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2493 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2494 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2495 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2496 status, patchDesc->mAfPatchHandle);
2497 removeAudioPatch(patchDesc->mHandle);
2498 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002499 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002500 } else {
2501 return BAD_VALUE;
2502 }
2503 } else {
2504 return BAD_VALUE;
2505 }
2506 return NO_ERROR;
2507}
2508
2509status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2510 struct audio_patch *patches,
2511 unsigned int *generation)
2512{
François Gaffie53615e22015-03-19 09:24:12 +01002513 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002514 return BAD_VALUE;
2515 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002516 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01002517 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002518}
2519
Eric Laurente1715a42014-05-20 11:30:42 -07002520status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002521{
Eric Laurente1715a42014-05-20 11:30:42 -07002522 ALOGV("setAudioPortConfig()");
2523
2524 if (config == NULL) {
2525 return BAD_VALUE;
2526 }
2527 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2528 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002529 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2530 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002531 }
2532
Eric Laurenta121f902014-06-03 13:32:54 -07002533 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002534 if (config->type == AUDIO_PORT_TYPE_MIX) {
2535 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07002536 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002537 if (outputDesc == NULL) {
2538 return BAD_VALUE;
2539 }
Eric Laurent84c70242014-06-23 08:46:27 -07002540 ALOG_ASSERT(!outputDesc->isDuplicated(),
2541 "setAudioPortConfig() called on duplicated output %d",
2542 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002543 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002544 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01002545 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002546 if (inputDesc == NULL) {
2547 return BAD_VALUE;
2548 }
Eric Laurenta121f902014-06-03 13:32:54 -07002549 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002550 } else {
2551 return BAD_VALUE;
2552 }
2553 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2554 sp<DeviceDescriptor> deviceDesc;
2555 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2556 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2557 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2558 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2559 } else {
2560 return BAD_VALUE;
2561 }
2562 if (deviceDesc == NULL) {
2563 return BAD_VALUE;
2564 }
Eric Laurenta121f902014-06-03 13:32:54 -07002565 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002566 } else {
2567 return BAD_VALUE;
2568 }
2569
Eric Laurenta121f902014-06-03 13:32:54 -07002570 struct audio_port_config backupConfig;
2571 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2572 if (status == NO_ERROR) {
2573 struct audio_port_config newConfig;
2574 audioPortConfig->toAudioPortConfig(&newConfig, config);
2575 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002576 }
Eric Laurenta121f902014-06-03 13:32:54 -07002577 if (status != NO_ERROR) {
2578 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002579 }
Eric Laurente1715a42014-05-20 11:30:42 -07002580
2581 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002582}
2583
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002584void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
2585{
Eric Laurentd60560a2015-04-10 11:31:20 -07002586 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002587 clearAudioPatches(uid);
2588 clearSessionRoutes(uid);
2589}
2590
Eric Laurent6a94d692014-05-20 11:18:06 -07002591void AudioPolicyManager::clearAudioPatches(uid_t uid)
2592{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002593 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002594 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2595 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002596 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002597 }
2598 }
2599}
2600
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002601void AudioPolicyManager::checkStrategyRoute(routing_strategy strategy,
2602 audio_io_handle_t ouptutToSkip)
2603{
2604 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
2605 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
2606 for (size_t j = 0; j < mOutputs.size(); j++) {
2607 if (mOutputs.keyAt(j) == ouptutToSkip) {
2608 continue;
2609 }
2610 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
2611 if (!isStrategyActive(outputDesc, (routing_strategy)strategy)) {
2612 continue;
2613 }
2614 // If the default device for this strategy is on another output mix,
2615 // invalidate all tracks in this strategy to force re connection.
2616 // Otherwise select new device on the output mix.
2617 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
2618 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
2619 if (stream == AUDIO_STREAM_PATCH) {
2620 continue;
2621 }
2622 if (getStrategy((audio_stream_type_t)stream) == strategy) {
2623 mpClientInterface->invalidateStream((audio_stream_type_t)stream);
2624 }
2625 }
2626 } else {
2627 audio_devices_t newDevice = getNewOutputDevice(outputDesc, false /*fromCache*/);
2628 setOutputDevice(outputDesc, newDevice, false);
2629 }
2630 }
2631}
2632
2633void AudioPolicyManager::clearSessionRoutes(uid_t uid)
2634{
2635 // remove output routes associated with this uid
2636 SortedVector<routing_strategy> affectedStrategies;
2637 for (ssize_t i = (ssize_t)mOutputRoutes.size() - 1; i >= 0; i--) {
2638 sp<SessionRoute> route = mOutputRoutes.valueAt(i);
2639 if (route->mUid == uid) {
2640 mOutputRoutes.removeItemsAt(i);
2641 if (route->mDeviceDescriptor != 0) {
2642 affectedStrategies.add(getStrategy(route->mStreamType));
2643 }
2644 }
2645 }
2646 // reroute outputs if necessary
2647 for (size_t i = 0; i < affectedStrategies.size(); i++) {
2648 checkStrategyRoute(affectedStrategies[i], AUDIO_IO_HANDLE_NONE);
2649 }
2650
2651 // remove input routes associated with this uid
2652 SortedVector<audio_source_t> affectedSources;
2653 for (ssize_t i = (ssize_t)mInputRoutes.size() - 1; i >= 0; i--) {
2654 sp<SessionRoute> route = mInputRoutes.valueAt(i);
2655 if (route->mUid == uid) {
2656 mInputRoutes.removeItemsAt(i);
2657 if (route->mDeviceDescriptor != 0) {
2658 affectedSources.add(route->mSource);
2659 }
2660 }
2661 }
2662 // reroute inputs if necessary
2663 SortedVector<audio_io_handle_t> inputsToClose;
2664 for (size_t i = 0; i < mInputs.size(); i++) {
2665 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
2666 if (affectedSources.indexOf(inputDesc->mInputSource) >= 0) {
2667 inputsToClose.add(inputDesc->mIoHandle);
2668 }
2669 }
2670 for (size_t i = 0; i < inputsToClose.size(); i++) {
2671 closeInput(inputsToClose[i]);
2672 }
2673}
2674
Eric Laurentd60560a2015-04-10 11:31:20 -07002675void AudioPolicyManager::clearAudioSources(uid_t uid)
2676{
2677 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
2678 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2679 if (sourceDesc->mUid == uid) {
2680 stopAudioSource(mAudioSources.keyAt(i));
2681 }
2682 }
2683}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002684
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002685status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2686 audio_io_handle_t *ioHandle,
2687 audio_devices_t *device)
2688{
2689 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2690 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002691 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002692
François Gaffiedf372692015-03-19 10:43:27 +01002693 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002694}
2695
Eric Laurentd60560a2015-04-10 11:31:20 -07002696status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
2697 const audio_attributes_t *attributes,
2698 audio_io_handle_t *handle,
2699 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07002700{
Eric Laurentd60560a2015-04-10 11:31:20 -07002701 ALOGV("%s source %p attributes %p handle %p", __FUNCTION__, source, attributes, handle);
2702 if (source == NULL || attributes == NULL || handle == NULL) {
2703 return BAD_VALUE;
2704 }
2705
2706 *handle = AUDIO_IO_HANDLE_NONE;
2707
2708 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
2709 source->type != AUDIO_PORT_TYPE_DEVICE) {
2710 ALOGV("%s INVALID_OPERATION source->role %d source->type %d", __FUNCTION__, source->role, source->type);
2711 return INVALID_OPERATION;
2712 }
2713
2714 sp<DeviceDescriptor> srcDeviceDesc =
2715 mAvailableInputDevices.getDevice(source->ext.device.type,
2716 String8(source->ext.device.address));
2717 if (srcDeviceDesc == 0) {
2718 ALOGV("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
2719 return BAD_VALUE;
2720 }
2721 sp<AudioSourceDescriptor> sourceDesc =
2722 new AudioSourceDescriptor(srcDeviceDesc, attributes, uid);
2723
2724 struct audio_patch dummyPatch;
2725 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
2726 sourceDesc->mPatchDesc = patchDesc;
2727
2728 status_t status = connectAudioSource(sourceDesc);
2729 if (status == NO_ERROR) {
2730 mAudioSources.add(sourceDesc->getHandle(), sourceDesc);
2731 *handle = sourceDesc->getHandle();
2732 }
2733 return status;
2734}
2735
2736status_t AudioPolicyManager::connectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2737{
2738 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2739
2740 // make sure we only have one patch per source.
2741 disconnectAudioSource(sourceDesc);
2742
2743 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2744 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2745 sp<DeviceDescriptor> srcDeviceDesc = sourceDesc->mDevice;
2746
2747 audio_devices_t sinkDevice = getDeviceForStrategy(strategy, true);
2748 sp<DeviceDescriptor> sinkDeviceDesc =
2749 mAvailableOutputDevices.getDevice(sinkDevice, String8(""));
2750
2751 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2752 struct audio_patch *patch = &sourceDesc->mPatchDesc->mPatch;
2753
2754 if (srcDeviceDesc->getAudioPort()->mModule->getHandle() ==
2755 sinkDeviceDesc->getAudioPort()->mModule->getHandle() &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002756 srcDeviceDesc->getAudioPort()->mModule->getHalVersion() >= AUDIO_DEVICE_API_VERSION_3_0 &&
Eric Laurentd60560a2015-04-10 11:31:20 -07002757 srcDeviceDesc->getAudioPort()->mGains.size() > 0) {
2758 ALOGV("%s AUDIO_DEVICE_API_VERSION_3_0", __FUNCTION__);
2759 // create patch between src device and output device
2760 // create Hwoutput and add to mHwOutputs
2761 } else {
2762 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(sinkDevice, mOutputs);
2763 audio_io_handle_t output =
2764 selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE, AUDIO_FORMAT_INVALID);
2765 if (output == AUDIO_IO_HANDLE_NONE) {
2766 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevice);
2767 return INVALID_OPERATION;
2768 }
2769 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2770 if (outputDesc->isDuplicated()) {
2771 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevice);
2772 return INVALID_OPERATION;
2773 }
2774 // create a special patch with no sink and two sources:
2775 // - the second source indicates to PatchPanel through which output mix this patch should
2776 // be connected as well as the stream type for volume control
2777 // - the sink is defined by whatever output device is currently selected for the output
2778 // though which this patch is routed.
2779 patch->num_sinks = 0;
2780 patch->num_sources = 2;
2781 srcDeviceDesc->toAudioPortConfig(&patch->sources[0], NULL);
2782 outputDesc->toAudioPortConfig(&patch->sources[1], NULL);
2783 patch->sources[1].ext.mix.usecase.stream = stream;
2784 status_t status = mpClientInterface->createAudioPatch(patch,
2785 &afPatchHandle,
2786 0);
2787 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
2788 status, afPatchHandle);
2789 if (status != NO_ERROR) {
2790 ALOGW("%s patch panel could not connect device patch, error %d",
2791 __FUNCTION__, status);
2792 return INVALID_OPERATION;
2793 }
2794 uint32_t delayMs = 0;
2795 status = startSource(outputDesc, stream, sinkDevice, &delayMs);
2796
2797 if (status != NO_ERROR) {
2798 mpClientInterface->releaseAudioPatch(sourceDesc->mPatchDesc->mAfPatchHandle, 0);
2799 return status;
2800 }
2801 sourceDesc->mSwOutput = outputDesc;
2802 if (delayMs != 0) {
2803 usleep(delayMs * 1000);
2804 }
2805 }
2806
2807 sourceDesc->mPatchDesc->mAfPatchHandle = afPatchHandle;
2808 addAudioPatch(sourceDesc->mPatchDesc->mHandle, sourceDesc->mPatchDesc);
2809
2810 return NO_ERROR;
Eric Laurent554a2772015-04-10 11:29:24 -07002811}
2812
Eric Laurent493404d2015-04-21 15:07:36 -07002813status_t AudioPolicyManager::stopAudioSource(audio_io_handle_t handle __unused)
Eric Laurent554a2772015-04-10 11:29:24 -07002814{
Eric Laurentd60560a2015-04-10 11:31:20 -07002815 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueFor(handle);
2816 ALOGV("%s handle %d", __FUNCTION__, handle);
2817 if (sourceDesc == 0) {
2818 ALOGW("%s unknown source for handle %d", __FUNCTION__, handle);
2819 return BAD_VALUE;
2820 }
2821 status_t status = disconnectAudioSource(sourceDesc);
2822
2823 mAudioSources.removeItem(handle);
2824 return status;
2825}
2826
2827status_t AudioPolicyManager::disconnectAudioSource(const sp<AudioSourceDescriptor>& sourceDesc)
2828{
2829 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->getHandle());
2830
2831 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->mPatchDesc->mHandle);
2832 if (patchDesc == 0) {
2833 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
2834 sourceDesc->mPatchDesc->mHandle);
2835 return BAD_VALUE;
2836 }
2837 removeAudioPatch(sourceDesc->mPatchDesc->mHandle);
2838
2839 audio_stream_type_t stream = audio_attributes_to_stream_type(&sourceDesc->mAttributes);
2840 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->mSwOutput.promote();
2841 if (swOutputDesc != 0) {
2842 stopSource(swOutputDesc, stream, false);
2843 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2844 } else {
2845 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->mHwOutput.promote();
2846 if (hwOutputDesc != 0) {
2847 // release patch between src device and output device
2848 // close Hwoutput and remove from mHwOutputs
2849 } else {
2850 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
2851 }
2852 }
2853 return NO_ERROR;
2854}
2855
2856sp<AudioSourceDescriptor> AudioPolicyManager::getSourceForStrategyOnOutput(
2857 audio_io_handle_t output, routing_strategy strategy)
2858{
2859 sp<AudioSourceDescriptor> source;
2860 for (size_t i = 0; i < mAudioSources.size(); i++) {
2861 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
2862 routing_strategy sourceStrategy =
2863 (routing_strategy) getStrategyForAttr(&sourceDesc->mAttributes);
2864 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->mSwOutput.promote();
2865 if (sourceStrategy == strategy && outputDesc != 0 && outputDesc->mIoHandle == output) {
2866 source = sourceDesc;
2867 break;
2868 }
2869 }
2870 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07002871}
2872
Eric Laurente552edb2014-03-10 17:42:56 -07002873// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002874// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002875// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07002876uint32_t AudioPolicyManager::nextAudioPortGeneration()
2877{
2878 return android_atomic_inc(&mAudioPortGeneration);
2879}
2880
Eric Laurente0720872014-03-11 09:30:41 -07002881AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002882 :
2883#ifdef AUDIO_POLICY_TEST
2884 Thread(false),
2885#endif //AUDIO_POLICY_TEST
Eric Laurente552edb2014-03-10 17:42:56 -07002886 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002887 mA2dpSuspended(false),
Paul McLeane743a472015-01-28 11:07:31 -08002888 mSpeakerDrcEnabled(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002889 mAudioPortGeneration(1),
2890 mBeaconMuteRefCount(0),
2891 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07002892 mBeaconMuted(false),
2893 mTtsOutputAvailable(false)
Eric Laurente552edb2014-03-10 17:42:56 -07002894{
François Gaffie2110e042015-03-24 08:41:51 +01002895 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
2896 if (!engineInstance) {
2897 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
2898 return;
2899 }
2900 // Retrieve the Policy Manager Interface
2901 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
2902 if (mEngine == NULL) {
2903 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
2904 return;
2905 }
2906 mEngine->setObserver(this);
2907 status_t status = mEngine->initCheck();
2908 ALOG_ASSERT(status == NO_ERROR, "Policy engine not initialized(err=%d)", status);
2909
Eric Laurent6a94d692014-05-20 11:18:06 -07002910 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002911 mpClientInterface = clientInterface;
2912
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002913 AudioPolicyConfig config(mHwModules, mAvailableOutputDevices, mAvailableInputDevices,
2914 mDefaultOutputDevice, mSpeakerDrcEnabled);
2915
2916 if ((ConfigParsingUtils::loadConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE, config) != NO_ERROR) &&
2917 (ConfigParsingUtils::loadConfig(AUDIO_POLICY_CONFIG_FILE, config) != NO_ERROR)) {
2918
2919 ALOGE("could not load audio policy configuration file, setting defaults");
2920 config.setDefault();
Eric Laurente552edb2014-03-10 17:42:56 -07002921 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002922 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002923
François Gaffie2110e042015-03-24 08:41:51 +01002924 // must be done after reading the policy (since conditionned by Speaker Drc Enabling)
2925 mEngine->initializeVolumeCurves(mSpeakerDrcEnabled);
Eric Laurente552edb2014-03-10 17:42:56 -07002926
2927 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002928 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2929 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002930 for (size_t i = 0; i < mHwModules.size(); i++) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002931 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07002932 if (mHwModules[i]->mHandle == 0) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002933 ALOGW("could not open HW module %s", mHwModules[i]->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07002934 continue;
2935 }
2936 // open all output streams needed to access attached devices
2937 // except for direct output streams that are only opened when they are actually
2938 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002939 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002940 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2941 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002942 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002943
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002944 if (!outProfile->hasSupportedDevices()) {
2945 ALOGW("Output profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002946 continue;
2947 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002948 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
Eric Laurent9459fb02015-08-12 18:36:32 -07002949 mTtsOutputAvailable = true;
2950 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002951
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002952 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentd78f1532014-09-16 16:38:20 -07002953 continue;
2954 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002955 audio_devices_t profileType = outProfile->getSupportedDevicesType();
François Gaffie53615e22015-03-19 09:24:12 +01002956 if ((profileType & mDefaultOutputDevice->type()) != AUDIO_DEVICE_NONE) {
2957 profileType = mDefaultOutputDevice->type();
Eric Laurent83b88082014-06-20 18:31:16 -07002958 } else {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002959 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07002960 // outputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002961 profileType = outProfile->getSupportedDeviceForType(outputDeviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002962 }
Eric Laurentd78f1532014-09-16 16:38:20 -07002963 if ((profileType & outputDeviceTypes) == 0) {
2964 continue;
2965 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002966 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
2967 mpClientInterface);
Eric Laurentd78f1532014-09-16 16:38:20 -07002968
2969 outputDesc->mDevice = profileType;
2970 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2971 config.sample_rate = outputDesc->mSamplingRate;
2972 config.channel_mask = outputDesc->mChannelMask;
2973 config.format = outputDesc->mFormat;
2974 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07002975 status_t status = mpClientInterface->openOutput(outProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07002976 &output,
2977 &config,
2978 &outputDesc->mDevice,
2979 String8(""),
2980 &outputDesc->mLatency,
2981 outputDesc->mFlags);
2982
2983 if (status != NO_ERROR) {
2984 ALOGW("Cannot open output stream for device %08x on hw module %s",
2985 outputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002986 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07002987 } else {
2988 outputDesc->mSamplingRate = config.sample_rate;
2989 outputDesc->mChannelMask = config.channel_mask;
2990 outputDesc->mFormat = config.format;
2991
François Gaffiea8ecc2c2015-11-09 16:10:40 +01002992 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
2993 for (size_t k = 0; k < supportedDevices.size(); k++) {
2994 ssize_t index = mAvailableOutputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07002995 // give a valid ID to an attached device once confirmed it is reachable
Paul McLeane743a472015-01-28 11:07:31 -08002996 if (index >= 0 && !mAvailableOutputDevices[index]->isAttached()) {
2997 mAvailableOutputDevices[index]->attach(mHwModules[i]);
Eric Laurentd78f1532014-09-16 16:38:20 -07002998 }
2999 }
3000 if (mPrimaryOutput == 0 &&
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003001 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003002 mPrimaryOutput = outputDesc;
Eric Laurentd78f1532014-09-16 16:38:20 -07003003 }
3004 addOutput(output, outputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003005 setOutputDevice(outputDesc,
Eric Laurentd78f1532014-09-16 16:38:20 -07003006 outputDesc->mDevice,
3007 true);
3008 }
Eric Laurente552edb2014-03-10 17:42:56 -07003009 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003010 // open input streams needed to access attached devices to validate
3011 // mAvailableInputDevices list
3012 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3013 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003014 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003015
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003016 if (!inProfile->hasSupportedDevices()) {
3017 ALOGW("Input profile contains no device on module %s", mHwModules[i]->getName());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003018 continue;
3019 }
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003020 // chose first device present in profile's SupportedDevices also part of
Eric Laurentd78f1532014-09-16 16:38:20 -07003021 // inputDeviceTypes
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003022 audio_devices_t profileType = inProfile->getSupportedDeviceForType(inputDeviceTypes);
3023
Eric Laurentd78f1532014-09-16 16:38:20 -07003024 if ((profileType & inputDeviceTypes) == 0) {
3025 continue;
3026 }
3027 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3028
3029 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3030 inputDesc->mDevice = profileType;
3031
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003032 // find the address
3033 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3034 // the inputs vector must be of size 1, but we don't want to crash here
3035 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3036 : String8("");
3037 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3038 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3039
Eric Laurentd78f1532014-09-16 16:38:20 -07003040 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3041 config.sample_rate = inputDesc->mSamplingRate;
3042 config.channel_mask = inputDesc->mChannelMask;
3043 config.format = inputDesc->mFormat;
3044 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003045 status_t status = mpClientInterface->openInput(inProfile->getModuleHandle(),
Eric Laurentd78f1532014-09-16 16:38:20 -07003046 &input,
3047 &config,
3048 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003049 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003050 AUDIO_SOURCE_MIC,
3051 AUDIO_INPUT_FLAG_NONE);
3052
3053 if (status == NO_ERROR) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003054 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
3055 for (size_t k = 0; k < supportedDevices.size(); k++) {
3056 ssize_t index = mAvailableInputDevices.indexOf(supportedDevices[k]);
Eric Laurentd78f1532014-09-16 16:38:20 -07003057 // give a valid ID to an attached device once confirmed it is reachable
Eric Laurent45aabc32015-08-06 09:11:13 -07003058 if (index >= 0) {
3059 sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
3060 if (!devDesc->isAttached()) {
3061 devDesc->attach(mHwModules[i]);
3062 devDesc->importAudioPort(inProfile);
3063 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003064 }
3065 }
3066 mpClientInterface->closeInput(input);
3067 } else {
3068 ALOGW("Cannot open input stream for device %08x on hw module %s",
3069 inputDesc->mDevice,
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003070 mHwModules[i]->getName());
Eric Laurentd78f1532014-09-16 16:38:20 -07003071 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003072 }
3073 }
3074 // make sure all attached devices have been allocated a unique ID
3075 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003076 if (!mAvailableOutputDevices[i]->isAttached()) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003077 ALOGW("Output device %08x unreachable", mAvailableOutputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003078 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3079 continue;
3080 }
François Gaffie2110e042015-03-24 08:41:51 +01003081 // The device is now validated and can be appended to the available devices of the engine
3082 mEngine->setDeviceConnectionState(mAvailableOutputDevices[i],
3083 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003084 i++;
3085 }
3086 for (size_t i = 0; i < mAvailableInputDevices.size();) {
Paul McLeane743a472015-01-28 11:07:31 -08003087 if (!mAvailableInputDevices[i]->isAttached()) {
François Gaffie53615e22015-03-19 09:24:12 +01003088 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003089 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3090 continue;
3091 }
François Gaffie2110e042015-03-24 08:41:51 +01003092 // The device is now validated and can be appended to the available devices of the engine
3093 mEngine->setDeviceConnectionState(mAvailableInputDevices[i],
3094 AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003095 i++;
3096 }
3097 // make sure default device is reachable
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003098 if (mDefaultOutputDevice == 0 || mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
François Gaffie53615e22015-03-19 09:24:12 +01003099 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->type());
Eric Laurent3a4311c2014-03-17 12:00:47 -07003100 }
Eric Laurente552edb2014-03-10 17:42:56 -07003101
3102 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3103
3104 updateDevicesAndOutputs();
3105
3106#ifdef AUDIO_POLICY_TEST
3107 if (mPrimaryOutput != 0) {
3108 AudioParameter outputCmd = AudioParameter();
3109 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003110 mpClientInterface->setParameters(mPrimaryOutput->mIoHandle, outputCmd.toString());
Eric Laurente552edb2014-03-10 17:42:56 -07003111
3112 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3113 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003114 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3115 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003116 mTestLatencyMs = 0;
3117 mCurOutput = 0;
3118 mDirectOutput = false;
3119 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3120 mTestOutputs[i] = 0;
3121 }
3122
3123 const size_t SIZE = 256;
3124 char buffer[SIZE];
3125 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3126 run(buffer, ANDROID_PRIORITY_AUDIO);
3127 }
3128#endif //AUDIO_POLICY_TEST
3129}
3130
Eric Laurente0720872014-03-11 09:30:41 -07003131AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003132{
3133#ifdef AUDIO_POLICY_TEST
3134 exit();
3135#endif //AUDIO_POLICY_TEST
3136 for (size_t i = 0; i < mOutputs.size(); i++) {
3137 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003138 }
3139 for (size_t i = 0; i < mInputs.size(); i++) {
3140 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003141 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003142 mAvailableOutputDevices.clear();
3143 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003144 mOutputs.clear();
3145 mInputs.clear();
3146 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003147}
3148
Eric Laurente0720872014-03-11 09:30:41 -07003149status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003150{
Eric Laurent87ffa392015-05-22 10:32:38 -07003151 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003152}
3153
3154#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003155bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003156{
3157 ALOGV("entering threadLoop()");
3158 while (!exitPending())
3159 {
3160 String8 command;
3161 int valueInt;
3162 String8 value;
3163
3164 Mutex::Autolock _l(mLock);
3165 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3166
3167 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3168 AudioParameter param = AudioParameter(command);
3169
3170 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3171 valueInt != 0) {
3172 ALOGV("Test command %s received", command.string());
3173 String8 target;
3174 if (param.get(String8("target"), target) != NO_ERROR) {
3175 target = "Manager";
3176 }
3177 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3178 param.remove(String8("test_cmd_policy_output"));
3179 mCurOutput = valueInt;
3180 }
3181 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3182 param.remove(String8("test_cmd_policy_direct"));
3183 if (value == "false") {
3184 mDirectOutput = false;
3185 } else if (value == "true") {
3186 mDirectOutput = true;
3187 }
3188 }
3189 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3190 param.remove(String8("test_cmd_policy_input"));
3191 mTestInput = valueInt;
3192 }
3193
3194 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3195 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003196 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003197 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003198 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003199 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003200 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003201 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003202 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003203 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003204 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003205 if (target == "Manager") {
3206 mTestFormat = format;
3207 } else if (mTestOutputs[mCurOutput] != 0) {
3208 AudioParameter outputParam = AudioParameter();
3209 outputParam.addInt(String8("format"), format);
3210 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3211 }
3212 }
3213 }
3214 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3215 param.remove(String8("test_cmd_policy_channels"));
3216 int channels = 0;
3217
3218 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003219 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003220 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003221 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003222 }
3223 if (channels != 0) {
3224 if (target == "Manager") {
3225 mTestChannels = channels;
3226 } else if (mTestOutputs[mCurOutput] != 0) {
3227 AudioParameter outputParam = AudioParameter();
3228 outputParam.addInt(String8("channels"), channels);
3229 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3230 }
3231 }
3232 }
3233 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3234 param.remove(String8("test_cmd_policy_sampleRate"));
3235 if (valueInt >= 0 && valueInt <= 96000) {
3236 int samplingRate = valueInt;
3237 if (target == "Manager") {
3238 mTestSamplingRate = samplingRate;
3239 } else if (mTestOutputs[mCurOutput] != 0) {
3240 AudioParameter outputParam = AudioParameter();
3241 outputParam.addInt(String8("sampling_rate"), samplingRate);
3242 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3243 }
3244 }
3245 }
3246
3247 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3248 param.remove(String8("test_cmd_policy_reopen"));
3249
Eric Laurentc75307b2015-03-17 15:29:32 -07003250 mpClientInterface->closeOutput(mpClientInterface->closeOutput(mPrimaryOutput););
Eric Laurente552edb2014-03-10 17:42:56 -07003251
Eric Laurentc75307b2015-03-17 15:29:32 -07003252 audio_module_handle_t moduleHandle = mPrimaryOutput->getModuleHandle();
Eric Laurente552edb2014-03-10 17:42:56 -07003253
Eric Laurentc75307b2015-03-17 15:29:32 -07003254 removeOutput(mPrimaryOutput->mIoHandle);
3255 sp<SwAudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL,
3256 mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003257 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003258 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3259 config.sample_rate = outputDesc->mSamplingRate;
3260 config.channel_mask = outputDesc->mChannelMask;
3261 config.format = outputDesc->mFormat;
Eric Laurentc75307b2015-03-17 15:29:32 -07003262 audio_io_handle_t handle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003263 status_t status = mpClientInterface->openOutput(moduleHandle,
Eric Laurentc75307b2015-03-17 15:29:32 -07003264 &handle,
Eric Laurentcf2c0212014-07-25 16:20:43 -07003265 &config,
3266 &outputDesc->mDevice,
3267 String8(""),
3268 &outputDesc->mLatency,
3269 outputDesc->mFlags);
3270 if (status != NO_ERROR) {
3271 ALOGE("Failed to reopen hardware output stream, "
3272 "samplingRate: %d, format %d, channels %d",
3273 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003274 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003275 outputDesc->mSamplingRate = config.sample_rate;
3276 outputDesc->mChannelMask = config.channel_mask;
3277 outputDesc->mFormat = config.format;
Eric Laurentc75307b2015-03-17 15:29:32 -07003278 mPrimaryOutput = outputDesc;
Eric Laurente552edb2014-03-10 17:42:56 -07003279 AudioParameter outputCmd = AudioParameter();
3280 outputCmd.addInt(String8("set_id"), 0);
Eric Laurentc75307b2015-03-17 15:29:32 -07003281 mpClientInterface->setParameters(handle, outputCmd.toString());
3282 addOutput(handle, outputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07003283 }
3284 }
3285
3286
3287 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3288 }
3289 }
3290 return false;
3291}
3292
Eric Laurente0720872014-03-11 09:30:41 -07003293void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003294{
3295 {
3296 AutoMutex _l(mLock);
3297 requestExit();
3298 mWaitWorkCV.signal();
3299 }
3300 requestExitAndWait();
3301}
3302
Eric Laurente0720872014-03-11 09:30:41 -07003303int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003304{
3305 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3306 if (output == mTestOutputs[i]) return i;
3307 }
3308 return 0;
3309}
3310#endif //AUDIO_POLICY_TEST
3311
3312// ---
3313
Eric Laurentc75307b2015-03-17 15:29:32 -07003314void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<SwAudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003315{
François Gaffie98cc1912015-03-18 17:52:40 +01003316 outputDesc->setIoHandle(output);
Eric Laurent1c333e22014-05-20 10:48:17 -07003317 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003318 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003319}
3320
François Gaffie53615e22015-03-19 09:24:12 +01003321void AudioPolicyManager::removeOutput(audio_io_handle_t output)
3322{
3323 mOutputs.removeItem(output);
3324}
3325
Eric Laurent1f2f2232014-06-02 12:01:23 -07003326void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003327{
François Gaffie98cc1912015-03-18 17:52:40 +01003328 inputDesc->setIoHandle(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003329 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003330 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003331}
Eric Laurente552edb2014-03-10 17:42:56 -07003332
Eric Laurentc75307b2015-03-17 15:29:32 -07003333void AudioPolicyManager::findIoHandlesByAddress(sp<SwAudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003334 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003335 const String8 address /*in*/,
3336 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003337 sp<DeviceDescriptor> devDesc =
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003338 desc->mProfile->getSupportedDeviceByAddress(device, address);
keunyoung3190e672014-12-30 13:00:52 -08003339 if (devDesc != 0) {
3340 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3341 desc->mIoHandle, address.string());
3342 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003343 }
3344}
3345
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003346status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003347 audio_policy_dev_state_t state,
3348 SortedVector<audio_io_handle_t>& outputs,
3349 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003350{
François Gaffie53615e22015-03-19 09:24:12 +01003351 audio_devices_t device = devDesc->type();
Eric Laurentc75307b2015-03-17 15:29:32 -07003352 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003353
3354 if (audio_device_is_digital(device)) {
3355 // erase all current sample rates, formats and channel masks
3356 devDesc->clearCapabilities();
3357 }
Eric Laurente552edb2014-03-10 17:42:56 -07003358
Eric Laurent3b73df72014-03-11 09:06:29 -07003359 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003360 // first list already open outputs that can be routed to this device
3361 for (size_t i = 0; i < mOutputs.size(); i++) {
3362 desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07003363 if (!desc->isDuplicated() && (desc->supportedDevices() & device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003364 if (!device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003365 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3366 outputs.add(mOutputs.keyAt(i));
3367 } else {
3368 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003369 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003370 }
Eric Laurente552edb2014-03-10 17:42:56 -07003371 }
3372 }
3373 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003374 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003375 for (size_t i = 0; i < mHwModules.size(); i++)
3376 {
3377 if (mHwModules[i]->mHandle == 0) {
3378 continue;
3379 }
3380 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3381 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003382 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003383 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003384 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003385 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003386 profiles.add(profile);
3387 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3388 }
Eric Laurente552edb2014-03-10 17:42:56 -07003389 }
3390 }
3391 }
3392
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003393 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3394
Eric Laurente552edb2014-03-10 17:42:56 -07003395 if (profiles.isEmpty() && outputs.isEmpty()) {
3396 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3397 return BAD_VALUE;
3398 }
3399
3400 // open outputs for matching profiles if needed. Direct outputs are also opened to
3401 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3402 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003403 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003404
3405 // nothing to do if one output is already opened for this profile
3406 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003407 for (j = 0; j < outputs.size(); j++) {
3408 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003409 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003410 // matching profile: save the sample rates, format and channel masks supported
3411 // by the profile in our device descriptor
Paul McLean9080a4c2015-06-18 08:24:02 -07003412 if (audio_device_is_digital(device)) {
3413 devDesc->importAudioPort(profile);
3414 }
Eric Laurente552edb2014-03-10 17:42:56 -07003415 break;
3416 }
3417 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003418 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003419 continue;
3420 }
3421
Eric Laurent83b88082014-06-20 18:31:16 -07003422 ALOGV("opening output for device %08x with params %s profile %p",
3423 device, address.string(), profile.get());
Eric Laurentc75307b2015-03-17 15:29:32 -07003424 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
Eric Laurente552edb2014-03-10 17:42:56 -07003425 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003426 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3427 config.sample_rate = desc->mSamplingRate;
3428 config.channel_mask = desc->mChannelMask;
3429 config.format = desc->mFormat;
3430 config.offload_info.sample_rate = desc->mSamplingRate;
3431 config.offload_info.channel_mask = desc->mChannelMask;
3432 config.offload_info.format = desc->mFormat;
3433 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003434 status_t status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003435 &output,
3436 &config,
3437 &desc->mDevice,
3438 address,
3439 &desc->mLatency,
3440 desc->mFlags);
3441 if (status == NO_ERROR) {
3442 desc->mSamplingRate = config.sample_rate;
3443 desc->mChannelMask = config.channel_mask;
3444 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003445
Eric Laurentd4692962014-05-05 18:13:44 -07003446 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003447 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003448 char *param = audio_device_address_to_parameter(device, address);
3449 mpClientInterface->setParameters(output, String8(param));
3450 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003451 }
3452
Eric Laurentd4692962014-05-05 18:13:44 -07003453 // Here is where we step through and resolve any "dynamic" fields
3454 String8 reply;
3455 char *value;
3456 if (profile->mSamplingRates[0] == 0) {
3457 reply = mpClientInterface->getParameters(output,
3458 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003459 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003460 reply.string());
3461 value = strpbrk((char *)reply.string(), "=");
3462 if (value != NULL) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003463 profile->setSupportedSamplingRates(samplingRatesFromString(value + 1));
Eric Laurente552edb2014-03-10 17:42:56 -07003464 }
Eric Laurentd4692962014-05-05 18:13:44 -07003465 }
3466 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3467 reply = mpClientInterface->getParameters(output,
3468 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003469 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003470 reply.string());
3471 value = strpbrk((char *)reply.string(), "=");
3472 if (value != NULL) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003473 profile->setSupportedFormats(formatsFromString(value + 1));
Eric Laurente552edb2014-03-10 17:42:56 -07003474 }
Eric Laurentd4692962014-05-05 18:13:44 -07003475 }
3476 if (profile->mChannelMasks[0] == 0) {
3477 reply = mpClientInterface->getParameters(output,
3478 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003479 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003480 reply.string());
3481 value = strpbrk((char *)reply.string(), "=");
3482 if (value != NULL) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003483 profile->setSupportedChannelMasks(outputChannelMasksFromString(value + 1));
Eric Laurente552edb2014-03-10 17:42:56 -07003484 }
Eric Laurentd4692962014-05-05 18:13:44 -07003485 }
3486 if (((profile->mSamplingRates[0] == 0) &&
3487 (profile->mSamplingRates.size() < 2)) ||
3488 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3489 (profile->mFormats.size() < 2)) ||
3490 ((profile->mChannelMasks[0] == 0) &&
3491 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003492 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003493 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003494 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003495 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3496 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003497 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003498 config.sample_rate = profile->pickSamplingRate();
3499 config.channel_mask = profile->pickChannelMask();
3500 config.format = profile->pickFormat();
3501 config.offload_info.sample_rate = config.sample_rate;
3502 config.offload_info.channel_mask = config.channel_mask;
3503 config.offload_info.format = config.format;
Eric Laurent322b4d22015-04-03 15:57:54 -07003504 status = mpClientInterface->openOutput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003505 &output,
3506 &config,
3507 &desc->mDevice,
3508 address,
3509 &desc->mLatency,
3510 desc->mFlags);
3511 if (status == NO_ERROR) {
3512 desc->mSamplingRate = config.sample_rate;
3513 desc->mChannelMask = config.channel_mask;
3514 desc->mFormat = config.format;
3515 } else {
3516 output = AUDIO_IO_HANDLE_NONE;
3517 }
Eric Laurentd4692962014-05-05 18:13:44 -07003518 }
3519
Eric Laurentcf2c0212014-07-25 16:20:43 -07003520 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003521 addOutput(output, desc);
François Gaffie53615e22015-03-19 09:24:12 +01003522 if (device_distinguishes_on_address(device) && address != "0") {
François Gaffie036e1e92015-03-19 10:16:24 +01003523 sp<AudioPolicyMix> policyMix;
3524 if (mPolicyMixes.getAudioPolicyMix(address, policyMix) != NO_ERROR) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003525 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3526 address.string());
3527 }
François Gaffie036e1e92015-03-19 10:16:24 +01003528 policyMix->setOutput(desc);
Jean-Michel Trividacc06f2015-04-08 18:16:39 -07003529 desc->mPolicyMix = policyMix->getMix();
François Gaffie036e1e92015-03-19 10:16:24 +01003530
Eric Laurent87ffa392015-05-22 10:32:38 -07003531 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
3532 hasPrimaryOutput()) {
Eric Laurentc722f302014-12-10 11:21:49 -08003533 // no duplicated output for direct outputs and
3534 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003535 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003536
Eric Laurentd4692962014-05-05 18:13:44 -07003537 // set initial stream volume for device
Eric Laurentc75307b2015-03-17 15:29:32 -07003538 applyStreamVolumes(desc, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003539
Eric Laurentd4692962014-05-05 18:13:44 -07003540 //TODO: configure audio effect output stage here
3541
3542 // open a duplicating output thread for the new output and the primary output
Eric Laurentc75307b2015-03-17 15:29:32 -07003543 duplicatedOutput =
3544 mpClientInterface->openDuplicateOutput(output,
3545 mPrimaryOutput->mIoHandle);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003546 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003547 // add duplicated output descriptor
Eric Laurentc75307b2015-03-17 15:29:32 -07003548 sp<SwAudioOutputDescriptor> dupOutputDesc =
3549 new SwAudioOutputDescriptor(NULL, mpClientInterface);
3550 dupOutputDesc->mOutput1 = mPrimaryOutput;
3551 dupOutputDesc->mOutput2 = desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003552 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3553 dupOutputDesc->mFormat = desc->mFormat;
3554 dupOutputDesc->mChannelMask = desc->mChannelMask;
3555 dupOutputDesc->mLatency = desc->mLatency;
3556 addOutput(duplicatedOutput, dupOutputDesc);
Eric Laurentc75307b2015-03-17 15:29:32 -07003557 applyStreamVolumes(dupOutputDesc, device, 0, true);
Eric Laurentd4692962014-05-05 18:13:44 -07003558 } else {
3559 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07003560 mPrimaryOutput->mIoHandle, output);
Eric Laurentd4692962014-05-05 18:13:44 -07003561 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003562 removeOutput(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003563 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003564 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003565 }
Eric Laurente552edb2014-03-10 17:42:56 -07003566 }
3567 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003568 } else {
3569 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003570 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003571 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003572 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003573 profiles.removeAt(profile_index);
3574 profile_index--;
3575 } else {
3576 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07003577 // Load digital format info only for digital devices
3578 if (audio_device_is_digital(device)) {
3579 devDesc->importAudioPort(profile);
3580 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003581
François Gaffie53615e22015-03-19 09:24:12 +01003582 if (device_distinguishes_on_address(device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003583 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3584 device, address.string());
Eric Laurentc75307b2015-03-17 15:29:32 -07003585 setOutputDevice(desc, device, true/*force*/, 0/*delay*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003586 NULL/*patch handle*/, address.string());
3587 }
Eric Laurente552edb2014-03-10 17:42:56 -07003588 ALOGV("checkOutputsForDevice(): adding output %d", output);
3589 }
3590 }
3591
3592 if (profiles.isEmpty()) {
3593 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3594 return BAD_VALUE;
3595 }
Eric Laurentd4692962014-05-05 18:13:44 -07003596 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003597 // check if one opened output is not needed any more after disconnecting one device
3598 for (size_t i = 0; i < mOutputs.size(); i++) {
3599 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003600 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003601 // exact match on device
François Gaffie53615e22015-03-19 09:24:12 +01003602 if (device_distinguishes_on_address(device) &&
Eric Laurentc75307b2015-03-17 15:29:32 -07003603 (desc->supportedDevices() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003604 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003605 } else if (!(desc->supportedDevices() & mAvailableOutputDevices.types())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003606 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3607 mOutputs.keyAt(i));
3608 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003609 }
Eric Laurente552edb2014-03-10 17:42:56 -07003610 }
3611 }
Eric Laurentd4692962014-05-05 18:13:44 -07003612 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003613 for (size_t i = 0; i < mHwModules.size(); i++)
3614 {
3615 if (mHwModules[i]->mHandle == 0) {
3616 continue;
3617 }
3618 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3619 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003620 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003621 if (profile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003622 ALOGV("checkOutputsForDevice(): "
3623 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003624 if (profile->mSamplingRates[0] == 0) {
3625 profile->mSamplingRates.clear();
3626 profile->mSamplingRates.add(0);
3627 }
3628 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3629 profile->mFormats.clear();
3630 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3631 }
3632 if (profile->mChannelMasks[0] == 0) {
3633 profile->mChannelMasks.clear();
3634 profile->mChannelMasks.add(0);
3635 }
3636 }
3637 }
3638 }
3639 }
3640 return NO_ERROR;
3641}
3642
Paul McLean9080a4c2015-06-18 08:24:02 -07003643status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor> devDesc,
François Gaffie53615e22015-03-19 09:24:12 +01003644 audio_policy_dev_state_t state,
3645 SortedVector<audio_io_handle_t>& inputs,
3646 const String8 address)
Eric Laurentd4692962014-05-05 18:13:44 -07003647{
Paul McLean9080a4c2015-06-18 08:24:02 -07003648 audio_devices_t device = devDesc->type();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003649 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07003650
3651 if (audio_device_is_digital(device)) {
3652 // erase all current sample rates, formats and channel masks
3653 devDesc->clearCapabilities();
3654 }
3655
Eric Laurentd4692962014-05-05 18:13:44 -07003656 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3657 // first list already open inputs that can be routed to this device
3658 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3659 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003660 if (desc->mProfile->supportDevice(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003661 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3662 inputs.add(mInputs.keyAt(input_index));
3663 }
3664 }
3665
3666 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003667 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003668 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3669 {
3670 if (mHwModules[module_idx]->mHandle == 0) {
3671 continue;
3672 }
3673 for (size_t profile_index = 0;
3674 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3675 profile_index++)
3676 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003677 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3678
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003679 if (profile->supportDevice(device)) {
François Gaffie53615e22015-03-19 09:24:12 +01003680 if (!device_distinguishes_on_address(device) ||
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003681 profile->supportDeviceAddress(address)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003682 profiles.add(profile);
3683 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3684 profile_index, module_idx);
3685 }
Eric Laurentd4692962014-05-05 18:13:44 -07003686 }
3687 }
3688 }
3689
3690 if (profiles.isEmpty() && inputs.isEmpty()) {
3691 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3692 return BAD_VALUE;
3693 }
3694
3695 // open inputs for matching profiles if needed. Direct inputs are also opened to
3696 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3697 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3698
Eric Laurent1c333e22014-05-20 10:48:17 -07003699 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003700 // nothing to do if one input is already opened for this profile
3701 size_t input_index;
3702 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3703 desc = mInputs.valueAt(input_index);
3704 if (desc->mProfile == profile) {
Paul McLean9080a4c2015-06-18 08:24:02 -07003705 if (audio_device_is_digital(device)) {
3706 devDesc->importAudioPort(profile);
3707 }
Eric Laurentd4692962014-05-05 18:13:44 -07003708 break;
3709 }
3710 }
3711 if (input_index != mInputs.size()) {
3712 continue;
3713 }
3714
3715 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3716 desc = new AudioInputDescriptor(profile);
3717 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003718 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3719 config.sample_rate = desc->mSamplingRate;
3720 config.channel_mask = desc->mChannelMask;
3721 config.format = desc->mFormat;
3722 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurent322b4d22015-04-03 15:57:54 -07003723 status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
Eric Laurentcf2c0212014-07-25 16:20:43 -07003724 &input,
3725 &config,
3726 &desc->mDevice,
3727 address,
3728 AUDIO_SOURCE_MIC,
3729 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003730
Eric Laurentcf2c0212014-07-25 16:20:43 -07003731 if (status == NO_ERROR) {
3732 desc->mSamplingRate = config.sample_rate;
3733 desc->mChannelMask = config.channel_mask;
3734 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003735
Eric Laurentd4692962014-05-05 18:13:44 -07003736 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003737 char *param = audio_device_address_to_parameter(device, address);
3738 mpClientInterface->setParameters(input, String8(param));
3739 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003740 }
3741
3742 // Here is where we step through and resolve any "dynamic" fields
3743 String8 reply;
3744 char *value;
3745 if (profile->mSamplingRates[0] == 0) {
3746 reply = mpClientInterface->getParameters(input,
3747 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3748 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3749 reply.string());
3750 value = strpbrk((char *)reply.string(), "=");
3751 if (value != NULL) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003752 profile->setSupportedSamplingRates(samplingRatesFromString(value + 1));
Eric Laurentd4692962014-05-05 18:13:44 -07003753 }
3754 }
3755 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3756 reply = mpClientInterface->getParameters(input,
3757 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3758 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3759 value = strpbrk((char *)reply.string(), "=");
3760 if (value != NULL) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003761 profile->setSupportedFormats(formatsFromString(value + 1));
Eric Laurentd4692962014-05-05 18:13:44 -07003762 }
3763 }
3764 if (profile->mChannelMasks[0] == 0) {
3765 reply = mpClientInterface->getParameters(input,
3766 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3767 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3768 reply.string());
3769 value = strpbrk((char *)reply.string(), "=");
3770 if (value != NULL) {
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003771 profile->setSupportedChannelMasks(inputChannelMasksFromString(value + 1));
Eric Laurentd4692962014-05-05 18:13:44 -07003772 }
3773 }
3774 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3775 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3776 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3777 ALOGW("checkInputsForDevice() direct input missing param");
3778 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003779 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003780 }
3781
3782 if (input != 0) {
3783 addInput(input, desc);
3784 }
3785 } // endif input != 0
3786
Eric Laurentcf2c0212014-07-25 16:20:43 -07003787 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003788 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003789 profiles.removeAt(profile_index);
3790 profile_index--;
3791 } else {
3792 inputs.add(input);
Paul McLean9080a4c2015-06-18 08:24:02 -07003793 if (audio_device_is_digital(device)) {
3794 devDesc->importAudioPort(profile);
3795 }
Eric Laurentd4692962014-05-05 18:13:44 -07003796 ALOGV("checkInputsForDevice(): adding input %d", input);
3797 }
3798 } // end scan profiles
3799
3800 if (profiles.isEmpty()) {
3801 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3802 return BAD_VALUE;
3803 }
3804 } else {
3805 // Disconnect
3806 // check if one opened input is not needed any more after disconnecting one device
3807 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3808 desc = mInputs.valueAt(input_index);
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003809 if (!(desc->mProfile->supportDevice(mAvailableInputDevices.types()))) {
Eric Laurentd4692962014-05-05 18:13:44 -07003810 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3811 mInputs.keyAt(input_index));
3812 inputs.add(mInputs.keyAt(input_index));
3813 }
3814 }
3815 // Clear any profiles associated with the disconnected device.
3816 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3817 if (mHwModules[module_index]->mHandle == 0) {
3818 continue;
3819 }
3820 for (size_t profile_index = 0;
3821 profile_index < mHwModules[module_index]->mInputProfiles.size();
3822 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003823 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
François Gaffiea8ecc2c2015-11-09 16:10:40 +01003824 if (profile->supportDevice(device)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003825 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003826 profile_index, module_index);
3827 if (profile->mSamplingRates[0] == 0) {
3828 profile->mSamplingRates.clear();
3829 profile->mSamplingRates.add(0);
3830 }
3831 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3832 profile->mFormats.clear();
3833 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3834 }
3835 if (profile->mChannelMasks[0] == 0) {
3836 profile->mChannelMasks.clear();
3837 profile->mChannelMasks.add(0);
3838 }
3839 }
3840 }
3841 }
3842 } // end disconnect
3843
3844 return NO_ERROR;
3845}
3846
3847
Eric Laurente0720872014-03-11 09:30:41 -07003848void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003849{
3850 ALOGV("closeOutput(%d)", output);
3851
Eric Laurentc75307b2015-03-17 15:29:32 -07003852 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003853 if (outputDesc == NULL) {
3854 ALOGW("closeOutput() unknown output %d", output);
3855 return;
3856 }
François Gaffie036e1e92015-03-19 10:16:24 +01003857 mPolicyMixes.closeOutput(outputDesc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003858
Eric Laurente552edb2014-03-10 17:42:56 -07003859 // look for duplicated outputs connected to the output being removed.
3860 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003861 sp<SwAudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003862 if (dupOutputDesc->isDuplicated() &&
3863 (dupOutputDesc->mOutput1 == outputDesc ||
3864 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003865 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003866 if (dupOutputDesc->mOutput1 == outputDesc) {
3867 outputDesc2 = dupOutputDesc->mOutput2;
3868 } else {
3869 outputDesc2 = dupOutputDesc->mOutput1;
3870 }
3871 // As all active tracks on duplicated output will be deleted,
3872 // and as they were also referenced on the other output, the reference
3873 // count for their stream type must be adjusted accordingly on
3874 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003875 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003876 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003877 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003878 }
3879 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3880 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3881
3882 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01003883 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003884 }
3885 }
3886
Eric Laurent05b90f82014-08-27 15:32:29 -07003887 nextAudioPortGeneration();
3888
3889 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3890 if (index >= 0) {
3891 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3892 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3893 mAudioPatches.removeItemsAt(index);
3894 mpClientInterface->onAudioPatchListUpdate();
3895 }
3896
Eric Laurente552edb2014-03-10 17:42:56 -07003897 AudioParameter param;
3898 param.add(String8("closing"), String8("true"));
3899 mpClientInterface->setParameters(output, param.toString());
3900
3901 mpClientInterface->closeOutput(output);
François Gaffie53615e22015-03-19 09:24:12 +01003902 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003903 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07003904}
3905
3906void AudioPolicyManager::closeInput(audio_io_handle_t input)
3907{
3908 ALOGV("closeInput(%d)", input);
3909
3910 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3911 if (inputDesc == NULL) {
3912 ALOGW("closeInput() unknown input %d", input);
3913 return;
3914 }
3915
Eric Laurent6a94d692014-05-20 11:18:06 -07003916 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07003917
3918 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3919 if (index >= 0) {
3920 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3921 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3922 mAudioPatches.removeItemsAt(index);
3923 mpClientInterface->onAudioPatchListUpdate();
3924 }
3925
3926 mpClientInterface->closeInput(input);
3927 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07003928}
3929
Eric Laurentc75307b2015-03-17 15:29:32 -07003930SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(
3931 audio_devices_t device,
3932 SwAudioOutputCollection openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003933{
3934 SortedVector<audio_io_handle_t> outputs;
3935
3936 ALOGVV("getOutputsForDevice() device %04x", device);
3937 for (size_t i = 0; i < openOutputs.size(); i++) {
3938 ALOGVV("output %d isDuplicated=%d device=%04x",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07003939 i, openOutputs.valueAt(i)->isDuplicated(),
3940 openOutputs.valueAt(i)->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07003941 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3942 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3943 outputs.add(openOutputs.keyAt(i));
3944 }
3945 }
3946 return outputs;
3947}
3948
Eric Laurente0720872014-03-11 09:30:41 -07003949bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
François Gaffie53615e22015-03-19 09:24:12 +01003950 SortedVector<audio_io_handle_t>& outputs2)
Eric Laurente552edb2014-03-10 17:42:56 -07003951{
3952 if (outputs1.size() != outputs2.size()) {
3953 return false;
3954 }
3955 for (size_t i = 0; i < outputs1.size(); i++) {
3956 if (outputs1[i] != outputs2[i]) {
3957 return false;
3958 }
3959 }
3960 return true;
3961}
3962
Eric Laurente0720872014-03-11 09:30:41 -07003963void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003964{
3965 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3966 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3967 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3968 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3969
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003970 // also take into account external policy-related changes: add all outputs which are
3971 // associated with policies in the "before" and "after" output vectors
3972 ALOGVV("checkOutputForStrategy(): policy related outputs");
3973 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003974 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003975 if (desc != 0 && desc->mPolicyMix != NULL) {
3976 srcOutputs.add(desc->mIoHandle);
3977 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
3978 }
3979 }
3980 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003981 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivife472e22014-12-16 14:23:13 -08003982 if (desc != 0 && desc->mPolicyMix != NULL) {
3983 dstOutputs.add(desc->mIoHandle);
3984 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
3985 }
3986 }
3987
Eric Laurente552edb2014-03-10 17:42:56 -07003988 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3989 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3990 strategy, srcOutputs[0], dstOutputs[0]);
3991 // mute strategy while moving tracks from one output to another
3992 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003993 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01003994 if (isStrategyActive(desc, strategy)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07003995 setStrategyMute(strategy, true, desc);
3996 setStrategyMute(strategy, false, desc, MUTE_TIME_MS, newDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07003997 }
Eric Laurentd60560a2015-04-10 11:31:20 -07003998 sp<AudioSourceDescriptor> source =
3999 getSourceForStrategyOnOutput(srcOutputs[i], strategy);
4000 if (source != 0){
4001 connectAudioSource(source);
4002 }
Eric Laurente552edb2014-03-10 17:42:56 -07004003 }
4004
4005 // Move effects associated to this strategy from previous output to new output
4006 if (strategy == STRATEGY_MEDIA) {
4007 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4008 SortedVector<audio_io_handle_t> moved;
4009 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004010 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4011 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4012 effectDesc->mIo != fxOutput) {
4013 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004014 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4015 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004016 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004017 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004018 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004019 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004020 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004021 }
4022 }
4023 }
4024 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004025 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004026 if (i == AUDIO_STREAM_PATCH) {
4027 continue;
4028 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004029 if (getStrategy((audio_stream_type_t)i) == strategy) {
4030 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004031 }
4032 }
4033 }
4034}
4035
Eric Laurente0720872014-03-11 09:30:41 -07004036void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004037{
François Gaffie2110e042015-03-24 08:41:51 +01004038 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004039 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004040 checkOutputForStrategy(STRATEGY_PHONE);
François Gaffie2110e042015-03-24 08:41:51 +01004041 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
Jon Eklund966095e2014-09-09 15:39:49 -05004042 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004043 checkOutputForStrategy(STRATEGY_SONIFICATION);
4044 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004045 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004046 checkOutputForStrategy(STRATEGY_MEDIA);
4047 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004048 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004049}
4050
Eric Laurente0720872014-03-11 09:30:41 -07004051void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004052{
François Gaffie53615e22015-03-19 09:24:12 +01004053 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Eric Laurente552edb2014-03-10 17:42:56 -07004054 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004055 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004056 return;
4057 }
4058
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004060 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4061 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4062 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004063 // suspend A2DP output if:
4064 // (NOT already suspended) &&
4065 // ((SCO device is connected &&
4066 // (forced usage for communication || for record is SCO))) ||
4067 // (phone state is ringing || in call)
4068 //
4069 // restore A2DP output if:
4070 // (Already suspended) &&
4071 // ((SCO device is NOT connected ||
4072 // (forced usage NOT for communication && NOT for record is SCO))) &&
4073 // (phone state is NOT ringing && NOT in call)
4074 //
4075 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004076 if ((!isScoConnected ||
François Gaffie2110e042015-03-24 08:41:51 +01004077 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) != AUDIO_POLICY_FORCE_BT_SCO) &&
4078 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) != AUDIO_POLICY_FORCE_BT_SCO))) &&
4079 ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
4080 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004081
4082 mpClientInterface->restoreOutput(a2dpOutput);
4083 mA2dpSuspended = false;
4084 }
4085 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004086 if ((isScoConnected &&
François Gaffie2110e042015-03-24 08:41:51 +01004087 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) == AUDIO_POLICY_FORCE_BT_SCO) ||
4088 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) == AUDIO_POLICY_FORCE_BT_SCO))) ||
4089 ((mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
4090 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004091
4092 mpClientInterface->suspendOutput(a2dpOutput);
4093 mA2dpSuspended = true;
4094 }
4095 }
4096}
4097
Eric Laurentc75307b2015-03-17 15:29:32 -07004098audio_devices_t AudioPolicyManager::getNewOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
4099 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004100{
4101 audio_devices_t device = AUDIO_DEVICE_NONE;
4102
Eric Laurent6a94d692014-05-20 11:18:06 -07004103 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4104 if (index >= 0) {
4105 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4106 if (patchDesc->mUid != mUidCached) {
4107 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4108 outputDesc->device(), outputDesc->mPatchHandle);
4109 return outputDesc->device();
4110 }
4111 }
4112
Eric Laurente552edb2014-03-10 17:42:56 -07004113 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004114 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004115 // use device for strategy enforced audible
4116 // 2: we are in call or the strategy phone is active on the output:
4117 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004118 // 3: the strategy for enforced audible is active but not enforced on the output:
4119 // use the device for strategy enforced audible
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004120 // 4: the strategy accessibility is active on the output:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004121 // use device for strategy accessibility
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004122 // 5: the strategy sonification is active on the output:
4123 // use device for strategy sonification
4124 // 6: the strategy "respectful" sonification is active on the output:
4125 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004126 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004127 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004128 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004129 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004130 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004131 // use device for strategy t-t-s
François Gaffiead3183e2015-03-18 16:55:35 +01004132 if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004133 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004134 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4135 } else if (isInCall() ||
François Gaffiead3183e2015-03-18 16:55:35 +01004136 isStrategyActive(outputDesc, STRATEGY_PHONE)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004137 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004138 } else if (isStrategyActive(outputDesc, STRATEGY_ENFORCED_AUDIBLE)) {
Jon Eklund966095e2014-09-09 15:39:49 -05004139 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Jean-Michel Trivi5de234b2015-07-21 11:42:02 -07004140 } else if (isStrategyActive(outputDesc, STRATEGY_ACCESSIBILITY)) {
4141 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004142 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004143 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004144 } else if (isStrategyActive(outputDesc, STRATEGY_SONIFICATION_RESPECTFUL)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004145 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004146 } else if (isStrategyActive(outputDesc, STRATEGY_MEDIA)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004147 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004148 } else if (isStrategyActive(outputDesc, STRATEGY_DTMF)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004149 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004150 } else if (isStrategyActive(outputDesc, STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004151 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
François Gaffiead3183e2015-03-18 16:55:35 +01004152 } else if (isStrategyActive(outputDesc, STRATEGY_REROUTING)) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004153 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004154 }
4155
Eric Laurent1c333e22014-05-20 10:48:17 -07004156 ALOGV("getNewOutputDevice() selected device %x", device);
4157 return device;
4158}
4159
4160audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4161{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004162 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004163
4164 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4165 if (index >= 0) {
4166 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4167 if (patchDesc->mUid != mUidCached) {
4168 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4169 inputDesc->mDevice, inputDesc->mPatchHandle);
4170 return inputDesc->mDevice;
4171 }
4172 }
4173
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004174 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004175
Eric Laurente552edb2014-03-10 17:42:56 -07004176 return device;
4177}
4178
Eric Laurente0720872014-03-11 09:30:41 -07004179uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004180 return (uint32_t)getStrategy(stream);
4181}
4182
Eric Laurente0720872014-03-11 09:30:41 -07004183audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004184 // By checking the range of stream before calling getStrategy, we avoid
4185 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4186 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004187 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004188 return AUDIO_DEVICE_NONE;
4189 }
4190 audio_devices_t devices;
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004191 routing_strategy strategy = getStrategy(stream);
Eric Laurent6a94d692014-05-20 11:18:06 -07004192 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4193 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4194 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004195 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
François Gaffiead3183e2015-03-18 16:55:35 +01004196 if (isStrategyActive(outputDesc, strategy)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 devices = outputDesc->device();
4198 break;
4199 }
Eric Laurente552edb2014-03-10 17:42:56 -07004200 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004201
4202 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4203 and doesn't really need to.*/
4204 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4205 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4206 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4207 }
4208
Eric Laurente552edb2014-03-10 17:42:56 -07004209 return devices;
4210}
4211
François Gaffie2110e042015-03-24 08:41:51 +01004212routing_strategy AudioPolicyManager::getStrategy(audio_stream_type_t stream) const
4213{
Eric Laurent223fd5c2014-11-11 13:43:36 -08004214 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
François Gaffie2110e042015-03-24 08:41:51 +01004215 return mEngine->getStrategyForStream(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004216}
4217
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004218uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4219 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004220 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4221 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4222 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004223 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4224 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4225 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004226 // usage to strategy mapping
François Gaffie2110e042015-03-24 08:41:51 +01004227 return static_cast<uint32_t>(mEngine->getStrategyForUsage(attr->usage));
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004228}
4229
Eric Laurente0720872014-03-11 09:30:41 -07004230void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004231 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004232 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004233 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4234 updateDevicesAndOutputs();
4235 break;
4236 default:
4237 break;
4238 }
4239}
4240
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004241uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07004242
4243 // skip beacon mute management if a dedicated TTS output is available
4244 if (mTtsOutputAvailable) {
4245 return 0;
4246 }
4247
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004248 switch(event) {
4249 case STARTING_OUTPUT:
4250 mBeaconMuteRefCount++;
4251 break;
4252 case STOPPING_OUTPUT:
4253 if (mBeaconMuteRefCount > 0) {
4254 mBeaconMuteRefCount--;
4255 }
4256 break;
4257 case STARTING_BEACON:
4258 mBeaconPlayingRefCount++;
4259 break;
4260 case STOPPING_BEACON:
4261 if (mBeaconPlayingRefCount > 0) {
4262 mBeaconPlayingRefCount--;
4263 }
4264 break;
4265 }
4266
4267 if (mBeaconMuteRefCount > 0) {
4268 // any playback causes beacon to be muted
4269 return setBeaconMute(true);
4270 } else {
4271 // no other playback: unmute when beacon starts playing, mute when it stops
4272 return setBeaconMute(mBeaconPlayingRefCount == 0);
4273 }
4274}
4275
4276uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4277 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4278 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4279 // keep track of muted state to avoid repeating mute/unmute operations
4280 if (mBeaconMuted != mute) {
4281 // mute/unmute AUDIO_STREAM_TTS on all outputs
4282 ALOGV("\t muting %d", mute);
4283 uint32_t maxLatency = 0;
4284 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004285 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004286 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
Eric Laurentc75307b2015-03-17 15:29:32 -07004287 desc,
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004288 0 /*delay*/, AUDIO_DEVICE_NONE);
4289 const uint32_t latency = desc->latency() * 2;
4290 if (latency > maxLatency) {
4291 maxLatency = latency;
4292 }
4293 }
4294 mBeaconMuted = mute;
4295 return maxLatency;
4296 }
4297 return 0;
4298}
4299
Eric Laurente0720872014-03-11 09:30:41 -07004300audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
François Gaffie53615e22015-03-19 09:24:12 +01004301 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004302{
Paul McLeanaa981192015-03-21 09:55:15 -07004303 // Routing
4304 // see if we have an explicit route
4305 // scan the whole RouteMap, for each entry, convert the stream type to a strategy
4306 // (getStrategy(stream)).
4307 // if the strategy from the stream type in the RouteMap is the same as the argument above,
4308 // and activity count is non-zero
4309 // the device = the device from the descriptor in the RouteMap, and exit.
4310 for (size_t routeIndex = 0; routeIndex < mOutputRoutes.size(); routeIndex++) {
4311 sp<SessionRoute> route = mOutputRoutes.valueAt(routeIndex);
4312 routing_strategy strat = getStrategy(route->mStreamType);
Eric Laurent093a20c2015-06-11 12:33:29 -07004313 // Special case for accessibility strategy which must follow any strategy it is
4314 // currently remapped to
4315 bool strategyMatch = (strat == strategy) ||
4316 ((strategy == STRATEGY_ACCESSIBILITY) &&
4317 ((mEngine->getStrategyForUsage(
4318 AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY) == strat) ||
4319 (strat == STRATEGY_MEDIA)));
4320 if (strategyMatch && route->isActive()) {
Paul McLeanaa981192015-03-21 09:55:15 -07004321 return route->mDeviceDescriptor->type();
4322 }
4323 }
4324
Eric Laurente552edb2014-03-10 17:42:56 -07004325 if (fromCache) {
4326 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4327 strategy, mDeviceForStrategy[strategy]);
4328 return mDeviceForStrategy[strategy];
4329 }
François Gaffie2110e042015-03-24 08:41:51 +01004330 return mEngine->getDeviceForStrategy(strategy);
Eric Laurente552edb2014-03-10 17:42:56 -07004331}
4332
Eric Laurente0720872014-03-11 09:30:41 -07004333void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004334{
4335 for (int i = 0; i < NUM_STRATEGIES; i++) {
4336 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4337 }
4338 mPreviousOutputs = mOutputs;
4339}
4340
Eric Laurent1f2f2232014-06-02 12:01:23 -07004341uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004342 audio_devices_t prevDevice,
4343 uint32_t delayMs)
4344{
4345 // mute/unmute strategies using an incompatible device combination
4346 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4347 // if unmuting, unmute only after the specified delay
4348 if (outputDesc->isDuplicated()) {
4349 return 0;
4350 }
4351
4352 uint32_t muteWaitMs = 0;
4353 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004354 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004355
4356 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4357 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurentc75307b2015-03-17 15:29:32 -07004358 curDevice = curDevice & outputDesc->supportedDevices();
Eric Laurente552edb2014-03-10 17:42:56 -07004359 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4360 bool doMute = false;
4361
4362 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4363 doMute = true;
4364 outputDesc->mStrategyMutedByDevice[i] = true;
4365 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4366 doMute = true;
4367 outputDesc->mStrategyMutedByDevice[i] = false;
4368 }
Eric Laurent99401132014-05-07 19:48:15 -07004369 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004370 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004371 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004372 // skip output if it does not share any device with current output
4373 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4374 == AUDIO_DEVICE_NONE) {
4375 continue;
4376 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004377 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x)",
4378 mute ? "muting" : "unmuting", i, curDevice);
4379 setStrategyMute((routing_strategy)i, mute, desc, mute ? 0 : delayMs);
François Gaffiead3183e2015-03-18 16:55:35 +01004380 if (isStrategyActive(desc, (routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004381 if (mute) {
4382 // FIXME: should not need to double latency if volume could be applied
4383 // immediately by the audioflinger mixer. We must account for the delay
4384 // between now and the next time the audioflinger thread for this output
4385 // will process a buffer (which corresponds to one buffer size,
4386 // usually 1/2 or 1/4 of the latency).
4387 if (muteWaitMs < desc->latency() * 2) {
4388 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004389 }
4390 }
4391 }
4392 }
4393 }
4394 }
4395
Eric Laurent99401132014-05-07 19:48:15 -07004396 // temporary mute output if device selection changes to avoid volume bursts due to
4397 // different per device volumes
4398 if (outputDesc->isActive() && (device != prevDevice)) {
4399 if (muteWaitMs < outputDesc->latency() * 2) {
4400 muteWaitMs = outputDesc->latency() * 2;
4401 }
4402 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
François Gaffiead3183e2015-03-18 16:55:35 +01004403 if (isStrategyActive(outputDesc, (routing_strategy)i)) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004404 setStrategyMute((routing_strategy)i, true, outputDesc);
Eric Laurent99401132014-05-07 19:48:15 -07004405 // do tempMute unmute after twice the mute wait time
Eric Laurentc75307b2015-03-17 15:29:32 -07004406 setStrategyMute((routing_strategy)i, false, outputDesc,
Eric Laurent99401132014-05-07 19:48:15 -07004407 muteWaitMs *2, device);
4408 }
4409 }
4410 }
4411
Eric Laurente552edb2014-03-10 17:42:56 -07004412 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4413 if (muteWaitMs > delayMs) {
4414 muteWaitMs -= delayMs;
4415 usleep(muteWaitMs * 1000);
4416 return muteWaitMs;
4417 }
4418 return 0;
4419}
4420
Eric Laurentc75307b2015-03-17 15:29:32 -07004421uint32_t AudioPolicyManager::setOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004422 audio_devices_t device,
4423 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004424 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004425 audio_patch_handle_t *patchHandle,
4426 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004427{
Eric Laurentc75307b2015-03-17 15:29:32 -07004428 ALOGV("setOutputDevice() device %04x delayMs %d", device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004429 AudioParameter param;
4430 uint32_t muteWaitMs;
4431
4432 if (outputDesc->isDuplicated()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004433 muteWaitMs = setOutputDevice(outputDesc->subOutput1(), device, force, delayMs);
4434 muteWaitMs += setOutputDevice(outputDesc->subOutput2(), device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004435 return muteWaitMs;
4436 }
4437 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4438 // output profile
Eric Laurentc75307b2015-03-17 15:29:32 -07004439 if ((device != AUDIO_DEVICE_NONE) &&
4440 ((device & outputDesc->supportedDevices()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004441 return 0;
4442 }
4443
4444 // filter devices according to output selected
Eric Laurentc75307b2015-03-17 15:29:32 -07004445 device = (audio_devices_t)(device & outputDesc->supportedDevices());
Eric Laurente552edb2014-03-10 17:42:56 -07004446
4447 audio_devices_t prevDevice = outputDesc->mDevice;
4448
Paul McLeanaa981192015-03-21 09:55:15 -07004449 ALOGV("setOutputDevice() prevDevice 0x%04x", prevDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004450
4451 if (device != AUDIO_DEVICE_NONE) {
4452 outputDesc->mDevice = device;
4453 }
4454 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4455
4456 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004457 // the requested device is AUDIO_DEVICE_NONE
4458 // OR the requested device is the same as current device
4459 // AND force is not specified
4460 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004461 // Doing this check here allows the caller to call setOutputDevice() without conditions
Paul McLeanaa981192015-03-21 09:55:15 -07004462 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) &&
4463 !force &&
4464 outputDesc->mPatchHandle != 0) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004465 ALOGV("setOutputDevice() setting same device 0x%04x or null device", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004466 return muteWaitMs;
4467 }
4468
4469 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004470
Eric Laurente552edb2014-03-10 17:42:56 -07004471 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004472 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004473 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004474 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004475 DeviceVector deviceList = (address == NULL) ?
4476 mAvailableOutputDevices.getDevicesFromType(device)
4477 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004478 if (!deviceList.isEmpty()) {
4479 struct audio_patch patch;
4480 outputDesc->toAudioPortConfig(&patch.sources[0]);
4481 patch.num_sources = 1;
4482 patch.num_sinks = 0;
4483 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4484 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004485 patch.num_sinks++;
4486 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 ssize_t index;
4488 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4489 index = mAudioPatches.indexOfKey(*patchHandle);
4490 } else {
4491 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4492 }
4493 sp< AudioPatch> patchDesc;
4494 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4495 if (index >= 0) {
4496 patchDesc = mAudioPatches.valueAt(index);
4497 afPatchHandle = patchDesc->mAfPatchHandle;
4498 }
4499
Eric Laurent1c333e22014-05-20 10:48:17 -07004500 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 &afPatchHandle,
4502 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004503 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4504 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004506 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004507 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004508 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 addAudioPatch(patchDesc->mHandle, patchDesc);
4510 } else {
4511 patchDesc->mPatch = patch;
4512 }
4513 patchDesc->mAfPatchHandle = afPatchHandle;
4514 patchDesc->mUid = mUidCached;
4515 if (patchHandle) {
4516 *patchHandle = patchDesc->mHandle;
4517 }
4518 outputDesc->mPatchHandle = patchDesc->mHandle;
4519 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004520 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004521 }
4522 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004523
4524 // inform all input as well
4525 for (size_t i = 0; i < mInputs.size(); i++) {
4526 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
François Gaffie53615e22015-03-19 09:24:12 +01004527 if (!is_virtual_input_device(inputDescriptor->mDevice)) {
bryant_liuf5e7e792014-08-19 20:07:05 +08004528 AudioParameter inputCmd = AudioParameter();
4529 ALOGV("%s: inform input %d of device:%d", __func__,
4530 inputDescriptor->mIoHandle, device);
4531 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
4532 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
4533 inputCmd.toString(),
4534 delayMs);
4535 }
4536 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004537 }
Eric Laurente552edb2014-03-10 17:42:56 -07004538
4539 // update stream volumes according to new device
Eric Laurentc75307b2015-03-17 15:29:32 -07004540 applyStreamVolumes(outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004541
4542 return muteWaitMs;
4543}
4544
Eric Laurentc75307b2015-03-17 15:29:32 -07004545status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07004546 int delayMs,
4547 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004548{
Eric Laurent6a94d692014-05-20 11:18:06 -07004549 ssize_t index;
4550 if (patchHandle) {
4551 index = mAudioPatches.indexOfKey(*patchHandle);
4552 } else {
4553 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4554 }
4555 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004556 return INVALID_OPERATION;
4557 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4559 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004560 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4561 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004562 removeAudioPatch(patchDesc->mHandle);
4563 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004564 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004565 return status;
4566}
4567
4568status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4569 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07004570 bool force,
4571 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004572{
4573 status_t status = NO_ERROR;
4574
Eric Laurent1f2f2232014-06-02 12:01:23 -07004575 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004576 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4577 inputDesc->mDevice = device;
4578
4579 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4580 if (!deviceList.isEmpty()) {
4581 struct audio_patch patch;
4582 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004583 // AUDIO_SOURCE_HOTWORD is for internal use only:
4584 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004585 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4586 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004587 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4588 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004589 patch.num_sinks = 1;
4590 //only one input device for now
4591 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004592 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004593 ssize_t index;
4594 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4595 index = mAudioPatches.indexOfKey(*patchHandle);
4596 } else {
4597 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4598 }
4599 sp< AudioPatch> patchDesc;
4600 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4601 if (index >= 0) {
4602 patchDesc = mAudioPatches.valueAt(index);
4603 afPatchHandle = patchDesc->mAfPatchHandle;
4604 }
4605
Eric Laurent1c333e22014-05-20 10:48:17 -07004606 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004608 0);
4609 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004610 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004611 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004612 if (index < 0) {
François Gaffie98cc1912015-03-18 17:52:40 +01004613 patchDesc = new AudioPatch(&patch, mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004614 addAudioPatch(patchDesc->mHandle, patchDesc);
4615 } else {
4616 patchDesc->mPatch = patch;
4617 }
4618 patchDesc->mAfPatchHandle = afPatchHandle;
4619 patchDesc->mUid = mUidCached;
4620 if (patchHandle) {
4621 *patchHandle = patchDesc->mHandle;
4622 }
4623 inputDesc->mPatchHandle = patchDesc->mHandle;
4624 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004625 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004626 }
4627 }
4628 }
4629 return status;
4630}
4631
Eric Laurent6a94d692014-05-20 11:18:06 -07004632status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4633 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004634{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004635 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004636 ssize_t index;
4637 if (patchHandle) {
4638 index = mAudioPatches.indexOfKey(*patchHandle);
4639 } else {
4640 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4641 }
4642 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004643 return INVALID_OPERATION;
4644 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004645 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4646 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004647 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4648 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004649 removeAudioPatch(patchDesc->mHandle);
4650 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004651 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004652 return status;
4653}
4654
Jean-Michel Trivi56ec4ff2015-01-23 16:45:18 -08004655sp<IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +01004656 String8 address,
4657 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07004658 audio_format_t& format,
4659 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01004660 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004661{
4662 // Choose an input profile based on the requested capture parameters: select the first available
4663 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07004664 //
4665 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
4666 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07004667
4668 for (size_t i = 0; i < mHwModules.size(); i++)
4669 {
4670 if (mHwModules[i]->mHandle == 0) {
4671 continue;
4672 }
4673 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4674 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004675 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004676 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08004677 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07004678 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07004679 format,
4680 &format /*updatedFormat*/,
4681 channelMask,
4682 &channelMask /*updatedChannelMask*/,
4683 (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08004684
Eric Laurente552edb2014-03-10 17:42:56 -07004685 return profile;
4686 }
4687 }
4688 }
4689 return NULL;
4690}
4691
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004692
4693audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
François Gaffie53615e22015-03-19 09:24:12 +01004694 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07004695{
François Gaffie036e1e92015-03-19 10:16:24 +01004696 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
4697 audio_devices_t selectedDeviceFromMix =
4698 mPolicyMixes.getDeviceAndMixForInputSource(inputSource, availableDeviceTypes, policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08004699
François Gaffie036e1e92015-03-19 10:16:24 +01004700 if (selectedDeviceFromMix != AUDIO_DEVICE_NONE) {
4701 return selectedDeviceFromMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08004702 }
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004703 return getDeviceForInputSource(inputSource);
4704}
4705
4706audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4707{
Paul McLean466dc8e2015-04-17 13:15:36 -06004708 for (size_t routeIndex = 0; routeIndex < mInputRoutes.size(); routeIndex++) {
4709 sp<SessionRoute> route = mInputRoutes.valueAt(routeIndex);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004710 if (inputSource == route->mSource && route->isActive()) {
Paul McLean466dc8e2015-04-17 13:15:36 -06004711 return route->mDeviceDescriptor->type();
4712 }
4713 }
4714
4715 return mEngine->getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07004716}
4717
Eric Laurente0720872014-03-11 09:30:41 -07004718float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004719 int index,
4720 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004721{
Eric Laurentffbc80f2015-03-18 18:30:19 -07004722 float volumeDb = mEngine->volIndexToDb(Volume::getDeviceCategory(device), stream, index);
Eric Laurente552edb2014-03-10 17:42:56 -07004723
4724 // if a headset is connected, apply the following rules to ring tones and notifications
4725 // to avoid sound level bursts in user's ears:
4726 // - always attenuate ring tones and notifications volume by 6dB
4727 // - if music is playing, always limit the volume to current music volume,
4728 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004729 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004730 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4731 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4732 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4733 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4734 ((stream_strategy == STRATEGY_SONIFICATION)
4735 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004736 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004737 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
François Gaffie2110e042015-03-24 08:41:51 +01004738 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
4739 mStreams.canBeMuted(stream)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004740 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07004741 // when the phone is ringing we must consider that music could have been paused just before
4742 // by the music application and behave as if music was active if the last music track was
4743 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004744 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004745 mLimitRingtoneVolume) {
4746 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004747 float musicVolDB = computeVolume(AUDIO_STREAM_MUSIC,
4748 mStreams.valueFor(AUDIO_STREAM_MUSIC).getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004749 musicDevice);
Eric Laurentffbc80f2015-03-18 18:30:19 -07004750 float minVolDB = (musicVolDB > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
4751 musicVolDB : SONIFICATION_HEADSET_VOLUME_MIN_DB;
4752 if (volumeDb > minVolDB) {
4753 volumeDb = minVolDB;
4754 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDB, musicVolDB);
Eric Laurente552edb2014-03-10 17:42:56 -07004755 }
4756 }
4757 }
4758
Eric Laurentffbc80f2015-03-18 18:30:19 -07004759 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07004760}
4761
Eric Laurente0720872014-03-11 09:30:41 -07004762status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004763 int index,
4764 const sp<AudioOutputDescriptor>& outputDesc,
4765 audio_devices_t device,
4766 int delayMs,
4767 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004768{
Eric Laurente552edb2014-03-10 17:42:56 -07004769 // do not change actual stream volume if the stream is muted
Eric Laurentc75307b2015-03-17 15:29:32 -07004770 if (outputDesc->mMuteCount[stream] != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004771 ALOGVV("checkAndSetVolume() stream %d muted count %d",
Eric Laurentc75307b2015-03-17 15:29:32 -07004772 stream, outputDesc->mMuteCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004773 return NO_ERROR;
4774 }
François Gaffie2110e042015-03-24 08:41:51 +01004775 audio_policy_forced_cfg_t forceUseForComm =
4776 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
Eric Laurente552edb2014-03-10 17:42:56 -07004777 // do not change in call volume if bluetooth is connected and vice versa
François Gaffie2110e042015-03-24 08:41:51 +01004778 if ((stream == AUDIO_STREAM_VOICE_CALL && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
4779 (stream == AUDIO_STREAM_BLUETOOTH_SCO && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004780 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
François Gaffie2110e042015-03-24 08:41:51 +01004781 stream, forceUseForComm);
Eric Laurente552edb2014-03-10 17:42:56 -07004782 return INVALID_OPERATION;
4783 }
4784
Eric Laurentc75307b2015-03-17 15:29:32 -07004785 if (device == AUDIO_DEVICE_NONE) {
4786 device = outputDesc->device();
4787 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004788
Eric Laurentffbc80f2015-03-18 18:30:19 -07004789 float volumeDb = computeVolume(stream, index, device);
Eric Laurentc75307b2015-03-17 15:29:32 -07004790 if (outputDesc->isFixedVolume(device)) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07004791 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08004792 }
Eric Laurentc75307b2015-03-17 15:29:32 -07004793
Eric Laurentffbc80f2015-03-18 18:30:19 -07004794 outputDesc->setVolume(volumeDb, stream, device, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07004795
Eric Laurent3b73df72014-03-11 09:06:29 -07004796 if (stream == AUDIO_STREAM_VOICE_CALL ||
4797 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004798 float voiceVolume;
4799 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004800 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004801 voiceVolume = (float)index/(float)mStreams.valueFor(stream).getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07004802 } else {
4803 voiceVolume = 1.0;
4804 }
4805
Eric Laurentc75307b2015-03-17 15:29:32 -07004806 if (voiceVolume != mLastVoiceVolume && outputDesc == mPrimaryOutput) {
Eric Laurente552edb2014-03-10 17:42:56 -07004807 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4808 mLastVoiceVolume = voiceVolume;
4809 }
4810 }
4811
4812 return NO_ERROR;
4813}
4814
Eric Laurentc75307b2015-03-17 15:29:32 -07004815void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
4816 audio_devices_t device,
4817 int delayMs,
4818 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07004819{
Eric Laurentc75307b2015-03-17 15:29:32 -07004820 ALOGVV("applyStreamVolumes() for device %08x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004821
Eric Laurent3b73df72014-03-11 09:06:29 -07004822 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004823 if (stream == AUDIO_STREAM_PATCH) {
4824 continue;
4825 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004826 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004827 mStreams.valueFor((audio_stream_type_t)stream).getVolumeIndex(device),
4828 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004829 device,
4830 delayMs,
4831 force);
4832 }
4833}
4834
Eric Laurente0720872014-03-11 09:30:41 -07004835void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurentc75307b2015-03-17 15:29:32 -07004836 bool on,
4837 const sp<AudioOutputDescriptor>& outputDesc,
4838 int delayMs,
4839 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004840{
Eric Laurent72249d52015-06-08 11:12:15 -07004841 ALOGVV("setStrategyMute() strategy %d, mute %d, output ID %d",
4842 strategy, on, outputDesc->getId());
Eric Laurent3b73df72014-03-11 09:06:29 -07004843 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004844 if (stream == AUDIO_STREAM_PATCH) {
4845 continue;
4846 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004847 if (getStrategy((audio_stream_type_t)stream) == strategy) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004848 setStreamMute((audio_stream_type_t)stream, on, outputDesc, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004849 }
4850 }
4851}
4852
Eric Laurente0720872014-03-11 09:30:41 -07004853void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurentc75307b2015-03-17 15:29:32 -07004854 bool on,
4855 const sp<AudioOutputDescriptor>& outputDesc,
4856 int delayMs,
4857 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004858{
Eric Laurentc75307b2015-03-17 15:29:32 -07004859 const StreamDescriptor& streamDesc = mStreams.valueFor(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004860 if (device == AUDIO_DEVICE_NONE) {
4861 device = outputDesc->device();
4862 }
4863
Eric Laurentc75307b2015-03-17 15:29:32 -07004864 ALOGVV("setStreamMute() stream %d, mute %d, mMuteCount %d device %04x",
4865 stream, on, outputDesc->mMuteCount[stream], device);
Eric Laurente552edb2014-03-10 17:42:56 -07004866
4867 if (on) {
4868 if (outputDesc->mMuteCount[stream] == 0) {
François Gaffiedfd74092015-03-19 12:10:59 +01004869 if (streamDesc.canBeMuted() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004870 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
François Gaffie2110e042015-03-24 08:41:51 +01004871 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004872 checkAndSetVolume(stream, 0, outputDesc, device, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004873 }
4874 }
4875 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4876 outputDesc->mMuteCount[stream]++;
4877 } else {
4878 if (outputDesc->mMuteCount[stream] == 0) {
4879 ALOGV("setStreamMute() unmuting non muted stream!");
4880 return;
4881 }
4882 if (--outputDesc->mMuteCount[stream] == 0) {
4883 checkAndSetVolume(stream,
4884 streamDesc.getVolumeIndex(device),
Eric Laurentc75307b2015-03-17 15:29:32 -07004885 outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004886 device,
4887 delayMs);
4888 }
4889 }
4890}
4891
Eric Laurente0720872014-03-11 09:30:41 -07004892void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004893 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004894{
Eric Laurent87ffa392015-05-22 10:32:38 -07004895 if(!hasPrimaryOutput()) {
4896 return;
4897 }
4898
Eric Laurente552edb2014-03-10 17:42:56 -07004899 // if the stream pertains to sonification strategy and we are in call we must
4900 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4901 // in the device used for phone strategy and play the tone if the selected device does not
4902 // interfere with the device used for phone strategy
4903 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4904 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004905 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004906 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4907 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004908 sp<SwAudioOutputDescriptor> outputDesc = mPrimaryOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004909 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4910 stream, starting, outputDesc->mDevice, stateChange);
4911 if (outputDesc->mRefCount[stream]) {
4912 int muteCount = 1;
4913 if (stateChange) {
4914 muteCount = outputDesc->mRefCount[stream];
4915 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004916 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004917 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4918 for (int i = 0; i < muteCount; i++) {
4919 setStreamMute(stream, starting, mPrimaryOutput);
4920 }
4921 } else {
4922 ALOGV("handleIncallSonification() high visibility");
4923 if (outputDesc->device() &
4924 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4925 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4926 for (int i = 0; i < muteCount; i++) {
4927 setStreamMute(stream, starting, mPrimaryOutput);
4928 }
4929 }
4930 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004931 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4932 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004933 } else {
4934 mpClientInterface->stopTone();
4935 }
4936 }
4937 }
4938 }
4939}
4940
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004941audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
4942{
4943 // flags to stream type mapping
4944 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4945 return AUDIO_STREAM_ENFORCED_AUDIBLE;
4946 }
4947 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
4948 return AUDIO_STREAM_BLUETOOTH_SCO;
4949 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08004950 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4951 return AUDIO_STREAM_TTS;
4952 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004953
4954 // usage to stream type mapping
4955 switch (attr->usage) {
4956 case AUDIO_USAGE_MEDIA:
4957 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004958 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4959 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004960 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08004961 if (isStreamActive(AUDIO_STREAM_ALARM)) {
4962 return AUDIO_STREAM_ALARM;
4963 }
4964 if (isStreamActive(AUDIO_STREAM_RING)) {
4965 return AUDIO_STREAM_RING;
4966 }
4967 if (isInCall()) {
4968 return AUDIO_STREAM_VOICE_CALL;
4969 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08004970 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004971 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4972 return AUDIO_STREAM_SYSTEM;
4973 case AUDIO_USAGE_VOICE_COMMUNICATION:
4974 return AUDIO_STREAM_VOICE_CALL;
4975
4976 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4977 return AUDIO_STREAM_DTMF;
4978
4979 case AUDIO_USAGE_ALARM:
4980 return AUDIO_STREAM_ALARM;
4981 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4982 return AUDIO_STREAM_RING;
4983
4984 case AUDIO_USAGE_NOTIFICATION:
4985 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4986 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4987 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4988 case AUDIO_USAGE_NOTIFICATION_EVENT:
4989 return AUDIO_STREAM_NOTIFICATION;
4990
4991 case AUDIO_USAGE_UNKNOWN:
4992 default:
4993 return AUDIO_STREAM_MUSIC;
4994 }
4995}
Eric Laurente83b55d2014-11-14 10:06:21 -08004996
François Gaffie53615e22015-03-19 09:24:12 +01004997bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
4998{
Eric Laurente83b55d2014-11-14 10:06:21 -08004999 // has flags that map to a strategy?
5000 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5001 return true;
5002 }
5003
5004 // has known usage?
5005 switch (paa->usage) {
5006 case AUDIO_USAGE_UNKNOWN:
5007 case AUDIO_USAGE_MEDIA:
5008 case AUDIO_USAGE_VOICE_COMMUNICATION:
5009 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5010 case AUDIO_USAGE_ALARM:
5011 case AUDIO_USAGE_NOTIFICATION:
5012 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5013 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5014 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5015 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5016 case AUDIO_USAGE_NOTIFICATION_EVENT:
5017 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5018 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5019 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5020 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08005021 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08005022 break;
5023 default:
5024 return false;
5025 }
5026 return true;
5027}
5028
François Gaffiead3183e2015-03-18 16:55:35 +01005029bool AudioPolicyManager::isStrategyActive(const sp<AudioOutputDescriptor> outputDesc,
5030 routing_strategy strategy, uint32_t inPastMs,
5031 nsecs_t sysTime) const
5032{
5033 if ((sysTime == 0) && (inPastMs != 0)) {
5034 sysTime = systemTime();
5035 }
5036 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
5037 if (i == AUDIO_STREAM_PATCH) {
5038 continue;
5039 }
5040 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
5041 (NUM_STRATEGIES == strategy)) &&
5042 outputDesc->isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
5043 return true;
5044 }
5045 }
5046 return false;
5047}
5048
François Gaffie2110e042015-03-24 08:41:51 +01005049audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5050{
5051 return mEngine->getForceUse(usage);
5052}
5053
5054bool AudioPolicyManager::isInCall()
5055{
5056 return isStateInCall(mEngine->getPhoneState());
5057}
5058
5059bool AudioPolicyManager::isStateInCall(int state)
5060{
5061 return is_state_in_call(state);
5062}
5063
Eric Laurentd60560a2015-04-10 11:31:20 -07005064void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5065{
5066 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5067 sp<AudioSourceDescriptor> sourceDesc = mAudioSources.valueAt(i);
5068 if (sourceDesc->mDevice->equals(deviceDesc)) {
5069 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->getHandle());
5070 stopAudioSource(sourceDesc->getHandle());
5071 }
5072 }
5073
5074 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5075 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5076 bool release = false;
5077 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
5078 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
5079 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
5080 source->ext.device.type == deviceDesc->type()) {
5081 release = true;
5082 }
5083 }
5084 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
5085 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
5086 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
5087 sink->ext.device.type == deviceDesc->type()) {
5088 release = true;
5089 }
5090 }
5091 if (release) {
5092 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
5093 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
5094 }
5095 }
5096}
5097
5098
Eric Laurente552edb2014-03-10 17:42:56 -07005099}; // namespace android