1 /*
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
17 #define LOG_TAG "APM_AudioPolicyManager"
18
19 // Need to keep the log statements even in production builds
20 // to enable VERBOSE logging dynamically.
21 // You can enable VERBOSE logging as follows:
22 // adb shell setprop log.tag.APM_AudioPolicyManager V
23 #define LOG_NDEBUG 0
24
25 //#define VERY_VERBOSE_LOGGING
26 #ifdef VERY_VERBOSE_LOGGING
27 #define ALOGVV ALOGV
28 #else
29 #define ALOGVV(a...) do { } while(0)
30 #endif
31
32 #define AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH 128
33 #define AUDIO_POLICY_XML_CONFIG_FILE_NAME "audio_policy_configuration.xml"
34 #define AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME \
35 "audio_policy_configuration_a2dp_offload_disabled.xml"
36 #define AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME \
37 "audio_policy_configuration_bluetooth_legacy_hal.xml"
38
39 #include <algorithm>
40 #include <inttypes.h>
41 #include <math.h>
42 #include <set>
43 #include <unordered_set>
44 #include <vector>
45 #include <AudioPolicyManagerInterface.h>
46 #include <AudioPolicyEngineInstance.h>
47 #include <cutils/properties.h>
48 #include <utils/Log.h>
49 #include <media/AudioParameter.h>
50 #include <private/android_filesystem_config.h>
51 #include <soundtrigger/SoundTrigger.h>
52 #include <system/audio.h>
53 #include <audio_policy_conf.h>
54 #include "AudioPolicyManager.h"
55 #include <Serializer.h>
56 #include "TypeConverter.h"
57 #include <policy.h>
58
59 namespace android {
60
61 //FIXME: workaround for truncated touch sounds
62 // to be removed when the problem is handled by system UI
63 #define TOUCH_SOUND_FIXED_DELAY_MS 100
64
65 // Largest difference in dB on earpiece in call between the voice volume and another
66 // media / notification / system volume.
67 constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
68
69 // Compressed formats for MSD module, ordered from most preferred to least preferred.
70 static const std::vector<audio_format_t> compressedFormatsOrder = {{
71 AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
72 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
73 // Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
74 static const std::vector<audio_channel_mask_t> surroundChannelMasksOrder = {{
75 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
76 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
77 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
78
79 // ----------------------------------------------------------------------------
80 // AudioPolicyInterface implementation
81 // ----------------------------------------------------------------------------
82
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)83 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
84 audio_policy_dev_state_t state,
85 const char *device_address,
86 const char *device_name,
87 audio_format_t encodedFormat)
88 {
89 status_t status = setDeviceConnectionStateInt(device, state, device_address,
90 device_name, encodedFormat);
91 nextAudioPortGeneration();
92 return status;
93 }
94
broadcastDeviceConnectionState(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state)95 void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
96 audio_policy_dev_state_t state)
97 {
98 AudioParameter param(device->address());
99 const String8 key(state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE ?
100 AudioParameter::keyStreamConnect : AudioParameter::keyStreamDisconnect);
101 param.addInt(key, device->type());
102 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
103 }
104
setDeviceConnectionStateInt(audio_devices_t deviceType,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)105 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
106 audio_policy_dev_state_t state,
107 const char *device_address,
108 const char *device_name,
109 audio_format_t encodedFormat)
110 {
111 ALOGV("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
112 deviceType, state, device_address, device_name, encodedFormat);
113
114 // connect/disconnect only 1 device at a time
115 if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
116
117 sp<DeviceDescriptor> device =
118 mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
119 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
120 if (device == 0) {
121 return INVALID_OPERATION;
122 }
123
124 // handle output devices
125 if (audio_is_output_device(deviceType)) {
126 SortedVector <audio_io_handle_t> outputs;
127
128 ssize_t index = mAvailableOutputDevices.indexOf(device);
129
130 // save a copy of the opened output descriptors before any output is opened or closed
131 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
132 mPreviousOutputs = mOutputs;
133 switch (state)
134 {
135 // handle output device connection
136 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
137 if (index >= 0) {
138 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
139 return INVALID_OPERATION;
140 }
141 ALOGV("%s() connecting device %s format %x",
142 __func__, device->toString().c_str(), encodedFormat);
143
144 // register new device as available
145 if (mAvailableOutputDevices.add(device) < 0) {
146 return NO_MEMORY;
147 }
148
149 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
150 // parameters on newly connected devices (instead of opening the outputs...)
151 broadcastDeviceConnectionState(device, state);
152
153 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
154 mAvailableOutputDevices.remove(device);
155
156 mHwModules.cleanUpForDevice(device);
157
158 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
159 return INVALID_OPERATION;
160 }
161
162 // outputs should never be empty here
163 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
164 "checkOutputsForDevice() returned no outputs but status OK");
165 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
166
167 } break;
168 // handle output device disconnection
169 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
170 if (index < 0) {
171 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
172 return INVALID_OPERATION;
173 }
174
175 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
176
177 // Send Disconnect to HALs
178 broadcastDeviceConnectionState(device, state);
179
180 // remove device from available output devices
181 mAvailableOutputDevices.remove(device);
182
183 mOutputs.clearSessionRoutesForDevice(device);
184
185 checkOutputsForDevice(device, state, outputs);
186
187 // Reset active device codec
188 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
189
190 } break;
191
192 default:
193 ALOGE("%s() invalid state: %x", __func__, state);
194 return BAD_VALUE;
195 }
196
197 // Propagate device availability to Engine
198 setEngineDeviceConnectionState(device, state);
199
200 // No need to evaluate playback routing when connecting a remote submix
201 // output device used by a dynamic policy of type recorder as no
202 // playback use case is affected.
203 bool doCheckForDeviceAndOutputChanges = true;
204 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX
205 && strncmp(device_address, "0", AUDIO_DEVICE_MAX_ADDRESS_LEN) != 0) {
206 for (audio_io_handle_t output : outputs) {
207 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
208 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
209 if (policyMix != nullptr
210 && policyMix->mMixType == MIX_TYPE_RECORDERS
211 && strncmp(device_address,
212 policyMix->mDeviceAddress.string(),
213 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
214 doCheckForDeviceAndOutputChanges = false;
215 break;
216 }
217 }
218 }
219
220 auto checkCloseOutputs = [&]() {
221 // outputs must be closed after checkOutputForAllStrategies() is executed
222 if (!outputs.isEmpty()) {
223 for (audio_io_handle_t output : outputs) {
224 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
225 // close unused outputs after device disconnection or direct outputs that have
226 // been opened by checkOutputsForDevice() to query dynamic parameters
227 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
228 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
229 (desc->mDirectOpenCount == 0))) {
230 closeOutput(output);
231 }
232 }
233 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
234 return true;
235 }
236 return false;
237 };
238
239 if (doCheckForDeviceAndOutputChanges) {
240 checkForDeviceAndOutputChanges(checkCloseOutputs);
241 } else {
242 checkCloseOutputs();
243 }
244
245 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
246 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
247 updateCallRouting(newDevices);
248 }
249 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
250 for (size_t i = 0; i < mOutputs.size(); i++) {
251 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
252 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (desc != mPrimaryOutput)) {
253 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
254 // do not force device change on duplicated output because if device is 0, it will
255 // also force a device 0 for the two outputs it is duplicated to which may override
256 // a valid device selection on those outputs.
257 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
258 && !desc->isDuplicated()
259 && (!device_distinguishes_on_address(deviceType)
260 // always force when disconnecting (a non-duplicated device)
261 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
262 setOutputDevices(desc, newDevices, force, 0);
263 }
264 }
265
266 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
267 cleanUpForDevice(device);
268 }
269
270 mpClientInterface->onAudioPortListUpdate();
271 return NO_ERROR;
272 } // end if is output device
273
274 // handle input devices
275 if (audio_is_input_device(deviceType)) {
276 ssize_t index = mAvailableInputDevices.indexOf(device);
277 switch (state)
278 {
279 // handle input device connection
280 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
281 if (index >= 0) {
282 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
283 return INVALID_OPERATION;
284 }
285
286 if (mAvailableInputDevices.add(device) < 0) {
287 return NO_MEMORY;
288 }
289
290 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
291 // parameters on newly connected devices (instead of opening the inputs...)
292 broadcastDeviceConnectionState(device, state);
293
294 if (checkInputsForDevice(device, state) != NO_ERROR) {
295 mAvailableInputDevices.remove(device);
296
297 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
298
299 mHwModules.cleanUpForDevice(device);
300
301 return INVALID_OPERATION;
302 }
303
304 } break;
305
306 // handle input device disconnection
307 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
308 if (index < 0) {
309 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
310 return INVALID_OPERATION;
311 }
312
313 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
314
315 // Set Disconnect to HALs
316 broadcastDeviceConnectionState(device, state);
317
318 mAvailableInputDevices.remove(device);
319
320 checkInputsForDevice(device, state);
321 } break;
322
323 default:
324 ALOGE("%s() invalid state: %x", __func__, state);
325 return BAD_VALUE;
326 }
327
328 // Propagate device availability to Engine
329 setEngineDeviceConnectionState(device, state);
330
331 checkCloseInputs();
332 // As the input device list can impact the output device selection, update
333 // getDeviceForStrategy() cache
334 updateDevicesAndOutputs();
335
336 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
337 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
338 updateCallRouting(newDevices);
339 }
340
341 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
342 cleanUpForDevice(device);
343 }
344
345 mpClientInterface->onAudioPortListUpdate();
346 return NO_ERROR;
347 } // end if is input device
348
349 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
350 return BAD_VALUE;
351 }
352
setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,audio_policy_dev_state_t state)353 void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
354 audio_policy_dev_state_t state) {
355
356 // the Engine does not have to know about remote submix devices used by dynamic audio policies
357 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
358 return;
359 }
360 mEngine->setDeviceConnectionState(device, state);
361 }
362
363
getDeviceConnectionState(audio_devices_t device,const char * device_address)364 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
365 const char *device_address)
366 {
367 sp<DeviceDescriptor> devDesc =
368 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
369 false /* allowToCreate */,
370 (strlen(device_address) != 0)/*matchAddress*/);
371
372 if (devDesc == 0) {
373 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
374 device, device_address);
375 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
376 }
377
378 DeviceVector *deviceVector;
379
380 if (audio_is_output_device(device)) {
381 deviceVector = &mAvailableOutputDevices;
382 } else if (audio_is_input_device(device)) {
383 deviceVector = &mAvailableInputDevices;
384 } else {
385 ALOGW("%s() invalid device type %08x", __func__, device);
386 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
387 }
388
389 return (deviceVector->getDevice(
390 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
391 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
392 }
393
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name,audio_format_t encodedFormat)394 status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
395 const char *device_address,
396 const char *device_name,
397 audio_format_t encodedFormat)
398 {
399 status_t status;
400 String8 reply;
401 AudioParameter param;
402 int isReconfigA2dpSupported = 0;
403
404 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
405 device, device_address, device_name, encodedFormat);
406
407 // connect/disconnect only 1 device at a time
408 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
409
410 // Check if the device is currently connected
411 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromTypeMask(device);
412 if (deviceList.empty()) {
413 // Nothing to do: device is not connected
414 return NO_ERROR;
415 }
416 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
417
418 // For offloaded A2DP, Hw modules may have the capability to
419 // configure codecs.
420 // Handle two specific cases by sending a set parameter to
421 // configure A2DP codecs. No need to toggle device state.
422 // Case 1: A2DP active device switches from primary to primary
423 // module
424 // Case 2: A2DP device config changes on primary module.
425 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
426 sp<HwModule> module = mHwModules.getModuleForDeviceTypes(device, encodedFormat);
427 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
428 if (availablePrimaryOutputDevices().contains(devDesc) &&
429 (module != 0 && module->getHandle() == primaryHandle)) {
430 reply = mpClientInterface->getParameters(
431 AUDIO_IO_HANDLE_NONE,
432 String8(AudioParameter::keyReconfigA2dpSupported));
433 AudioParameter repliedParameters(reply);
434 repliedParameters.getInt(
435 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
436 if (isReconfigA2dpSupported) {
437 const String8 key(AudioParameter::keyReconfigA2dp);
438 param.add(key, String8("true"));
439 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
440 devDesc->setEncodedFormat(encodedFormat);
441 return NO_ERROR;
442 }
443 }
444 }
445
446 // Toggle the device state: UNAVAILABLE -> AVAILABLE
447 // This will force reading again the device configuration
448 status = setDeviceConnectionState(device,
449 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
450 device_address, device_name,
451 devDesc->getEncodedFormat());
452 if (status != NO_ERROR) {
453 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
454 status);
455 return status;
456 }
457
458 status = setDeviceConnectionState(device,
459 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
460 device_address, device_name, encodedFormat);
461 if (status != NO_ERROR) {
462 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
463 status);
464 return status;
465 }
466
467 return NO_ERROR;
468 }
469
getHwOffloadEncodingFormatsSupportedForA2DP(std::vector<audio_format_t> * formats)470 status_t AudioPolicyManager::getHwOffloadEncodingFormatsSupportedForA2DP(
471 std::vector<audio_format_t> *formats)
472 {
473 ALOGV("getHwOffloadEncodingFormatsSupportedForA2DP()");
474 status_t status = NO_ERROR;
475 std::unordered_set<audio_format_t> formatSet;
476 sp<HwModule> primaryModule =
477 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
478 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypeMask(
479 AUDIO_DEVICE_OUT_ALL_A2DP);
480 for (const auto& device : declaredDevices) {
481 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
482 }
483 formats->assign(formatSet.begin(), formatSet.end());
484 return status;
485 }
486
updateCallRouting(const DeviceVector & rxDevices,uint32_t delayMs)487 uint32_t AudioPolicyManager::updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs)
488 {
489 bool createTxPatch = false;
490 bool createRxPatch = false;
491 uint32_t muteWaitMs = 0;
492
493 if(!hasPrimaryOutput() || mPrimaryOutput->devices().types() == AUDIO_DEVICE_OUT_STUB) {
494 return muteWaitMs;
495 }
496 ALOG_ASSERT(!rxDevices.isEmpty(), "updateCallRouting() no selected output device");
497
498 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
499 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
500 ALOG_ASSERT(txSourceDevice != 0, "updateCallRouting() input selected device not available");
501
502 ALOGV("updateCallRouting device rxDevice %s txDevice %s",
503 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
504
505 // release existing RX patch if any
506 if (mCallRxPatch != 0) {
507 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
508 mCallRxPatch.clear();
509 }
510 // release TX patch if any
511 if (mCallTxPatch != 0) {
512 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
513 mCallTxPatch.clear();
514 }
515
516 auto telephonyRxModule =
517 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
518 auto telephonyTxModule =
519 mHwModules.getModuleForDeviceTypes(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
520 // retrieve Rx Source and Tx Sink device descriptors
521 sp<DeviceDescriptor> rxSourceDevice =
522 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
523 String8(),
524 AUDIO_FORMAT_DEFAULT);
525 sp<DeviceDescriptor> txSinkDevice =
526 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
527 String8(),
528 AUDIO_FORMAT_DEFAULT);
529
530 // RX and TX Telephony device are declared by Primary Audio HAL
531 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
532 (telephonyRxModule->getHalVersionMajor() >= 3)) {
533 if (rxSourceDevice == 0 || txSinkDevice == 0) {
534 // RX / TX Telephony device(s) is(are) not currently available
535 ALOGE("updateCallRouting() no telephony Tx and/or RX device");
536 return muteWaitMs;
537 }
538 // do not create a patch (aka Sw Bridging) if Primary HW module has declared supporting a
539 // route between telephony RX to Sink device and Source device to telephony TX
540 const auto &primaryModule = telephonyRxModule;
541 createRxPatch = !primaryModule->supportsPatch(rxSourceDevice, rxDevices.itemAt(0));
542 createTxPatch = !primaryModule->supportsPatch(txSourceDevice, txSinkDevice);
543 } else {
544 // If the RX device is on the primary HW module, then use legacy routing method for
545 // voice calls via setOutputDevice() on primary output.
546 // Otherwise, create two audio patches for TX and RX path.
547 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
548 (rxSourceDevice != 0);
549 // If the TX device is also on the primary HW module, setOutputDevice() will take care
550 // of it due to legacy implementation. If not, create a patch.
551 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
552 (txSinkDevice != 0);
553 }
554 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
555 // Otherwise, create two audio patches for TX and RX path.
556 if (!createRxPatch) {
557 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
558 } else { // create RX path audio patch
559 mCallRxPatch = createTelephonyPatch(true /*isRx*/, rxDevices.itemAt(0), delayMs);
560
561 // If the TX device is on the primary HW module but RX device is
562 // on other HW module, SinkMetaData of telephony input should handle it
563 // assuming the device uses audio HAL V5.0 and above
564 }
565 if (createTxPatch) { // create TX path audio patch
566 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
567 }
568
569 return muteWaitMs;
570 }
571
createTelephonyPatch(bool isRx,const sp<DeviceDescriptor> & device,uint32_t delayMs)572 sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
573 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
574 PatchBuilder patchBuilder;
575
576 if (device == nullptr) {
577 return nullptr;
578 }
579 if (isRx) {
580 patchBuilder.addSink(device).
581 addSource(mAvailableInputDevices.getDevice(
582 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
583 } else {
584 patchBuilder.addSource(device).
585 addSink(mAvailableOutputDevices.getDevice(
586 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
587 }
588
589 // @TODO: still ignoring the address, or not dealing platform with mutliple telephonydevices
590 const sp<DeviceDescriptor> outputDevice = isRx ?
591 device : mAvailableOutputDevices.getDevice(
592 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT);
593 SortedVector<audio_io_handle_t> outputs =
594 getOutputsForDevices(DeviceVector(outputDevice), mOutputs);
595 const audio_io_handle_t output = selectOutput(outputs);
596 // request to reuse existing output stream if one is already opened to reach the target device
597 if (output != AUDIO_IO_HANDLE_NONE) {
598 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
599 ALOG_ASSERT(!outputDesc->isDuplicated(), "%s() %s device output %d is duplicated", __func__,
600 outputDevice->toString().c_str(), output);
601 patchBuilder.addSource(outputDesc, { .stream = AUDIO_STREAM_PATCH });
602 }
603
604 if (!isRx) {
605 // terminate active capture if on the same HW module as the call TX source device
606 // FIXME: would be better to refine to only inputs whose profile connects to the
607 // call TX device but this information is not in the audio patch and logic here must be
608 // symmetric to the one in startInput()
609 for (const auto& activeDesc : mInputs.getActiveInputs()) {
610 if (activeDesc->hasSameHwModuleAs(device)) {
611 closeActiveClients(activeDesc);
612 }
613 }
614 }
615
616 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
617 status_t status = mpClientInterface->createAudioPatch(
618 patchBuilder.patch(), &afPatchHandle, delayMs);
619 ALOGW_IF(status != NO_ERROR,
620 "%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
621 sp<AudioPatch> audioPatch;
622 if (status == NO_ERROR) {
623 audioPatch = new AudioPatch(patchBuilder.patch(), mUidCached);
624 audioPatch->mAfPatchHandle = afPatchHandle;
625 audioPatch->mUid = mUidCached;
626 }
627 return audioPatch;
628 }
629
findDevice(const DeviceVector & devices,audio_devices_t device) const630 sp<DeviceDescriptor> AudioPolicyManager::findDevice(
631 const DeviceVector& devices, audio_devices_t device) const {
632 DeviceVector deviceList = devices.getDevicesFromTypeMask(device);
633 ALOG_ASSERT(!deviceList.isEmpty(),
634 "%s() selected device type %#x is not in devices list", __func__, device);
635 return deviceList.itemAt(0);
636 }
637
getModuleDeviceTypes(const DeviceVector & devices,const char * moduleId) const638 audio_devices_t AudioPolicyManager::getModuleDeviceTypes(
639 const DeviceVector& devices, const char *moduleId) const {
640 sp<HwModule> mod = mHwModules.getModuleFromName(moduleId);
641 return mod != 0 ? devices.getDeviceTypesFromHwModule(mod->getHandle()) : AUDIO_DEVICE_NONE;
642 }
643
isDeviceOfModule(const sp<DeviceDescriptor> & devDesc,const char * moduleId) const644 bool AudioPolicyManager::isDeviceOfModule(
645 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
646 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
647 if (module != 0) {
648 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
649 .indexOf(devDesc) != NAME_NOT_FOUND
650 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
651 .indexOf(devDesc) != NAME_NOT_FOUND;
652 }
653 return false;
654 }
655
setPhoneState(audio_mode_t state)656 void AudioPolicyManager::setPhoneState(audio_mode_t state)
657 {
658 ALOGV("setPhoneState() state %d", state);
659 // store previous phone state for management of sonification strategy below
660 int oldState = mEngine->getPhoneState();
661
662 if (mEngine->setPhoneState(state) != NO_ERROR) {
663 ALOGW("setPhoneState() invalid or same state %d", state);
664 return;
665 }
666 /// Opens: can these line be executed after the switch of volume curves???
667 if (isStateInCall(oldState)) {
668 ALOGV("setPhoneState() in call state management: new state is %d", state);
669 // force reevaluating accessibility routing when call stops
670 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
671 }
672
673 /**
674 * Switching to or from incall state or switching between telephony and VoIP lead to force
675 * routing command.
676 */
677 bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
678 || (is_state_in_call(state) && (state != oldState)));
679
680 // check for device and output changes triggered by new phone state
681 checkForDeviceAndOutputChanges();
682
683 int delayMs = 0;
684 if (isStateInCall(state)) {
685 nsecs_t sysTime = systemTime();
686 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
687 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
688 for (size_t i = 0; i < mOutputs.size(); i++) {
689 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
690 // mute media and sonification strategies and delay device switch by the largest
691 // latency of any output where either strategy is active.
692 // This avoid sending the ring tone or music tail into the earpiece or headset.
693 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
694 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
695 sysTime)) &&
696 (delayMs < (int)desc->latency()*2)) {
697 delayMs = desc->latency()*2;
698 }
699 setStrategyMute(musicStrategy, true, desc);
700 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
701 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
702 nullptr, true /*fromCache*/).types());
703 setStrategyMute(sonificationStrategy, true, desc);
704 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
705 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
706 nullptr, true /*fromCache*/).types());
707 }
708 }
709
710 if (hasPrimaryOutput()) {
711 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
712 // the device returned is not necessarily reachable via this output
713 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
714 // force routing command to audio hardware when ending call
715 // even if no device change is needed
716 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
717 rxDevices = mPrimaryOutput->devices();
718 }
719
720 if (state == AUDIO_MODE_IN_CALL) {
721 updateCallRouting(rxDevices, delayMs);
722 } else if (oldState == AUDIO_MODE_IN_CALL) {
723 if (mCallRxPatch != 0) {
724 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
725 mCallRxPatch.clear();
726 }
727 if (mCallTxPatch != 0) {
728 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
729 mCallTxPatch.clear();
730 }
731 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
732 } else {
733 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
734 }
735 }
736
737 // reevaluate routing on all outputs in case tracks have been started during the call
738 for (size_t i = 0; i < mOutputs.size(); i++) {
739 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
740 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
741 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
742 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
743 }
744 }
745
746 if (isStateInCall(state)) {
747 ALOGV("setPhoneState() in call state management: new state is %d", state);
748 // force reevaluating accessibility routing when call starts
749 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
750 }
751
752 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
753 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
754 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
755 }
756
getPhoneState()757 audio_mode_t AudioPolicyManager::getPhoneState() {
758 return mEngine->getPhoneState();
759 }
760
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)761 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
762 audio_policy_forced_cfg_t config)
763 {
764 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
765 if (config == mEngine->getForceUse(usage)) {
766 return;
767 }
768
769 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
770 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
771 return;
772 }
773 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
774 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
775 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
776
777 // check for device and output changes triggered by new force usage
778 checkForDeviceAndOutputChanges();
779
780 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
781 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
782 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
783 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
784 }
785
786 //FIXME: workaround for truncated touch sounds
787 // to be removed when the problem is handled by system UI
788 uint32_t delayMs = 0;
789 uint32_t waitMs = 0;
790 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
791 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
792 }
793 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
794 DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
795 waitMs = updateCallRouting(newDevices, delayMs);
796 }
797 for (size_t i = 0; i < mOutputs.size(); i++) {
798 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
799 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
800 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
801 // As done in setDeviceConnectionState, we could also fix default device issue by
802 // preventing the force re-routing in case of default dev that distinguishes on address.
803 // Let's give back to engine full device choice decision however.
804 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
805 }
806 if (forceVolumeReeval && !newDevices.isEmpty()) {
807 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
808 }
809 }
810
811 for (const auto& activeDesc : mInputs.getActiveInputs()) {
812 auto newDevice = getNewInputDevice(activeDesc);
813 // Force new input selection if the new device can not be reached via current input
814 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
815 setInputDevice(activeDesc->mIoHandle, newDevice);
816 } else {
817 closeInput(activeDesc->mIoHandle);
818 }
819 }
820 }
821
setSystemProperty(const char * property,const char * value)822 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
823 {
824 ALOGV("setSystemProperty() property %s, value %s", property, value);
825 }
826
827 // Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
828 // search to profiles for direct outputs.
getProfileForOutput(const DeviceVector & devices,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,bool directOnly)829 sp<IOProfile> AudioPolicyManager::getProfileForOutput(
830 const DeviceVector& devices,
831 uint32_t samplingRate,
832 audio_format_t format,
833 audio_channel_mask_t channelMask,
834 audio_output_flags_t flags,
835 bool directOnly)
836 {
837 if (directOnly) {
838 // only retain flags that will drive the direct output profile selection
839 // if explicitly requested
840 static const uint32_t kRelevantFlags =
841 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
842 AUDIO_OUTPUT_FLAG_VOIP_RX);
843 flags =
844 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
845 }
846
847 sp<IOProfile> profile;
848
849 for (const auto& hwModule : mHwModules) {
850 for (const auto& curProfile : hwModule->getOutputProfiles()) {
851 if (!curProfile->isCompatibleProfile(devices,
852 samplingRate, NULL /*updatedSamplingRate*/,
853 format, NULL /*updatedFormat*/,
854 channelMask, NULL /*updatedChannelMask*/,
855 flags)) {
856 continue;
857 }
858 // reject profiles not corresponding to a device currently available
859 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
860 continue;
861 }
862 // reject profiles if connected device does not support codec
863 if (!curProfile->deviceSupportsEncodedFormats(devices.types())) {
864 continue;
865 }
866 if (!directOnly) return curProfile;
867 // when searching for direct outputs, if several profiles are compatible, give priority
868 // to one with offload capability
869 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
870 continue;
871 }
872 profile = curProfile;
873 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
874 break;
875 }
876 }
877 }
878 return profile;
879 }
880
getOutput(audio_stream_type_t stream)881 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
882 {
883 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
884
885 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
886 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
887 // format, flags, etc. This may result in some discrepancy for functions that utilize
888 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
889 // and AudioSystem::getOutputSamplingRate().
890
891 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
892 const audio_io_handle_t output = selectOutput(outputs);
893
894 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
895 devices.toString().c_str(), output);
896 return output;
897 }
898
getAudioAttributes(audio_attributes_t * dstAttr,const audio_attributes_t * srcAttr,audio_stream_type_t srcStream)899 status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
900 const audio_attributes_t *srcAttr,
901 audio_stream_type_t srcStream)
902 {
903 if (srcAttr != NULL) {
904 if (!isValidAttributes(srcAttr)) {
905 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
906 __func__,
907 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
908 srcAttr->tags);
909 return BAD_VALUE;
910 }
911 *dstAttr = *srcAttr;
912 } else {
913 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
914 ALOGE("%s: invalid stream type", __func__);
915 return BAD_VALUE;
916 }
917 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
918 }
919
920 // Only honor audibility enforced when required. The client will be
921 // forced to reconnect if the forced usage changes.
922 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
923 dstAttr->flags &= ~AUDIO_FLAG_AUDIBILITY_ENFORCED;
924 }
925
926 return NO_ERROR;
927 }
928
getOutputForAttrInt(audio_attributes_t * resultAttr,audio_io_handle_t * output,audio_session_t session,const audio_attributes_t * attr,audio_stream_type_t * stream,uid_t uid,const audio_config_t * config,audio_output_flags_t * flags,audio_port_handle_t * selectedDeviceId,bool * isRequestedDeviceForExclusiveUse,std::vector<sp<SwAudioOutputDescriptor>> * secondaryDescs)929 status_t AudioPolicyManager::getOutputForAttrInt(
930 audio_attributes_t *resultAttr,
931 audio_io_handle_t *output,
932 audio_session_t session,
933 const audio_attributes_t *attr,
934 audio_stream_type_t *stream,
935 uid_t uid,
936 const audio_config_t *config,
937 audio_output_flags_t *flags,
938 audio_port_handle_t *selectedDeviceId,
939 bool *isRequestedDeviceForExclusiveUse,
940 std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs)
941 {
942 DeviceVector outputDevices;
943 const audio_port_handle_t requestedPortId = *selectedDeviceId;
944 DeviceVector msdDevices = getMsdAudioOutDevices();
945 const sp<DeviceDescriptor> requestedDevice =
946 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
947
948 status_t status = getAudioAttributes(resultAttr, attr, *stream);
949 if (status != NO_ERROR) {
950 return status;
951 }
952 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
953 resultAttr->flags |= it->second;
954 }
955 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
956
957 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
958 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
959
960 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
961 // otherwise, fallback to the dynamic policies, if none match, query the engine.
962 // Secondary outputs are always found by dynamic policies as the engine do not support them
963 sp<SwAudioOutputDescriptor> policyDesc;
964 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, policyDesc, secondaryDescs);
965 if (status != OK) {
966 return status;
967 }
968
969 // Explicit routing is higher priority then any dynamic policy primary output
970 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && policyDesc != nullptr;
971
972 // FIXME: in case of RENDER policy, the output capabilities should be checked
973 if ((usePrimaryOutputFromPolicyMixes || !secondaryDescs->empty())
974 && !audio_is_linear_pcm(config->format)) {
975 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
976 return BAD_VALUE;
977 }
978 if (usePrimaryOutputFromPolicyMixes) {
979 *output = policyDesc->mIoHandle;
980 sp<AudioPolicyMix> mix = policyDesc->mPolicyMix.promote();
981 sp<DeviceDescriptor> deviceDesc =
982 mAvailableOutputDevices.getDevice(mix->mDeviceType,
983 mix->mDeviceAddress,
984 AUDIO_FORMAT_DEFAULT);
985 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
986 ALOGV("getOutputForAttr() returns output %d", *output);
987 return NO_ERROR;
988 }
989 // Virtual sources must always be dynamicaly or explicitly routed
990 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
991 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
992 return BAD_VALUE;
993 }
994 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
995 // in order to let the choice of the order to future vendor engine
996 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
997
998 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
999 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1000 }
1001
1002 // Set incall music only if device was explicitly set, and fallback to the device which is
1003 // chosen by the engine if not.
1004 // FIXME: provide a more generic approach which is not device specific and move this back
1005 // to getOutputForDevice.
1006 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
1007 if (outputDevices.types() == AUDIO_DEVICE_OUT_TELEPHONY_TX &&
1008 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
1009 audio_is_linear_pcm(config->format) &&
1010 isInCall()) {
1011 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
1012 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
1013 *isRequestedDeviceForExclusiveUse = true;
1014 }
1015 }
1016
1017 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1018 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1019 config->channel_mask, *flags, toString(*stream).c_str());
1020
1021 *output = AUDIO_IO_HANDLE_NONE;
1022 if (!msdDevices.isEmpty()) {
1023 *output = getOutputForDevices(msdDevices, session, *stream, config, flags);
1024 sp<DeviceDescriptor> device = outputDevices.isEmpty() ? nullptr : outputDevices.itemAt(0);
1025 if (*output != AUDIO_IO_HANDLE_NONE && setMsdPatch(device) == NO_ERROR) {
1026 ALOGV("%s() Using MSD devices %s instead of devices %s",
1027 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1028 outputDevices = msdDevices;
1029 } else {
1030 *output = AUDIO_IO_HANDLE_NONE;
1031 }
1032 }
1033 if (*output == AUDIO_IO_HANDLE_NONE) {
1034 *output = getOutputForDevices(outputDevices, session, *stream, config,
1035 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
1036 }
1037 if (*output == AUDIO_IO_HANDLE_NONE) {
1038 return INVALID_OPERATION;
1039 }
1040
1041 *selectedDeviceId = getFirstDeviceId(outputDevices);
1042
1043 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1044
1045 return NO_ERROR;
1046 }
1047
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,uid_t uid,const audio_config_t * config,audio_output_flags_t * flags,audio_port_handle_t * selectedDeviceId,audio_port_handle_t * portId,std::vector<audio_io_handle_t> * secondaryOutputs)1048 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1049 audio_io_handle_t *output,
1050 audio_session_t session,
1051 audio_stream_type_t *stream,
1052 uid_t uid,
1053 const audio_config_t *config,
1054 audio_output_flags_t *flags,
1055 audio_port_handle_t *selectedDeviceId,
1056 audio_port_handle_t *portId,
1057 std::vector<audio_io_handle_t> *secondaryOutputs)
1058 {
1059 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1060 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1061 return INVALID_OPERATION;
1062 }
1063 const audio_port_handle_t requestedPortId = *selectedDeviceId;
1064 audio_attributes_t resultAttr;
1065 bool isRequestedDeviceForExclusiveUse = false;
1066 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputDescs;
1067 const sp<DeviceDescriptor> requestedDevice =
1068 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1069
1070 // Prevent from storing invalid requested device id in clients
1071 const audio_port_handle_t sanitizedRequestedPortId =
1072 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1073 *selectedDeviceId = sanitizedRequestedPortId;
1074
1075 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1076 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
1077 &secondaryOutputDescs);
1078 if (status != NO_ERROR) {
1079 return status;
1080 }
1081 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1082 for (auto& secondaryDesc : secondaryOutputDescs) {
1083 secondaryOutputs->push_back(secondaryDesc->mIoHandle);
1084 weakSecondaryOutputDescs.push_back(secondaryDesc);
1085 }
1086
1087 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1088 .format = config->format,
1089 .channel_mask = config->channel_mask };
1090 *portId = AudioPort::getNextUniqueId();
1091
1092 sp<TrackClientDescriptor> clientDesc =
1093 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
1094 sanitizedRequestedPortId, *stream,
1095 mEngine->getProductStrategyForAttributes(resultAttr),
1096 toVolumeSource(resultAttr),
1097 *flags, isRequestedDeviceForExclusiveUse,
1098 std::move(weakSecondaryOutputDescs));
1099 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
1100 outputDesc->addClient(clientDesc);
1101
1102 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1103 *output, requestedPortId, *selectedDeviceId, *portId);
1104
1105 return NO_ERROR;
1106 }
1107
getOutputForDevices(const DeviceVector & devices,audio_session_t session,audio_stream_type_t stream,const audio_config_t * config,audio_output_flags_t * flags,bool forceMutingHaptic)1108 audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1109 const DeviceVector &devices,
1110 audio_session_t session,
1111 audio_stream_type_t stream,
1112 const audio_config_t *config,
1113 audio_output_flags_t *flags,
1114 bool forceMutingHaptic)
1115 {
1116 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
1117 status_t status;
1118
1119 // Discard haptic channel mask when forcing muting haptic channels.
1120 audio_channel_mask_t channelMask = forceMutingHaptic
1121 ? (config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL) : config->channel_mask;
1122
1123 // open a direct output if required by specified parameters
1124 //force direct flag if offload flag is set: offloading implies a direct output stream
1125 // and all common behaviors are driven by checking only the direct flag
1126 // this should normally be set appropriately in the policy configuration file
1127 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1128 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1129 }
1130 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1131 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1132 }
1133 // only allow deep buffering for music stream type
1134 if (stream != AUDIO_STREAM_MUSIC) {
1135 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1136 } else if (/* stream == AUDIO_STREAM_MUSIC && */
1137 *flags == AUDIO_OUTPUT_FLAG_NONE &&
1138 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1139 // use DEEP_BUFFER as default output for music stream type
1140 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1141 }
1142 if (stream == AUDIO_STREAM_TTS) {
1143 *flags = AUDIO_OUTPUT_FLAG_TTS;
1144 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
1145 audio_is_linear_pcm(config->format) &&
1146 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
1147 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
1148 AUDIO_OUTPUT_FLAG_DIRECT);
1149 ALOGV("Set VoIP and Direct output flags for PCM format");
1150 }
1151
1152
1153 sp<IOProfile> profile;
1154
1155 // skip direct output selection if the request can obviously be attached to a mixed output
1156 // and not explicitly requested
1157 if (((*flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1158 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1159 audio_channel_count_from_out_mask(channelMask) <= 2) {
1160 goto non_direct_output;
1161 }
1162
1163 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1164 // This prevents creating an offloaded track and tearing it down immediately after start
1165 // when audioflinger detects there is an active non offloadable effect.
1166 // FIXME: We should check the audio session here but we do not have it in this context.
1167 // This may prevent offloading in rare situations where effects are left active by apps
1168 // in the background.
1169
1170 if (((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1171 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1172 profile = getProfileForOutput(devices,
1173 config->sample_rate,
1174 config->format,
1175 channelMask,
1176 (audio_output_flags_t)*flags,
1177 true /* directOnly */);
1178 }
1179
1180 if (profile != 0) {
1181 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1182 for (size_t i = 0; i < mOutputs.size(); i++) {
1183 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1184 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1185 // reuse direct output if currently open by the same client
1186 // and configured with same parameters
1187 if ((config->sample_rate == desc->mSamplingRate) &&
1188 (config->format == desc->mFormat) &&
1189 (channelMask == desc->mChannelMask) &&
1190 (session == desc->mDirectClientSession)) {
1191 desc->mDirectOpenCount++;
1192 ALOGI("%s reusing direct output %d for session %d", __func__,
1193 mOutputs.keyAt(i), session);
1194 return mOutputs.keyAt(i);
1195 }
1196 }
1197 }
1198
1199 if (!profile->canOpenNewIo()) {
1200 goto non_direct_output;
1201 }
1202
1203 sp<SwAudioOutputDescriptor> outputDesc =
1204 new SwAudioOutputDescriptor(profile, mpClientInterface);
1205
1206 String8 address = getFirstDeviceAddress(devices);
1207
1208 // MSD patch may be using the only output stream that can service this request. Release
1209 // MSD patch to prioritize this request over any active output on MSD.
1210 AudioPatchCollection msdPatches = getMsdPatches();
1211 for (size_t i = 0; i < msdPatches.size(); i++) {
1212 const auto& patch = msdPatches[i];
1213 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1214 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1215 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
1216 (sink->ext.device.type & devices.types()) != AUDIO_DEVICE_NONE &&
1217 (address.isEmpty() || strncmp(sink->ext.device.address, address.string(),
1218 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
1219 releaseAudioPatch(patch->mHandle, mUidCached);
1220 break;
1221 }
1222 }
1223 }
1224
1225 status = outputDesc->open(config, devices, stream, *flags, &output);
1226
1227 // only accept an output with the requested parameters
1228 if (status != NO_ERROR ||
1229 (config->sample_rate != 0 && config->sample_rate != outputDesc->mSamplingRate) ||
1230 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->mFormat) ||
1231 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
1232 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1233 "format %d %d, channel mask %04x %04x", __func__, output, config->sample_rate,
1234 outputDesc->mSamplingRate, config->format, outputDesc->mFormat,
1235 channelMask, outputDesc->mChannelMask);
1236 if (output != AUDIO_IO_HANDLE_NONE) {
1237 outputDesc->close();
1238 }
1239 // fall back to mixer output if possible when the direct output could not be open
1240 if (audio_is_linear_pcm(config->format) &&
1241 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1242 goto non_direct_output;
1243 }
1244 return AUDIO_IO_HANDLE_NONE;
1245 }
1246 outputDesc->mDirectOpenCount = 1;
1247 outputDesc->mDirectClientSession = session;
1248
1249 addOutput(output, outputDesc);
1250 mPreviousOutputs = mOutputs;
1251 ALOGV("%s returns new direct output %d", __func__, output);
1252 mpClientInterface->onAudioPortListUpdate();
1253 return output;
1254 }
1255
1256 non_direct_output:
1257
1258 // A request for HW A/V sync cannot fallback to a mixed output because time
1259 // stamps are embedded in audio data
1260 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1261 return AUDIO_IO_HANDLE_NONE;
1262 }
1263
1264 // ignoring channel mask due to downmix capability in mixer
1265
1266 // open a non direct output
1267
1268 // for non direct outputs, only PCM is supported
1269 if (audio_is_linear_pcm(config->format)) {
1270 // get which output is suitable for the specified stream. The actual
1271 // routing change will happen when startOutput() will be called
1272 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
1273
1274 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1275 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1276 output = selectOutput(outputs, *flags, config->format, channelMask, config->sample_rate);
1277 }
1278 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
1279 "sampling rate %d, format %#x, channels %#x, flags %#x",
1280 stream, config->sample_rate, config->format, channelMask, *flags);
1281
1282 return output;
1283 }
1284
getMsdAudioInDevice() const1285 sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1286 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1287 mAvailableInputDevices);
1288 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1289 }
1290
getMsdAudioOutDevices() const1291 DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1292 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1293 mAvailableOutputDevices);
1294 }
1295
getMsdPatches() const1296 const AudioPatchCollection AudioPolicyManager::getMsdPatches() const {
1297 AudioPatchCollection msdPatches;
1298 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1299 if (msdModule != 0) {
1300 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1301 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1302 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1303 const struct audio_port_config *source = &patch->mPatch.sources[j];
1304 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1305 source->ext.device.hw_module == msdModule->getHandle()) {
1306 msdPatches.addAudioPatch(patch->mHandle, patch);
1307 }
1308 }
1309 }
1310 }
1311 return msdPatches;
1312 }
1313
getBestMsdAudioProfileFor(const sp<DeviceDescriptor> & outputDevice,bool hwAvSync,audio_port_config * sourceConfig,audio_port_config * sinkConfig) const1314 status_t AudioPolicyManager::getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
1315 bool hwAvSync, audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1316 {
1317 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1318 if (msdModule == nullptr) {
1319 ALOGE("%s() unable to get MSD module", __func__);
1320 return NO_INIT;
1321 }
1322 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(outputDevice, AUDIO_FORMAT_DEFAULT);
1323 if (deviceModule == nullptr) {
1324 ALOGE("%s() unable to get module for %s", __func__, outputDevice->toString().c_str());
1325 return NO_INIT;
1326 }
1327 const InputProfileCollection &inputProfiles = msdModule->getInputProfiles();
1328 if (inputProfiles.isEmpty()) {
1329 ALOGE("%s() no input profiles for MSD module", __func__);
1330 return NO_INIT;
1331 }
1332 const OutputProfileCollection &outputProfiles = deviceModule->getOutputProfiles();
1333 if (outputProfiles.isEmpty()) {
1334 ALOGE("%s() no output profiles for device %s", __func__, outputDevice->toString().c_str());
1335 return NO_INIT;
1336 }
1337 AudioProfileVector msdProfiles;
1338 // Each IOProfile represents a MixPort from audio_policy_configuration.xml
1339 for (const auto &inProfile : inputProfiles) {
1340 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0)) {
1341 msdProfiles.appendVector(inProfile->getAudioProfiles());
1342 }
1343 }
1344 AudioProfileVector deviceProfiles;
1345 for (const auto &outProfile : outputProfiles) {
1346 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0)) {
1347 deviceProfiles.appendVector(outProfile->getAudioProfiles());
1348 }
1349 }
1350 struct audio_config_base bestSinkConfig;
1351 status_t result = msdProfiles.findBestMatchingOutputConfig(deviceProfiles,
1352 compressedFormatsOrder, surroundChannelMasksOrder, true /*preferHigherSamplingRates*/,
1353 &bestSinkConfig);
1354 if (result != NO_ERROR) {
1355 ALOGD("%s() no matching profiles found for device: %s, hwAvSync: %d",
1356 __func__, outputDevice->toString().c_str(), hwAvSync);
1357 return result;
1358 }
1359 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1360 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1361 sinkConfig->format = bestSinkConfig.format;
1362 // For encoded streams force direct flag to prevent downstream mixing.
1363 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1364 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1365 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1366 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1367 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1368 sourceConfig->format = bestSinkConfig.format;
1369 // Copy input stream directly without any processing (e.g. resampling).
1370 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1371 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1372 if (hwAvSync) {
1373 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1374 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1375 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1376 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1377 }
1378 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1379 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1380 sinkConfig->config_mask |= config_mask;
1381 sourceConfig->config_mask |= config_mask;
1382 return NO_ERROR;
1383 }
1384
buildMsdPatch(const sp<DeviceDescriptor> & outputDevice) const1385 PatchBuilder AudioPolicyManager::buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const
1386 {
1387 PatchBuilder patchBuilder;
1388 patchBuilder.addSource(getMsdAudioInDevice()).addSink(outputDevice);
1389 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1390 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1391 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1392 // For now, we just forcefully try with HwAvSync first.
1393 status_t res = getBestMsdAudioProfileFor(outputDevice, true /*hwAvSync*/,
1394 &sourceConfig, &sinkConfig) == NO_ERROR ? NO_ERROR :
1395 getBestMsdAudioProfileFor(
1396 outputDevice, false /*hwAvSync*/, &sourceConfig, &sinkConfig);
1397 if (res == NO_ERROR) {
1398 // Found a matching profile for encoded audio. Re-create PatchBuilder with this config.
1399 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1400 }
1401 ALOGV("%s() no matching profile found. Fall through to default PCM patch"
1402 " supporting PCM format conversion.", __func__);
1403 return patchBuilder;
1404 }
1405
setMsdPatch(const sp<DeviceDescriptor> & outputDevice)1406 status_t AudioPolicyManager::setMsdPatch(const sp<DeviceDescriptor> &outputDevice) {
1407 sp<DeviceDescriptor> device = outputDevice;
1408 if (device == nullptr) {
1409 // Use media strategy for unspecified output device. This should only
1410 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1411 // therefore invalidate explicit routing requests.
1412 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
1413 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
1414 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no outpudevice to set Msd Patch");
1415 device = devices.itemAt(0);
1416 }
1417 ALOGV("%s() for device %s", __func__, device->toString().c_str());
1418 PatchBuilder patchBuilder = buildMsdPatch(device);
1419 const struct audio_patch* patch = patchBuilder.patch();
1420 const AudioPatchCollection msdPatches = getMsdPatches();
1421 if (!msdPatches.isEmpty()) {
1422 LOG_ALWAYS_FATAL_IF(msdPatches.size() > 1,
1423 "The current MSD prototype only supports one output patch");
1424 sp<AudioPatch> currentPatch = msdPatches.valueAt(0);
1425 if (audio_patches_are_equal(¤tPatch->mPatch, patch)) {
1426 return NO_ERROR;
1427 }
1428 releaseAudioPatch(currentPatch->mHandle, mUidCached);
1429 }
1430 status_t status = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1431 patch, 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1432 ALOGE_IF(status != NO_ERROR, "%s() error %d creating MSD audio patch", __func__, status);
1433 ALOGI_IF(status == NO_ERROR, "%s() Patch created from MSD_IN to "
1434 "device:%s (format:%#x channels:%#x samplerate:%d)", __func__,
1435 device->toString().c_str(), patch->sources[0].format,
1436 patch->sources[0].channel_mask, patch->sources[0].sample_rate);
1437 return status;
1438 }
1439
selectOutput(const SortedVector<audio_io_handle_t> & outputs,audio_output_flags_t flags,audio_format_t format,audio_channel_mask_t channelMask,uint32_t samplingRate)1440 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
1441 audio_output_flags_t flags,
1442 audio_format_t format,
1443 audio_channel_mask_t channelMask,
1444 uint32_t samplingRate)
1445 {
1446 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1447 "%s called with format %#x", __func__, format);
1448
1449 // Flags disqualifying an output: the match must happen before calling selectOutput()
1450 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1451 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1452
1453 // Flags expressing a functional request: must be honored in priority over
1454 // other criteria
1455 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1456 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
1457 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM);
1458 // Flags expressing a performance request: have lower priority than serving
1459 // requested sampling rate or channel mask
1460 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1461 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1462 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1463
1464 const audio_output_flags_t functionalFlags =
1465 (audio_output_flags_t)(flags & kFunctionalFlags);
1466 const audio_output_flags_t performanceFlags =
1467 (audio_output_flags_t)(flags & kPerformanceFlags);
1468
1469 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1470
1471 // select one output among several that provide a path to a particular device or set of
1472 // devices (the list was previously build by getOutputsForDevices()).
1473 // The priority is as follows:
1474 // 1: the output supporting haptic playback when requesting haptic playback
1475 // 2: the output with the highest number of requested functional flags
1476 // 3: the output supporting the exact channel mask
1477 // 4: the output with a higher channel count than requested
1478 // 5: the output with a higher sampling rate than requested
1479 // 6: the output with the highest number of requested performance flags
1480 // 7: the output with the bit depth the closest to the requested one
1481 // 8: the primary output
1482 // 9: the first output in the list
1483
1484 // matching criteria values in priority order for best matching output so far
1485 std::vector<uint32_t> bestMatchCriteria(8, 0);
1486
1487 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1488 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1489 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
1490
1491 for (audio_io_handle_t output : outputs) {
1492 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
1493 // matching criteria values in priority order for current output
1494 std::vector<uint32_t> currentMatchCriteria(8, 0);
1495
1496 if (outputDesc->isDuplicated()) {
1497 continue;
1498 }
1499 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1500 continue;
1501 }
1502
1503 // If haptic channel is specified, use the haptic output if present.
1504 // When using haptic output, same audio format and sample rate are required.
1505 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
1506 outputDesc->mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
1507 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1508 continue;
1509 }
1510 if (outputHapticChannelCount >= hapticChannelCount
1511 && format == outputDesc->mFormat
1512 && samplingRate == outputDesc->mSamplingRate) {
1513 currentMatchCriteria[0] = outputHapticChannelCount;
1514 }
1515
1516 // functional flags match
1517 currentMatchCriteria[1] = popcount(outputDesc->mFlags & functionalFlags);
1518
1519 // channel mask and channel count match
1520 uint32_t outputChannelCount = audio_channel_count_from_out_mask(outputDesc->mChannelMask);
1521 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1522 channelCount <= outputChannelCount) {
1523 if ((audio_channel_mask_get_representation(channelMask) ==
1524 audio_channel_mask_get_representation(outputDesc->mChannelMask)) &&
1525 ((channelMask & outputDesc->mChannelMask) == channelMask)) {
1526 currentMatchCriteria[2] = outputChannelCount;
1527 }
1528 currentMatchCriteria[3] = outputChannelCount;
1529 }
1530
1531 // sampling rate match
1532 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
1533 samplingRate <= outputDesc->mSamplingRate) {
1534 currentMatchCriteria[4] = outputDesc->mSamplingRate;
1535 }
1536
1537 // performance flags match
1538 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1539
1540 // format match
1541 if (format != AUDIO_FORMAT_INVALID) {
1542 currentMatchCriteria[6] =
1543 AudioPort::kFormatDistanceMax -
1544 AudioPort::formatDistance(format, outputDesc->mFormat);
1545 }
1546
1547 // primary output match
1548 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1549
1550 // compare match criteria by priority then value
1551 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1552 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1553 bestMatchCriteria = currentMatchCriteria;
1554 bestOutput = output;
1555
1556 std::stringstream result;
1557 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1558 std::ostream_iterator<int>(result, " "));
1559 ALOGV("%s new bestOutput %d criteria %s",
1560 __func__, bestOutput, result.str().c_str());
1561 }
1562 }
1563
1564 return bestOutput;
1565 }
1566
startOutput(audio_port_handle_t portId)1567 status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
1568 {
1569 ALOGV("%s portId %d", __FUNCTION__, portId);
1570
1571 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1572 if (outputDesc == 0) {
1573 ALOGW("startOutput() no output for client %d", portId);
1574 return BAD_VALUE;
1575 }
1576 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
1577
1578 ALOGV("startOutput() output %d, stream %d, session %d",
1579 outputDesc->mIoHandle, client->stream(), client->session());
1580
1581 status_t status = outputDesc->start();
1582 if (status != NO_ERROR) {
1583 return status;
1584 }
1585
1586 uint32_t delayMs;
1587 status = startSource(outputDesc, client, &delayMs);
1588
1589 if (status != NO_ERROR) {
1590 outputDesc->stop();
1591 return status;
1592 }
1593 if (delayMs != 0) {
1594 usleep(delayMs * 1000);
1595 }
1596
1597 return status;
1598 }
1599
startSource(const sp<SwAudioOutputDescriptor> & outputDesc,const sp<TrackClientDescriptor> & client,uint32_t * delayMs)1600 status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1601 const sp<TrackClientDescriptor>& client,
1602 uint32_t *delayMs)
1603 {
1604 // cannot start playback of STREAM_TTS if any other output is being used
1605 uint32_t beaconMuteLatency = 0;
1606
1607 *delayMs = 0;
1608 audio_stream_type_t stream = client->stream();
1609 auto clientVolSrc = client->volumeSource();
1610 auto clientStrategy = client->strategy();
1611 auto clientAttr = client->attributes();
1612 if (stream == AUDIO_STREAM_TTS) {
1613 ALOGV("\t found BEACON stream");
1614 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
1615 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
1616 return INVALID_OPERATION;
1617 } else {
1618 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1619 }
1620 } else {
1621 // some playback other than beacon starts
1622 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1623 }
1624
1625 // force device change if the output is inactive and no audio patch is already present.
1626 // check active before incrementing usage count
1627 bool force = !outputDesc->isActive() &&
1628 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
1629
1630 DeviceVector devices;
1631 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
1632 const char *address = NULL;
1633 if (policyMix != NULL) {
1634 audio_devices_t newDeviceType;
1635 address = policyMix->mDeviceAddress.string();
1636 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
1637 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1638 } else {
1639 newDeviceType = policyMix->mDeviceType;
1640 }
1641 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1642 AUDIO_FORMAT_DEFAULT);
1643 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1644 devices.add(device);
1645 }
1646
1647 // requiresMuteCheck is false when we can bypass mute strategy.
1648 // It covers a common case when there is no materially active audio
1649 // and muting would result in unnecessary delay and dropped audio.
1650 const uint32_t outputLatencyMs = outputDesc->latency();
1651 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1652
1653 // increment usage count for this stream on the requested output:
1654 // NOTE that the usage count is the same for duplicated output and hardware output which is
1655 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1656 outputDesc->setClientActive(client, true);
1657
1658 if (client->hasPreferredDevice(true)) {
1659 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1660 client->isPreferredDeviceForExclusiveUse()) {
1661 // Preferred device may be exclusive, use only if no other active clients on this output
1662 devices = DeviceVector(
1663 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1664 } else {
1665 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1666 }
1667 if (devices != outputDesc->devices()) {
1668 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
1669 }
1670 }
1671
1672 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
1673 selectOutputForMusicEffects();
1674 }
1675
1676 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
1677 // starting an output being rerouted?
1678 if (devices.isEmpty()) {
1679 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1680 }
1681 bool shouldWait =
1682 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1683 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1684 (beaconMuteLatency > 0));
1685 uint32_t waitMs = beaconMuteLatency;
1686 for (size_t i = 0; i < mOutputs.size(); i++) {
1687 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1688 if (desc != outputDesc) {
1689 // An output has a shared device if
1690 // - managed by the same hw module
1691 // - supports the currently selected device
1692 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
1693 && (!desc->filterSupportedDevices(devices).isEmpty());
1694
1695 // force a device change if any other output is:
1696 // - managed by the same hw module
1697 // - supports currently selected device
1698 // - has a current device selection that differs from selected device.
1699 // - has an active audio patch
1700 // In this case, the audio HAL must receive the new device selection so that it can
1701 // change the device currently selected by the other output.
1702 if (sharedDevice &&
1703 desc->devices() != devices &&
1704 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
1705 force = true;
1706 }
1707 // wait for audio on other active outputs to be presented when starting
1708 // a notification so that audio focus effect can propagate, or that a mute/unmute
1709 // event occurred for beacon
1710 const uint32_t latencyMs = desc->latency();
1711 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
1712
1713 if (shouldWait && isActive && (waitMs < latencyMs)) {
1714 waitMs = latencyMs;
1715 }
1716
1717 // Require mute check if another output is on a shared device
1718 // and currently active to have proper drain and avoid pops.
1719 // Note restoring AudioTracks onto this output needs to invoke
1720 // a volume ramp if there is no mute.
1721 requiresMuteCheck |= sharedDevice && isActive;
1722 }
1723 }
1724
1725 const uint32_t muteWaitMs =
1726 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
1727
1728 // apply volume rules for current stream and device if necessary
1729 auto &curves = getVolumeCurves(client->attributes());
1730 checkAndSetVolume(curves, client->volumeSource(),
1731 curves.getVolumeIndex(outputDesc->devices().types()),
1732 outputDesc,
1733 outputDesc->devices().types());
1734
1735 // update the outputs if starting an output with a stream that can affect notification
1736 // routing
1737 handleNotificationRoutingForStream(stream);
1738
1739 // force reevaluating accessibility routing when ringtone or alarm starts
1740 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
1741 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1742 }
1743
1744 if (waitMs > muteWaitMs) {
1745 *delayMs = waitMs - muteWaitMs;
1746 }
1747
1748 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
1749 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
1750 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
1751 // change occurs after the MixerThread starts and causes a stream volume
1752 // glitch.
1753 //
1754 // We do not introduce additional delay here.
1755 }
1756
1757 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1758 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1759 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
1760 }
1761
1762 // Automatically enable the remote submix input when output is started on a re routing mix
1763 // of type MIX_TYPE_RECORDERS
1764 if (audio_is_remote_submix_device(devices.types()) && policyMix != NULL &&
1765 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1766 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1767 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1768 address,
1769 "remote-submix",
1770 AUDIO_FORMAT_DEFAULT);
1771 }
1772
1773 return NO_ERROR;
1774 }
1775
stopOutput(audio_port_handle_t portId)1776 status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
1777 {
1778 ALOGV("%s portId %d", __FUNCTION__, portId);
1779
1780 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1781 if (outputDesc == 0) {
1782 ALOGW("stopOutput() no output for client %d", portId);
1783 return BAD_VALUE;
1784 }
1785 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
1786
1787 ALOGV("stopOutput() output %d, stream %d, session %d",
1788 outputDesc->mIoHandle, client->stream(), client->session());
1789
1790 status_t status = stopSource(outputDesc, client);
1791
1792 if (status == NO_ERROR ) {
1793 outputDesc->stop();
1794 }
1795 return status;
1796 }
1797
stopSource(const sp<SwAudioOutputDescriptor> & outputDesc,const sp<TrackClientDescriptor> & client)1798 status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1799 const sp<TrackClientDescriptor>& client)
1800 {
1801 // always handle stream stop, check which stream type is stopping
1802 audio_stream_type_t stream = client->stream();
1803 auto clientVolSrc = client->volumeSource();
1804
1805 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1806
1807 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
1808 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
1809 // Automatically disable the remote submix input when output is stopped on a
1810 // re routing mix of type MIX_TYPE_RECORDERS
1811 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
1812 if (audio_is_remote_submix_device(outputDesc->devices().types()) &&
1813 policyMix != NULL &&
1814 policyMix->mMixType == MIX_TYPE_RECORDERS) {
1815 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
1816 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1817 policyMix->mDeviceAddress,
1818 "remote-submix", AUDIO_FORMAT_DEFAULT);
1819 }
1820 }
1821 bool forceDeviceUpdate = false;
1822 if (client->hasPreferredDevice(true)) {
1823 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
1824 forceDeviceUpdate = true;
1825 }
1826
1827 // decrement usage count of this stream on the output
1828 outputDesc->setClientActive(client, false);
1829
1830 // store time at which the stream was stopped - see isStreamActive()
1831 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
1832 outputDesc->setStopTime(client, systemTime());
1833 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1834 // delay the device switch by twice the latency because stopOutput() is executed when
1835 // the track stop() command is received and at that time the audio track buffer can
1836 // still contain data that needs to be drained. The latency only covers the audio HAL
1837 // and kernel buffers. Also the latency does not always include additional delay in the
1838 // audio path (audio DSP, CODEC ...)
1839 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
1840
1841 // force restoring the device selection on other active outputs if it differs from the
1842 // one being selected for this output
1843 uint32_t delayMs = outputDesc->latency()*2;
1844 for (size_t i = 0; i < mOutputs.size(); i++) {
1845 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1846 if (desc != outputDesc &&
1847 desc->isActive() &&
1848 outputDesc->sharesHwModuleWith(desc) &&
1849 (newDevices != desc->devices())) {
1850 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
1851 bool force = desc->devices() != newDevices2;
1852
1853 setOutputDevices(desc, newDevices2, force, delayMs);
1854
1855 // re-apply device specific volume if not done by setOutputDevice()
1856 if (!force) {
1857 applyStreamVolumes(desc, newDevices2.types(), delayMs);
1858 }
1859 }
1860 }
1861 // update the outputs if stopping one with a stream that can affect notification routing
1862 handleNotificationRoutingForStream(stream);
1863 }
1864
1865 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
1866 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1867 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
1868 }
1869
1870 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
1871 selectOutputForMusicEffects();
1872 }
1873 return NO_ERROR;
1874 } else {
1875 ALOGW("stopOutput() refcount is already 0");
1876 return INVALID_OPERATION;
1877 }
1878 }
1879
releaseOutput(audio_port_handle_t portId)1880 void AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
1881 {
1882 ALOGV("%s portId %d", __FUNCTION__, portId);
1883
1884 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1885 if (outputDesc == 0) {
1886 // If an output descriptor is closed due to a device routing change,
1887 // then there are race conditions with releaseOutput from tracks
1888 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
1889 // destroyed shortly thereafter.
1890 //
1891 // Here we just log a warning, instead of a fatal error.
1892 ALOGW("releaseOutput() no output for client %d", portId);
1893 return;
1894 }
1895
1896 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
1897
1898 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1899 if (outputDesc->mDirectOpenCount <= 0) {
1900 ALOGW("releaseOutput() invalid open count %d for output %d",
1901 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
1902 return;
1903 }
1904 if (--outputDesc->mDirectOpenCount == 0) {
1905 closeOutput(outputDesc->mIoHandle);
1906 mpClientInterface->onAudioPortListUpdate();
1907 }
1908 }
1909 // stopOutput() needs to be successfully called before releaseOutput()
1910 // otherwise there may be inaccurate stream reference counts.
1911 // This is checked in outputDesc->removeClient below.
1912 outputDesc->removeClient(portId);
1913 }
1914
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_unique_id_t riid,audio_session_t session,uid_t uid,const audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,input_type_t * inputType,audio_port_handle_t * portId)1915 status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1916 audio_io_handle_t *input,
1917 audio_unique_id_t riid,
1918 audio_session_t session,
1919 uid_t uid,
1920 const audio_config_base_t *config,
1921 audio_input_flags_t flags,
1922 audio_port_handle_t *selectedDeviceId,
1923 input_type_t *inputType,
1924 audio_port_handle_t *portId)
1925 {
1926 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
1927 "flags %#x attributes=%s", __func__, attr->source, config->sample_rate,
1928 config->format, config->channel_mask, session, flags, toString(*attr).c_str());
1929
1930 status_t status = NO_ERROR;
1931 audio_source_t halInputSource;
1932 audio_attributes_t attributes = *attr;
1933 sp<AudioPolicyMix> policyMix;
1934 sp<DeviceDescriptor> device;
1935 sp<AudioInputDescriptor> inputDesc;
1936 sp<RecordClientDescriptor> clientDesc;
1937 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
1938 bool isSoundTrigger;
1939
1940 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1941 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1942 return INVALID_OPERATION;
1943 }
1944
1945 if (attr->source == AUDIO_SOURCE_DEFAULT) {
1946 attributes.source = AUDIO_SOURCE_MIC;
1947 }
1948
1949 // Explicit routing?
1950 sp<DeviceDescriptor> explicitRoutingDevice =
1951 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
1952
1953 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
1954 // possible
1955 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
1956 *input != AUDIO_IO_HANDLE_NONE) {
1957 ssize_t index = mInputs.indexOfKey(*input);
1958 if (index < 0) {
1959 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
1960 status = BAD_VALUE;
1961 goto error;
1962 }
1963 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1964 RecordClientVector clients = inputDesc->getClientsForSession(session);
1965 if (clients.size() == 0) {
1966 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
1967 status = BAD_VALUE;
1968 goto error;
1969 }
1970 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
1971 // The second call is for the first active client and sets the UID. Any further call
1972 // corresponds to a new client and is only permitted from the same UID.
1973 // If the first UID is silenced, allow a new UID connection and replace with new UID
1974 if (clients.size() > 1) {
1975 for (const auto& client : clients) {
1976 // The client map is ordered by key values (portId) and portIds are allocated
1977 // incrementaly. So the first client in this list is the one opened by audio flinger
1978 // when the mmap stream is created and should be ignored as it does not correspond
1979 // to an actual client
1980 if (client == *clients.cbegin()) {
1981 continue;
1982 }
1983 if (uid != client->uid() && !client->isSilenced()) {
1984 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
1985 uid, client->portId(), client->uid());
1986 status = INVALID_OPERATION;
1987 goto error;
1988 }
1989 }
1990 }
1991 *inputType = API_INPUT_LEGACY;
1992 device = inputDesc->getDevice();
1993
1994 ALOGI("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
1995 goto exit;
1996 }
1997
1998 *input = AUDIO_IO_HANDLE_NONE;
1999 *inputType = API_INPUT_INVALID;
2000
2001 halInputSource = attributes.source;
2002
2003 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2004 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2005 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
2006 if (status != NO_ERROR) {
2007 ALOGW("%s could not find input mix for attr %s",
2008 __func__, toString(attributes).c_str());
2009 goto error;
2010 }
2011 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2012 String8(attr->tags + strlen("addr=")),
2013 AUDIO_FORMAT_DEFAULT);
2014 if (device == nullptr) {
2015 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
2016 __func__, attributes.source, attributes.tags);
2017 status = BAD_VALUE;
2018 goto error;
2019 }
2020
2021 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2022 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2023 } else {
2024 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2025 }
2026 } else {
2027 if (explicitRoutingDevice != nullptr) {
2028 device = explicitRoutingDevice;
2029 } else {
2030 // Prevent from storing invalid requested device id in clients
2031 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
2032 device = mEngine->getInputDeviceForAttributes(attributes, &policyMix);
2033 }
2034 if (device == nullptr) {
2035 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
2036 status = BAD_VALUE;
2037 goto error;
2038 }
2039 if (policyMix) {
2040 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2041 // there is an external policy, but this input is attached to a mix of recorders,
2042 // meaning it receives audio injected into the framework, so the recorder doesn't
2043 // know about it and is therefore considered "legacy"
2044 *inputType = API_INPUT_LEGACY;
2045 } else if (audio_is_remote_submix_device(device->type())) {
2046 *inputType = API_INPUT_MIX_CAPTURE;
2047 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
2048 *inputType = API_INPUT_TELEPHONY_RX;
2049 } else {
2050 *inputType = API_INPUT_LEGACY;
2051 }
2052
2053 }
2054
2055 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
2056 if (*input == AUDIO_IO_HANDLE_NONE) {
2057 status = INVALID_OPERATION;
2058 goto error;
2059 }
2060
2061 exit:
2062
2063 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2064 device->getId() : AUDIO_PORT_HANDLE_NONE;
2065
2066 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
2067 mSoundTriggerSessions.indexOfKey(session) >= 0;
2068 *portId = AudioPort::getNextUniqueId();
2069
2070 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
2071 requestedDeviceId, attributes.source, flags,
2072 isSoundTrigger);
2073 inputDesc = mInputs.valueFor(*input);
2074 inputDesc->addClient(clientDesc);
2075
2076 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2077 *input, *inputType, *selectedDeviceId, *portId);
2078
2079 return NO_ERROR;
2080
2081 error:
2082 return status;
2083 }
2084
2085
getInputForDevice(const sp<DeviceDescriptor> & device,audio_session_t session,const audio_attributes_t & attributes,const audio_config_base_t * config,audio_input_flags_t flags,const sp<AudioPolicyMix> & policyMix)2086 audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
2087 audio_session_t session,
2088 const audio_attributes_t &attributes,
2089 const audio_config_base_t *config,
2090 audio_input_flags_t flags,
2091 const sp<AudioPolicyMix> &policyMix)
2092 {
2093 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2094 audio_source_t halInputSource = attributes.source;
2095 bool isSoundTrigger = false;
2096
2097 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
2098 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2099 if (index >= 0) {
2100 input = mSoundTriggerSessions.valueFor(session);
2101 isSoundTrigger = true;
2102 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2103 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2104 } else {
2105 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
2106 }
2107 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
2108 audio_is_linear_pcm(config->format)) {
2109 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
2110 }
2111
2112 // find a compatible input profile (not necessarily identical in parameters)
2113 sp<IOProfile> profile;
2114 // sampling rate and flags may be updated by getInputProfile
2115 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2116 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
2117 audio_format_t profileFormat;
2118 audio_channel_mask_t profileChannelMask = config->channel_mask;
2119 audio_input_flags_t profileFlags = flags;
2120 for (;;) {
2121 profileFormat = config->format; // reset each time through loop, in case it is updated
2122 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
2123 profileFlags);
2124 if (profile != 0) {
2125 break; // success
2126 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2127 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
2128 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE) {
2129 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2130 } else { // fail
2131 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
2132 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
2133 config->sample_rate, config->format, config->channel_mask, flags);
2134 return input;
2135 }
2136 }
2137 // Pick input sampling rate if not specified by client
2138 uint32_t samplingRate = config->sample_rate;
2139 if (samplingRate == 0) {
2140 samplingRate = profileSamplingRate;
2141 }
2142
2143 if (profile->getModuleHandle() == 0) {
2144 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
2145 return input;
2146 }
2147
2148 if (!profile->canOpenNewIo()) {
2149 for (size_t i = 0; i < mInputs.size(); ) {
2150 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2151 if (desc->mProfile != profile) {
2152 i++;
2153 continue;
2154 }
2155 // if sound trigger, reuse input if used by other sound trigger on same session
2156 // else
2157 // reuse input if active client app is not in IDLE state
2158 //
2159 RecordClientVector clients = desc->clientsList();
2160 bool doClose = false;
2161 for (const auto& client : clients) {
2162 if (isSoundTrigger != client->isSoundTrigger()) {
2163 continue;
2164 }
2165 if (client->isSoundTrigger()) {
2166 if (session == client->session()) {
2167 return desc->mIoHandle;
2168 }
2169 continue;
2170 }
2171 if (client->active() && client->appState() != APP_STATE_IDLE) {
2172 return desc->mIoHandle;
2173 }
2174 doClose = true;
2175 }
2176 if (doClose) {
2177 closeInput(desc->mIoHandle);
2178 } else {
2179 i++;
2180 }
2181 }
2182 }
2183
2184 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
2185
2186 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2187 lConfig.sample_rate = profileSamplingRate;
2188 lConfig.channel_mask = profileChannelMask;
2189 lConfig.format = profileFormat;
2190
2191 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
2192
2193 // only accept input with the exact requested set of parameters
2194 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
2195 (profileSamplingRate != lConfig.sample_rate) ||
2196 !audio_formats_match(profileFormat, lConfig.format) ||
2197 (profileChannelMask != lConfig.channel_mask)) {
2198 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
2199 ", format %#x, channel mask %#x",
2200 profileSamplingRate, profileFormat, profileChannelMask);
2201 if (input != AUDIO_IO_HANDLE_NONE) {
2202 inputDesc->close();
2203 }
2204 return AUDIO_IO_HANDLE_NONE;
2205 }
2206
2207 inputDesc->mPolicyMix = policyMix;
2208
2209 addInput(input, inputDesc);
2210 mpClientInterface->onAudioPortListUpdate();
2211
2212 return input;
2213 }
2214
startInput(audio_port_handle_t portId)2215 status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
2216 {
2217 ALOGV("%s portId %d", __FUNCTION__, portId);
2218
2219 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2220 if (inputDesc == 0) {
2221 ALOGW("%s no input for client %d", __FUNCTION__, portId);
2222 return BAD_VALUE;
2223 }
2224 audio_io_handle_t input = inputDesc->mIoHandle;
2225 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
2226 if (client->active()) {
2227 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2228 return INVALID_OPERATION;
2229 }
2230
2231 audio_session_t session = client->session();
2232
2233 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
2234
2235 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
2236
2237 status_t status = inputDesc->start();
2238 if (status != NO_ERROR) {
2239 return status;
2240 }
2241
2242 // increment activity count before calling getNewInputDevice() below as only active sessions
2243 // are considered for device selection
2244 inputDesc->setClientActive(client, true);
2245
2246 // indicate active capture to sound trigger service if starting capture from a mic on
2247 // primary HW module
2248 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
2249 setInputDevice(input, device, true /* force */);
2250
2251 if (inputDesc->activeCount() == 1) {
2252 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
2253 // if input maps to a dynamic policy with an activity listener, notify of state change
2254 if ((policyMix != NULL)
2255 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2256 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
2257 MIX_STATE_MIXING);
2258 }
2259
2260 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2261 if (primaryInputDevices.contains(device) &&
2262 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
2263 SoundTrigger::setCaptureState(true);
2264 }
2265
2266 // automatically enable the remote submix output when input is started if not
2267 // used by a policy mix of type MIX_TYPE_RECORDERS
2268 // For remote submix (a virtual device), we open only one input per capture request.
2269 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
2270 String8 address = String8("");
2271 if (policyMix == NULL) {
2272 address = String8("0");
2273 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2274 address = policyMix->mDeviceAddress;
2275 }
2276 if (address != "") {
2277 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2278 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2279 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
2280 }
2281 }
2282 }
2283
2284 ALOGV("%s input %d source = %d exit", __FUNCTION__, input, client->source());
2285
2286 return NO_ERROR;
2287 }
2288
stopInput(audio_port_handle_t portId)2289 status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
2290 {
2291 ALOGV("%s portId %d", __FUNCTION__, portId);
2292
2293 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2294 if (inputDesc == 0) {
2295 ALOGW("%s no input for client %d", __FUNCTION__, portId);
2296 return BAD_VALUE;
2297 }
2298 audio_io_handle_t input = inputDesc->mIoHandle;
2299 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
2300 if (!client->active()) {
2301 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
2302 return INVALID_OPERATION;
2303 }
2304
2305 inputDesc->setClientActive(client, false);
2306
2307 inputDesc->stop();
2308 if (inputDesc->isActive()) {
2309 setInputDevice(input, getNewInputDevice(inputDesc), false /* force */);
2310 } else {
2311 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
2312 // if input maps to a dynamic policy with an activity listener, notify of state change
2313 if ((policyMix != NULL)
2314 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2315 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
2316 MIX_STATE_IDLE);
2317 }
2318
2319 // automatically disable the remote submix output when input is stopped if not
2320 // used by a policy mix of type MIX_TYPE_RECORDERS
2321 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
2322 String8 address = String8("");
2323 if (policyMix == NULL) {
2324 address = String8("0");
2325 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2326 address = policyMix->mDeviceAddress;
2327 }
2328 if (address != "") {
2329 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2330 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2331 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
2332 }
2333 }
2334 resetInputDevice(input);
2335
2336 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2337 // primary HW module
2338 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2339 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
2340 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
2341 SoundTrigger::setCaptureState(false);
2342 }
2343 inputDesc->clearPreemptedSessions();
2344 }
2345 return NO_ERROR;
2346 }
2347
releaseInput(audio_port_handle_t portId)2348 void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
2349 {
2350 ALOGV("%s portId %d", __FUNCTION__, portId);
2351
2352 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2353 if (inputDesc == 0) {
2354 ALOGW("%s no input for client %d", __FUNCTION__, portId);
2355 return;
2356 }
2357 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
2358 audio_io_handle_t input = inputDesc->mIoHandle;
2359
2360 ALOGV("%s %d", __FUNCTION__, input);
2361
2362 inputDesc->removeClient(portId);
2363
2364 if (inputDesc->getClientCount() > 0) {
2365 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
2366 return;
2367 }
2368
2369 closeInput(input);
2370 mpClientInterface->onAudioPortListUpdate();
2371 ALOGV("%s exit", __FUNCTION__);
2372 }
2373
closeActiveClients(const sp<AudioInputDescriptor> & input)2374 void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
2375 {
2376 RecordClientVector clients = input->clientsList(true);
2377
2378 for (const auto& client : clients) {
2379 closeClient(client->portId());
2380 }
2381 }
2382
closeClient(audio_port_handle_t portId)2383 void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2384 {
2385 stopInput(portId);
2386 releaseInput(portId);
2387 }
2388
checkCloseInputs()2389 void AudioPolicyManager::checkCloseInputs() {
2390 // After connecting or disconnecting an input device, close input if:
2391 // - it has no client (was just opened to check profile) OR
2392 // - none of its supported devices are connected anymore OR
2393 // - one of its clients cannot be routed to one of its supported
2394 // devices anymore. Otherwise update device selection
2395 std::vector<audio_io_handle_t> inputsToClose;
2396 for (size_t i = 0; i < mInputs.size(); i++) {
2397 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2398 if (input->clientsList().size() == 0
2399 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())
2400 || (input->getAudioPort()->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ) != 0) {
2401 inputsToClose.push_back(mInputs.keyAt(i));
2402 } else {
2403 bool close = false;
2404 for (const auto& client : input->clientsList()) {
2405 sp<DeviceDescriptor> device =
2406 mEngine->getInputDeviceForAttributes(client->attributes());
2407 if (!input->supportedDevices().contains(device)) {
2408 close = true;
2409 break;
2410 }
2411 }
2412 if (close) {
2413 inputsToClose.push_back(mInputs.keyAt(i));
2414 } else {
2415 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2416 }
2417 }
2418 }
2419
2420 for (const audio_io_handle_t handle : inputsToClose) {
2421 ALOGV("%s closing input %d", __func__, handle);
2422 closeInput(handle);
2423 }
2424 }
2425
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)2426 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
2427 {
2428 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
2429 if (indexMin < 0 || indexMax < 0) {
2430 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2431 return;
2432 }
2433 getVolumeCurves(stream).initVolume(indexMin, indexMax);
2434
2435 // initialize other private stream volumes which follow this one
2436 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2437 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
2438 continue;
2439 }
2440 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
2441 }
2442 }
2443
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)2444 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
2445 int index,
2446 audio_devices_t device)
2447 {
2448 auto attributes = mEngine->getAttributesForStreamType(stream);
2449 ALOGV("%s: stream %s attributes=%s", __func__,
2450 toString(stream).c_str(), toString(attributes).c_str());
2451 return setVolumeIndexForAttributes(attributes, index, device);
2452 }
2453
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)2454 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
2455 int *index,
2456 audio_devices_t device)
2457 {
2458 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2459 // stream by the engine.
2460 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2461 device = mEngine->getOutputDevicesForStream(stream, true /*fromCache*/).types();
2462 }
2463 return getVolumeIndex(getVolumeCurves(stream), *index, device);
2464 }
2465
setVolumeIndexForAttributes(const audio_attributes_t & attributes,int index,audio_devices_t device)2466 status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
2467 int index,
2468 audio_devices_t device)
2469 {
2470 // Get Volume group matching the Audio Attributes
2471 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2472 if (group == VOLUME_GROUP_NONE) {
2473 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
2474 return BAD_VALUE;
2475 }
2476 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
2477 status_t status = NO_ERROR;
2478 IVolumeCurves &curves = getVolumeCurves(attributes);
2479 VolumeSource vs = toVolumeSource(group);
2480 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2481
2482 status = setVolumeCurveIndex(index, device, curves);
2483 if (status != NO_ERROR) {
2484 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2485 return status;
2486 }
2487
2488 audio_devices_t curSrcDevice;
2489 auto curCurvAttrs = curves.getAttributes();
2490 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2491 auto attr = curCurvAttrs.front();
2492 curSrcDevice = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
2493 } else if (!curves.getStreamTypes().empty()) {
2494 auto stream = curves.getStreamTypes().front();
2495 curSrcDevice = mEngine->getOutputDevicesForStream(stream, false).types();
2496 } else {
2497 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2498 return BAD_VALUE;
2499 }
2500 curSrcDevice = Volume::getDeviceForVolume(curSrcDevice);
2501
2502 // update volume on all outputs and streams matching the following:
2503 // - The requested stream (or a stream matching for volume control) is active on the output
2504 // - The device (or devices) selected by the engine for this stream includes
2505 // the requested device
2506 // - For non default requested device, currently selected device on the output is either the
2507 // requested device or one of the devices selected by the engine for this stream
2508 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2509 // no specific device volume value exists for currently selected device.
2510 for (size_t i = 0; i < mOutputs.size(); i++) {
2511 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2512 audio_devices_t curDevice = desc->devices().types();
2513
2514 if (curDevice & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
2515 curDevice |= AUDIO_DEVICE_OUT_SPEAKER;
2516 curDevice &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
2517 }
2518
2519 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2520 // If a higher priority strategy is active, and the output is routed to a device with a
2521 // HW Gain management, do not change the volume
2522 bool applyVolume = false;
2523 if (desc->useHwGain()) {
2524 if (!(desc->isActive(toVolumeSource(group)) || isInCall())) {
2525 continue;
2526 }
2527 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2528 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2529 false /*preferredDevice*/);
2530 if (activeClients.empty()) {
2531 continue;
2532 }
2533 bool isPreempted = false;
2534 bool isHigherPriority = productStrategy < strategy;
2535 for (const auto &client : activeClients) {
2536 if (isHigherPriority && (client->volumeSource() != vs)) {
2537 ALOGV("%s: Strategy=%d (\nrequester:\n"
2538 " group %d, volumeGroup=%d attributes=%s)\n"
2539 " higher priority source active:\n"
2540 " volumeGroup=%d attributes=%s) \n"
2541 " on output %zu, bailing out", __func__, productStrategy,
2542 group, group, toString(attributes).c_str(),
2543 client->volumeSource(), toString(client->attributes()).c_str(), i);
2544 applyVolume = false;
2545 isPreempted = true;
2546 break;
2547 }
2548 // However, continue for loop to ensure no higher prio clients running on output
2549 if (client->volumeSource() == vs) {
2550 applyVolume = true;
2551 }
2552 }
2553 if (isPreempted || applyVolume) {
2554 break;
2555 }
2556 }
2557 if (!applyVolume) {
2558 continue; // next output
2559 }
2560 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevice,
2561 (vs == toVolumeSource(AUDIO_STREAM_SYSTEM)?
2562 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2563 if (volStatus != NO_ERROR) {
2564 status = volStatus;
2565 }
2566 continue;
2567 }
2568 if (!(desc->isActive(vs) || isInCall())) {
2569 continue;
2570 }
2571 if ((device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) && ((curDevice & device) == 0)) {
2572 continue;
2573 }
2574 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2575 curSrcDevice |= device;
2576 applyVolume = (Volume::getDeviceForVolume(curDevice) & curSrcDevice) != 0;
2577 } else {
2578 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2579 }
2580 if (applyVolume) {
2581 //FIXME: workaround for truncated touch sounds
2582 // delayed volume change for system stream to be removed when the problem is
2583 // handled by system UI
2584 status_t volStatus = checkAndSetVolume(
2585 curves, vs, index, desc, curDevice,
2586 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2587 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2588 if (volStatus != NO_ERROR) {
2589 status = volStatus;
2590 }
2591 }
2592 }
2593 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2594 return status;
2595 }
2596
setVolumeCurveIndex(int index,audio_devices_t device,IVolumeCurves & volumeCurves)2597 status_t AudioPolicyManager::setVolumeCurveIndex(int index,
2598 audio_devices_t device,
2599 IVolumeCurves &volumeCurves)
2600 {
2601 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2602 // app that has MODIFY_PHONE_STATE permission.
2603 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2604 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
2605 (index > volumeCurves.getVolumeIndexMax())) {
2606 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2607 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2608 return BAD_VALUE;
2609 }
2610 if (!audio_is_output_device(device)) {
2611 return BAD_VALUE;
2612 }
2613
2614 // Force max volume if stream cannot be muted
2615 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2616
2617 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
2618 volumeCurves.addCurrentVolumeIndex(device, index);
2619 return NO_ERROR;
2620 }
2621
getVolumeIndexForAttributes(const audio_attributes_t & attr,int & index,audio_devices_t device)2622 status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2623 int &index,
2624 audio_devices_t device)
2625 {
2626 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2627 // stream by the engine.
2628 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2629 device = mEngine->getOutputDevicesForAttributes(attr, nullptr, true /*fromCache*/).types();
2630 }
2631 return getVolumeIndex(getVolumeCurves(attr), index, device);
2632 }
2633
getVolumeIndex(const IVolumeCurves & curves,int & index,audio_devices_t device) const2634 status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
2635 int &index,
2636 audio_devices_t device) const
2637 {
2638 if (!audio_is_output_device(device)) {
2639 return BAD_VALUE;
2640 }
2641 device = Volume::getDeviceForVolume(device);
2642 index = curves.getVolumeIndex(device);
2643 ALOGV("%s: device %08x index %d", __FUNCTION__, device, index);
2644 return NO_ERROR;
2645 }
2646
getMinVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)2647 status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
2648 int &index)
2649 {
2650 index = getVolumeCurves(attr).getVolumeIndexMin();
2651 return NO_ERROR;
2652 }
2653
getMaxVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)2654 status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
2655 int &index)
2656 {
2657 index = getVolumeCurves(attr).getVolumeIndexMax();
2658 return NO_ERROR;
2659 }
2660
selectOutputForMusicEffects()2661 audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
2662 {
2663 // select one output among several suitable for global effects.
2664 // The priority is as follows:
2665 // 1: An offloaded output. If the effect ends up not being offloadable,
2666 // AudioFlinger will invalidate the track and the offloaded output
2667 // will be closed causing the effect to be moved to a PCM output.
2668 // 2: A deep buffer output
2669 // 3: The primary output
2670 // 4: the first output in the list
2671
2672 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
2673 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
2674 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
2675
2676 if (outputs.size() == 0) {
2677 return AUDIO_IO_HANDLE_NONE;
2678 }
2679
2680 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2681 bool activeOnly = true;
2682
2683 while (output == AUDIO_IO_HANDLE_NONE) {
2684 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
2685 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
2686 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
2687
2688 for (audio_io_handle_t output : outputs) {
2689 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
2690 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
2691 continue;
2692 }
2693 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
2694 activeOnly, output, desc->mFlags);
2695 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
2696 outputOffloaded = output;
2697 }
2698 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
2699 outputDeepBuffer = output;
2700 }
2701 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
2702 outputPrimary = output;
2703 }
2704 }
2705 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
2706 output = outputOffloaded;
2707 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
2708 output = outputDeepBuffer;
2709 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
2710 output = outputPrimary;
2711 } else {
2712 output = outputs[0];
2713 }
2714 activeOnly = false;
2715 }
2716
2717 if (output != mMusicEffectOutput) {
2718 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2719 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
2720 mMusicEffectOutput = output;
2721 }
2722
2723 ALOGV("selectOutputForMusicEffects selected output %d", output);
2724 return output;
2725 }
2726
getOutputForEffect(const effect_descriptor_t * desc __unused)2727 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
2728 {
2729 return selectOutputForMusicEffects();
2730 }
2731
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,uint32_t strategy,int session,int id)2732 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
2733 audio_io_handle_t io,
2734 uint32_t strategy,
2735 int session,
2736 int id)
2737 {
2738 ssize_t index = mOutputs.indexOfKey(io);
2739 if (index < 0) {
2740 index = mInputs.indexOfKey(io);
2741 if (index < 0) {
2742 ALOGW("registerEffect() unknown io %d", io);
2743 return INVALID_OPERATION;
2744 }
2745 }
2746 return mEffects.registerEffect(desc, io, session, id,
2747 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
2748 strategy == PRODUCT_STRATEGY_NONE));
2749 }
2750
unregisterEffect(int id)2751 status_t AudioPolicyManager::unregisterEffect(int id)
2752 {
2753 if (mEffects.getEffect(id) == nullptr) {
2754 return INVALID_OPERATION;
2755 }
2756 if (mEffects.isEffectEnabled(id)) {
2757 ALOGW("%s effect %d enabled", __FUNCTION__, id);
2758 setEffectEnabled(id, false);
2759 }
2760 return mEffects.unregisterEffect(id);
2761 }
2762
cleanUpEffectsForIo(audio_io_handle_t io)2763 void AudioPolicyManager::cleanUpEffectsForIo(audio_io_handle_t io)
2764 {
2765 EffectDescriptorCollection effects = mEffects.getEffectsForIo(io);
2766 for (size_t i = 0; i < effects.size(); i++) {
2767 ALOGW("%s removing stale effect %s, id %d on closed IO %d",
2768 __func__, effects.valueAt(i)->mDesc.name, effects.keyAt(i), io);
2769 unregisterEffect(effects.keyAt(i));
2770 }
2771 }
2772
setEffectEnabled(int id,bool enabled)2773 status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
2774 {
2775 sp<EffectDescriptor> effect = mEffects.getEffect(id);
2776 if (effect == nullptr) {
2777 return INVALID_OPERATION;
2778 }
2779
2780 status_t status = mEffects.setEffectEnabled(id, enabled);
2781 if (status == NO_ERROR) {
2782 mInputs.trackEffectEnabled(effect, enabled);
2783 }
2784 return status;
2785 }
2786
2787
moveEffectsToIo(const std::vector<int> & ids,audio_io_handle_t io)2788 status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
2789 {
2790 mEffects.moveEffects(ids, io);
2791 return NO_ERROR;
2792 }
2793
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const2794 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
2795 {
2796 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
2797 }
2798
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const2799 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
2800 {
2801 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
2802 }
2803
isSourceActive(audio_source_t source) const2804 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
2805 {
2806 for (size_t i = 0; i < mInputs.size(); i++) {
2807 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
2808 if (inputDescriptor->isSourceActive(source)) {
2809 return true;
2810 }
2811 }
2812 return false;
2813 }
2814
2815 // Register a list of custom mixes with their attributes and format.
2816 // When a mix is registered, corresponding input and output profiles are
2817 // added to the remote submix hw module. The profile contains only the
2818 // parameters (sampling rate, format...) specified by the mix.
2819 // The corresponding input remote submix device is also connected.
2820 //
2821 // When a remote submix device is connected, the address is checked to select the
2822 // appropriate profile and the corresponding input or output stream is opened.
2823 //
2824 // When capture starts, getInputForAttr() will:
2825 // - 1 look for a mix matching the address passed in attribtutes tags if any
2826 // - 2 if none found, getDeviceForInputSource() will:
2827 // - 2.1 look for a mix matching the attributes source
2828 // - 2.2 if none found, default to device selection by policy rules
2829 // At this time, the corresponding output remote submix device is also connected
2830 // and active playback use cases can be transferred to this mix if needed when reconnecting
2831 // after AudioTracks are invalidated
2832 //
2833 // When playback starts, getOutputForAttr() will:
2834 // - 1 look for a mix matching the address passed in attribtutes tags if any
2835 // - 2 if none found, look for a mix matching the attributes usage
2836 // - 3 if none found, default to device and output selection by policy rules.
2837
registerPolicyMixes(const Vector<AudioMix> & mixes)2838 status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
2839 {
2840 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
2841 status_t res = NO_ERROR;
2842
2843 sp<HwModule> rSubmixModule;
2844 // examine each mix's route type
2845 for (size_t i = 0; i < mixes.size(); i++) {
2846 AudioMix mix = mixes[i];
2847 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
2848 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
2849 ALOGE("Unsupported Policy Mix %zu of %zu: "
2850 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
2851 i, mixes.size());
2852 res = INVALID_OPERATION;
2853 break;
2854 }
2855 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
2856 // in the same way.
2857 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2858 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
2859 mix.mRouteFlags);
2860 if (rSubmixModule == 0) {
2861 rSubmixModule = mHwModules.getModuleFromName(
2862 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2863 if (rSubmixModule == 0) {
2864 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
2865 i);
2866 res = INVALID_OPERATION;
2867 break;
2868 }
2869 }
2870
2871 String8 address = mix.mDeviceAddress;
2872 audio_devices_t deviceTypeToMakeAvailable;
2873 if (mix.mMixType == MIX_TYPE_PLAYERS) {
2874 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2875 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2876 } else {
2877 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2878 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2879 }
2880
2881 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
2882 ALOGE("Error registering mix %zu for address %s", i, address.string());
2883 res = INVALID_OPERATION;
2884 break;
2885 }
2886 audio_config_t outputConfig = mix.mFormat;
2887 audio_config_t inputConfig = mix.mFormat;
2888 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2889 // stereo and let audio flinger do the channel conversion if needed.
2890 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2891 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2892 rSubmixModule->addOutputProfile(address, &outputConfig,
2893 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2894 rSubmixModule->addInputProfile(address, &inputConfig,
2895 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2896
2897 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
2898 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2899 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
2900 ALOGE("Failed to set remote submix device available, type %u, address %s",
2901 mix.mDeviceType, address.string());
2902 break;
2903 }
2904 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2905 String8 address = mix.mDeviceAddress;
2906 audio_devices_t type = mix.mDeviceType;
2907 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
2908 i, mixes.size(), type, address.string());
2909
2910 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
2911 mix.mDeviceType, mix.mDeviceAddress,
2912 String8(), AUDIO_FORMAT_DEFAULT);
2913 if (device == nullptr) {
2914 res = INVALID_OPERATION;
2915 break;
2916 }
2917
2918 bool foundOutput = false;
2919 for (size_t j = 0 ; j < mOutputs.size() ; j++) {
2920 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
2921
2922 if (desc->supportedDevices().contains(device)) {
2923 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
2924 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
2925 address.string());
2926 res = INVALID_OPERATION;
2927 } else {
2928 foundOutput = true;
2929 }
2930 break;
2931 }
2932 }
2933
2934 if (res != NO_ERROR) {
2935 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
2936 i, type, address.string());
2937 res = INVALID_OPERATION;
2938 break;
2939 } else if (!foundOutput) {
2940 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
2941 i, type, address.string());
2942 res = INVALID_OPERATION;
2943 break;
2944 }
2945 }
2946 }
2947 if (res != NO_ERROR) {
2948 unregisterPolicyMixes(mixes);
2949 }
2950 return res;
2951 }
2952
unregisterPolicyMixes(Vector<AudioMix> mixes)2953 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2954 {
2955 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
2956 status_t res = NO_ERROR;
2957 sp<HwModule> rSubmixModule;
2958 // examine each mix's route type
2959 for (const auto& mix : mixes) {
2960 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2961
2962 if (rSubmixModule == 0) {
2963 rSubmixModule = mHwModules.getModuleFromName(
2964 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
2965 if (rSubmixModule == 0) {
2966 res = INVALID_OPERATION;
2967 continue;
2968 }
2969 }
2970
2971 String8 address = mix.mDeviceAddress;
2972
2973 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
2974 res = INVALID_OPERATION;
2975 continue;
2976 }
2977
2978 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
2979 if (getDeviceConnectionState(device, address.string()) ==
2980 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2981 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2982 address.string(), "remote-submix",
2983 AUDIO_FORMAT_DEFAULT);
2984 if (res != OK) {
2985 ALOGE("Error making RemoteSubmix device unavailable for mix "
2986 "with type %d, address %s", device, address.string());
2987 }
2988 }
2989 }
2990 rSubmixModule->removeOutputProfile(address);
2991 rSubmixModule->removeInputProfile(address);
2992
2993 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
2994 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
2995 res = INVALID_OPERATION;
2996 continue;
2997 }
2998 }
2999 }
3000 return res;
3001 }
3002
dumpManualSurroundFormats(String8 * dst) const3003 void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3004 {
3005 size_t i = 0;
3006 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3007 for (const auto& fmt : mManualSurroundFormats) {
3008 if (i++ != 0) dst->append(", ");
3009 std::string sfmt;
3010 FormatConverter::toString(fmt, sfmt);
3011 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3012 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3013 }
3014 }
3015
setUidDeviceAffinities(uid_t uid,const Vector<AudioDeviceTypeAddr> & devices)3016 status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
3017 const Vector<AudioDeviceTypeAddr>& devices) {
3018 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
3019 // uid/device affinity is only for output devices
3020 for (size_t i = 0; i < devices.size(); i++) {
3021 if (!audio_is_output_device(devices[i].mType)) {
3022 ALOGE("setUidDeviceAffinities() device=%08x is NOT an output device",
3023 devices[i].mType);
3024 return BAD_VALUE;
3025 }
3026 }
3027 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
3028 if (res == NO_ERROR) {
3029 // reevaluate outputs for all given devices
3030 for (size_t i = 0; i < devices.size(); i++) {
3031 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
3032 devices[i].mType, devices[i].mAddress, String8(),
3033 AUDIO_FORMAT_DEFAULT);
3034 SortedVector<audio_io_handle_t> outputs;
3035 if (checkOutputsForDevice(devDesc, AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3036 outputs) != NO_ERROR) {
3037 ALOGE("setUidDeviceAffinities() error in checkOutputsForDevice for device=%08x"
3038 " addr=%s", devices[i].mType, devices[i].mAddress.string());
3039 return INVALID_OPERATION;
3040 }
3041 }
3042 }
3043 return res;
3044 }
3045
removeUidDeviceAffinities(uid_t uid)3046 status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3047 ALOGV("%s() uid=%d", __FUNCTION__, uid);
3048 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3049 if (res != NO_ERROR) {
3050 ALOGE("%s() Could not remove all device affinities fo uid = %d",
3051 __FUNCTION__, uid);
3052 return INVALID_OPERATION;
3053 }
3054
3055 return res;
3056 }
3057
dump(String8 * dst) const3058 void AudioPolicyManager::dump(String8 *dst) const
3059 {
3060 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
3061 dst->appendFormat(" Primary Output: %d\n",
3062 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
3063 std::string stateLiteral;
3064 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
3065 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
3066 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3067 "communications", "media", "record", "dock", "system",
3068 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3069 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3070 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
3071 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3072 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3073 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3074 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3075 dst->append(" (MANUAL: ");
3076 dumpManualSurroundFormats(dst);
3077 dst->append(")");
3078 }
3079 dst->append("\n");
3080 }
3081 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3082 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
3083 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
3084 mAvailableOutputDevices.dump(dst, String8("Available output"));
3085 mAvailableInputDevices.dump(dst, String8("Available input"));
3086 mHwModulesAll.dump(dst);
3087 mOutputs.dump(dst);
3088 mInputs.dump(dst);
3089 mEffects.dump(dst);
3090 mAudioPatches.dump(dst);
3091 mPolicyMixes.dump(dst);
3092 mAudioSources.dump(dst);
3093
3094 dst->appendFormat(" AllowedCapturePolicies:\n");
3095 for (auto& policy : mAllowedCapturePolicies) {
3096 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3097 }
3098
3099 dst->appendFormat("\nPolicy Engine dump:\n");
3100 mEngine->dump(dst);
3101 }
3102
dump(int fd)3103 status_t AudioPolicyManager::dump(int fd)
3104 {
3105 String8 result;
3106 dump(&result);
3107 write(fd, result.string(), result.size());
3108 return NO_ERROR;
3109 }
3110
setAllowedCapturePolicy(uid_t uid,audio_flags_mask_t capturePolicy)3111 status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3112 {
3113 mAllowedCapturePolicies[uid] = capturePolicy;
3114 return NO_ERROR;
3115 }
3116
3117 // This function checks for the parameters which can be offloaded.
3118 // This can be enhanced depending on the capability of the DSP and policy
3119 // of the system.
isOffloadSupported(const audio_offload_info_t & offloadInfo)3120 bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
3121 {
3122 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
3123 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
3124 offloadInfo.sample_rate, offloadInfo.channel_mask,
3125 offloadInfo.format,
3126 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3127 offloadInfo.has_video);
3128
3129 if (mMasterMono) {
3130 return false; // no offloading if mono is set.
3131 }
3132
3133 // Check if offload has been disabled
3134 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3135 ALOGV("offload disabled by audio.offload.disable");
3136 return false;
3137 }
3138
3139 // Check if stream type is music, then only allow offload as of now.
3140 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3141 {
3142 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
3143 return false;
3144 }
3145
3146 //TODO: enable audio offloading with video when ready
3147 const bool allowOffloadWithVideo =
3148 property_get_bool("audio.offload.video", false /* default_value */);
3149 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3150 ALOGV("isOffloadSupported: has_video == true, returning false");
3151 return false;
3152 }
3153
3154 //If duration is less than minimum value defined in property, return false
3155 const int min_duration_secs = property_get_int32(
3156 "audio.offload.min.duration.secs", -1 /* default_value */);
3157 if (min_duration_secs >= 0) {
3158 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3159 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3160 min_duration_secs);
3161 return false;
3162 }
3163 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3164 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3165 return false;
3166 }
3167
3168 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3169 // creating an offloaded track and tearing it down immediately after start when audioflinger
3170 // detects there is an active non offloadable effect.
3171 // FIXME: We should check the audio session here but we do not have it in this context.
3172 // This may prevent offloading in rare situations where effects are left active by apps
3173 // in the background.
3174 if (mEffects.isNonOffloadableEffectEnabled()) {
3175 return false;
3176 }
3177
3178 // See if there is a profile to support this.
3179 // AUDIO_DEVICE_NONE
3180 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
3181 offloadInfo.sample_rate,
3182 offloadInfo.format,
3183 offloadInfo.channel_mask,
3184 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3185 true /* directOnly */);
3186 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
3187 return (profile != 0);
3188 }
3189
isDirectOutputSupported(const audio_config_base_t & config,const audio_attributes_t & attributes)3190 bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3191 const audio_attributes_t& attributes) {
3192 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
3193 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
3194 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
3195 config.sample_rate,
3196 config.format,
3197 config.channel_mask,
3198 output_flags,
3199 true /* directOnly */);
3200 ALOGV("%s() profile %sfound with name: %s, "
3201 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3202 __FUNCTION__, profile != 0 ? "" : "NOT ",
3203 (profile != 0 ? profile->getTagName().string() : "null"),
3204 config.sample_rate, config.format, config.channel_mask, output_flags);
3205 return (profile != 0);
3206 }
3207
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port * ports,unsigned int * generation)3208 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3209 audio_port_type_t type,
3210 unsigned int *num_ports,
3211 struct audio_port *ports,
3212 unsigned int *generation)
3213 {
3214 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
3215 generation == NULL) {
3216 return BAD_VALUE;
3217 }
3218 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
3219 if (ports == NULL) {
3220 *num_ports = 0;
3221 }
3222
3223 size_t portsWritten = 0;
3224 size_t portsMax = *num_ports;
3225 *num_ports = 0;
3226 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
3227 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3228 // as they are used by stub HALs by convention
3229 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3230 for (const auto& dev : mAvailableOutputDevices) {
3231 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
3232 continue;
3233 }
3234 if (portsWritten < portsMax) {
3235 dev->toAudioPort(&ports[portsWritten++]);
3236 }
3237 (*num_ports)++;
3238 }
3239 }
3240 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
3241 for (const auto& dev : mAvailableInputDevices) {
3242 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
3243 continue;
3244 }
3245 if (portsWritten < portsMax) {
3246 dev->toAudioPort(&ports[portsWritten++]);
3247 }
3248 (*num_ports)++;
3249 }
3250 }
3251 }
3252 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
3253 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
3254 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
3255 mInputs[i]->toAudioPort(&ports[portsWritten++]);
3256 }
3257 *num_ports += mInputs.size();
3258 }
3259 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
3260 size_t numOutputs = 0;
3261 for (size_t i = 0; i < mOutputs.size(); i++) {
3262 if (!mOutputs[i]->isDuplicated()) {
3263 numOutputs++;
3264 if (portsWritten < portsMax) {
3265 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
3266 }
3267 }
3268 }
3269 *num_ports += numOutputs;
3270 }
3271 }
3272 *generation = curAudioPortGeneration();
3273 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
3274 return NO_ERROR;
3275 }
3276
getAudioPort(struct audio_port * port)3277 status_t AudioPolicyManager::getAudioPort(struct audio_port *port)
3278 {
3279 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
3280 return BAD_VALUE;
3281 }
3282 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
3283 if (dev != 0) {
3284 dev->toAudioPort(port);
3285 return NO_ERROR;
3286 }
3287 dev = mAvailableInputDevices.getDeviceFromId(port->id);
3288 if (dev != 0) {
3289 dev->toAudioPort(port);
3290 return NO_ERROR;
3291 }
3292 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
3293 if (out != 0) {
3294 out->toAudioPort(port);
3295 return NO_ERROR;
3296 }
3297 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
3298 if (in != 0) {
3299 in->toAudioPort(port);
3300 return NO_ERROR;
3301 }
3302 return BAD_VALUE;
3303 }
3304
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)3305 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
3306 audio_patch_handle_t *handle,
3307 uid_t uid)
3308 {
3309 ALOGV("createAudioPatch()");
3310
3311 if (handle == NULL || patch == NULL) {
3312 return BAD_VALUE;
3313 }
3314 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
3315
3316 if (!audio_patch_is_valid(patch)) {
3317 return BAD_VALUE;
3318 }
3319 // only one source per audio patch supported for now
3320 if (patch->num_sources > 1) {
3321 return INVALID_OPERATION;
3322 }
3323
3324 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
3325 return INVALID_OPERATION;
3326 }
3327 for (size_t i = 0; i < patch->num_sinks; i++) {
3328 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
3329 return INVALID_OPERATION;
3330 }
3331 }
3332
3333 sp<AudioPatch> patchDesc;
3334 ssize_t index = mAudioPatches.indexOfKey(*handle);
3335
3336 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
3337 patch->sources[0].role,
3338 patch->sources[0].type);
3339 #if LOG_NDEBUG == 0
3340 for (size_t i = 0; i < patch->num_sinks; i++) {
3341 ALOGV("createAudioPatch sink %zu: id %d role %d type %d", i, patch->sinks[i].id,
3342 patch->sinks[i].role,
3343 patch->sinks[i].type);
3344 }
3345 #endif
3346
3347 if (index >= 0) {
3348 patchDesc = mAudioPatches.valueAt(index);
3349 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3350 mUidCached, patchDesc->mUid, uid);
3351 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3352 return INVALID_OPERATION;
3353 }
3354 } else {
3355 *handle = AUDIO_PATCH_HANDLE_NONE;
3356 }
3357
3358 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
3359 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
3360 if (outputDesc == NULL) {
3361 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
3362 return BAD_VALUE;
3363 }
3364 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
3365 outputDesc->mIoHandle);
3366 if (patchDesc != 0) {
3367 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3368 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
3369 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
3370 return BAD_VALUE;
3371 }
3372 }
3373 DeviceVector devices;
3374 for (size_t i = 0; i < patch->num_sinks; i++) {
3375 // Only support mix to devices connection
3376 // TODO add support for mix to mix connection
3377 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3378 ALOGV("createAudioPatch() source mix but sink is not a device");
3379 return INVALID_OPERATION;
3380 }
3381 sp<DeviceDescriptor> devDesc =
3382 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3383 if (devDesc == 0) {
3384 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
3385 return BAD_VALUE;
3386 }
3387
3388 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
3389 patch->sources[0].sample_rate,
3390 NULL, // updatedSamplingRate
3391 patch->sources[0].format,
3392 NULL, // updatedFormat
3393 patch->sources[0].channel_mask,
3394 NULL, // updatedChannelMask
3395 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
3396 ALOGV("createAudioPatch() profile not supported for device %08x",
3397 devDesc->type());
3398 return INVALID_OPERATION;
3399 }
3400 devices.add(devDesc);
3401 }
3402 if (devices.size() == 0) {
3403 return INVALID_OPERATION;
3404 }
3405
3406 // TODO: reconfigure output format and channels here
3407 ALOGV("createAudioPatch() setting device %08x on output %d",
3408 devices.types(), outputDesc->mIoHandle);
3409 setOutputDevices(outputDesc, devices, true, 0, handle);
3410 index = mAudioPatches.indexOfKey(*handle);
3411 if (index >= 0) {
3412 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3413 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
3414 }
3415 patchDesc = mAudioPatches.valueAt(index);
3416 patchDesc->mUid = uid;
3417 ALOGV("createAudioPatch() success");
3418 } else {
3419 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
3420 return INVALID_OPERATION;
3421 }
3422 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3423 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3424 // input device to input mix connection
3425 // only one sink supported when connecting an input device to a mix
3426 if (patch->num_sinks > 1) {
3427 return INVALID_OPERATION;
3428 }
3429 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
3430 if (inputDesc == NULL) {
3431 return BAD_VALUE;
3432 }
3433 if (patchDesc != 0) {
3434 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
3435 return BAD_VALUE;
3436 }
3437 }
3438 sp<DeviceDescriptor> device =
3439 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3440 if (device == 0) {
3441 return BAD_VALUE;
3442 }
3443
3444 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
3445 patch->sinks[0].sample_rate,
3446 NULL, /*updatedSampleRate*/
3447 patch->sinks[0].format,
3448 NULL, /*updatedFormat*/
3449 patch->sinks[0].channel_mask,
3450 NULL, /*updatedChannelMask*/
3451 // FIXME for the parameter type,
3452 // and the NONE
3453 (audio_output_flags_t)
3454 AUDIO_INPUT_FLAG_NONE)) {
3455 return INVALID_OPERATION;
3456 }
3457 // TODO: reconfigure output format and channels here
3458 ALOGV("%s() setting device %s on output %d", __func__,
3459 device->toString().c_str(), inputDesc->mIoHandle);
3460 setInputDevice(inputDesc->mIoHandle, device, true, handle);
3461 index = mAudioPatches.indexOfKey(*handle);
3462 if (index >= 0) {
3463 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
3464 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
3465 }
3466 patchDesc = mAudioPatches.valueAt(index);
3467 patchDesc->mUid = uid;
3468 ALOGV("createAudioPatch() success");
3469 } else {
3470 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
3471 return INVALID_OPERATION;
3472 }
3473 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3474 // device to device connection
3475 if (patchDesc != 0) {
3476 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
3477 return BAD_VALUE;
3478 }
3479 }
3480 sp<DeviceDescriptor> srcDevice =
3481 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
3482 if (srcDevice == 0) {
3483 return BAD_VALUE;
3484 }
3485
3486 //update source and sink with our own data as the data passed in the patch may
3487 // be incomplete.
3488 struct audio_patch newPatch = *patch;
3489 srcDevice->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
3490
3491 for (size_t i = 0; i < patch->num_sinks; i++) {
3492 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
3493 ALOGV("createAudioPatch() source device but one sink is not a device");
3494 return INVALID_OPERATION;
3495 }
3496
3497 sp<DeviceDescriptor> sinkDevice =
3498 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
3499 if (sinkDevice == 0) {
3500 return BAD_VALUE;
3501 }
3502 sinkDevice->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
3503
3504 // create a software bridge in PatchPanel if:
3505 // - source and sink devices are on different HW modules OR
3506 // - audio HAL version is < 3.0
3507 // - audio HAL version is >= 3.0 but no route has been declared between devices
3508 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
3509 (srcDevice->getModuleVersionMajor() < 3) ||
3510 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice)) {
3511 // support only one sink device for now to simplify output selection logic
3512 if (patch->num_sinks > 1) {
3513 return INVALID_OPERATION;
3514 }
3515 SortedVector<audio_io_handle_t> outputs =
3516 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
3517 // if the sink device is reachable via an opened output stream, request to go via
3518 // this output stream by adding a second source to the patch description
3519 const audio_io_handle_t output = selectOutput(outputs);
3520 if (output != AUDIO_IO_HANDLE_NONE) {
3521 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3522 if (outputDesc->isDuplicated()) {
3523 return INVALID_OPERATION;
3524 }
3525 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
3526 newPatch.sources[1].ext.mix.usecase.stream = AUDIO_STREAM_PATCH;
3527 newPatch.num_sources = 2;
3528 }
3529 }
3530 }
3531 // TODO: check from routing capabilities in config file and other conflicting patches
3532
3533 status_t status = installPatch(__func__, index, handle, &newPatch, 0, uid, &patchDesc);
3534 if (status != NO_ERROR) {
3535 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
3536 status);
3537 return INVALID_OPERATION;
3538 }
3539 } else {
3540 return BAD_VALUE;
3541 }
3542 } else {
3543 return BAD_VALUE;
3544 }
3545 return NO_ERROR;
3546 }
3547
releaseAudioPatch(audio_patch_handle_t handle,uid_t uid)3548 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
3549 uid_t uid)
3550 {
3551 ALOGV("releaseAudioPatch() patch %d", handle);
3552
3553 ssize_t index = mAudioPatches.indexOfKey(handle);
3554
3555 if (index < 0) {
3556 return BAD_VALUE;
3557 }
3558 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3559 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
3560 mUidCached, patchDesc->mUid, uid);
3561 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
3562 return INVALID_OPERATION;
3563 }
3564
3565 struct audio_patch *patch = &patchDesc->mPatch;
3566 patchDesc->mUid = mUidCached;
3567 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
3568 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
3569 if (outputDesc == NULL) {
3570 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
3571 return BAD_VALUE;
3572 }
3573
3574 setOutputDevices(outputDesc,
3575 getNewOutputDevices(outputDesc, true /*fromCache*/),
3576 true,
3577 0,
3578 NULL);
3579 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
3580 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
3581 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
3582 if (inputDesc == NULL) {
3583 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
3584 return BAD_VALUE;
3585 }
3586 setInputDevice(inputDesc->mIoHandle,
3587 getNewInputDevice(inputDesc),
3588 true,
3589 NULL);
3590 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
3591 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
3592 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
3593 status, patchDesc->mAfPatchHandle);
3594 removeAudioPatch(patchDesc->mHandle);
3595 nextAudioPortGeneration();
3596 mpClientInterface->onAudioPatchListUpdate();
3597 } else {
3598 return BAD_VALUE;
3599 }
3600 } else {
3601 return BAD_VALUE;
3602 }
3603 return NO_ERROR;
3604 }
3605
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)3606 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
3607 struct audio_patch *patches,
3608 unsigned int *generation)
3609 {
3610 if (generation == NULL) {
3611 return BAD_VALUE;
3612 }
3613 *generation = curAudioPortGeneration();
3614 return mAudioPatches.listAudioPatches(num_patches, patches);
3615 }
3616
setAudioPortConfig(const struct audio_port_config * config)3617 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
3618 {
3619 ALOGV("setAudioPortConfig()");
3620
3621 if (config == NULL) {
3622 return BAD_VALUE;
3623 }
3624 ALOGV("setAudioPortConfig() on port handle %d", config->id);
3625 // Only support gain configuration for now
3626 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
3627 return INVALID_OPERATION;
3628 }
3629
3630 sp<AudioPortConfig> audioPortConfig;
3631 if (config->type == AUDIO_PORT_TYPE_MIX) {
3632 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3633 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
3634 if (outputDesc == NULL) {
3635 return BAD_VALUE;
3636 }
3637 ALOG_ASSERT(!outputDesc->isDuplicated(),
3638 "setAudioPortConfig() called on duplicated output %d",
3639 outputDesc->mIoHandle);
3640 audioPortConfig = outputDesc;
3641 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3642 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
3643 if (inputDesc == NULL) {
3644 return BAD_VALUE;
3645 }
3646 audioPortConfig = inputDesc;
3647 } else {
3648 return BAD_VALUE;
3649 }
3650 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
3651 sp<DeviceDescriptor> deviceDesc;
3652 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
3653 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
3654 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
3655 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
3656 } else {
3657 return BAD_VALUE;
3658 }
3659 if (deviceDesc == NULL) {
3660 return BAD_VALUE;
3661 }
3662 audioPortConfig = deviceDesc;
3663 } else {
3664 return BAD_VALUE;
3665 }
3666
3667 struct audio_port_config backupConfig = {};
3668 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
3669 if (status == NO_ERROR) {
3670 struct audio_port_config newConfig = {};
3671 audioPortConfig->toAudioPortConfig(&newConfig, config);
3672 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
3673 }
3674 if (status != NO_ERROR) {
3675 audioPortConfig->applyAudioPortConfig(&backupConfig);
3676 }
3677
3678 return status;
3679 }
3680
releaseResourcesForUid(uid_t uid)3681 void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
3682 {
3683 clearAudioSources(uid);
3684 clearAudioPatches(uid);
3685 clearSessionRoutes(uid);
3686 }
3687
clearAudioPatches(uid_t uid)3688 void AudioPolicyManager::clearAudioPatches(uid_t uid)
3689 {
3690 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
3691 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
3692 if (patchDesc->mUid == uid) {
3693 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
3694 }
3695 }
3696 }
3697
checkStrategyRoute(product_strategy_t ps,audio_io_handle_t ouptutToSkip)3698 void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
3699 {
3700 // Take the first attributes following the product strategy as it is used to retrieve the routed
3701 // device. All attributes wihin a strategy follows the same "routing strategy"
3702 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
3703 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
3704 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
3705 for (size_t j = 0; j < mOutputs.size(); j++) {
3706 if (mOutputs.keyAt(j) == ouptutToSkip) {
3707 continue;
3708 }
3709 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
3710 if (!outputDesc->isStrategyActive(ps)) {
3711 continue;
3712 }
3713 // If the default device for this strategy is on another output mix,
3714 // invalidate all tracks in this strategy to force re connection.
3715 // Otherwise select new device on the output mix.
3716 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
3717 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
3718 mpClientInterface->invalidateStream(stream);
3719 }
3720 } else {
3721 setOutputDevices(
3722 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
3723 }
3724 }
3725 }
3726
clearSessionRoutes(uid_t uid)3727 void AudioPolicyManager::clearSessionRoutes(uid_t uid)
3728 {
3729 // remove output routes associated with this uid
3730 std::vector<product_strategy_t> affectedStrategies;
3731 for (size_t i = 0; i < mOutputs.size(); i++) {
3732 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3733 for (const auto& client : outputDesc->getClientIterable()) {
3734 if (client->hasPreferredDevice() && client->uid() == uid) {
3735 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3736 auto clientStrategy = client->strategy();
3737 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
3738 end(affectedStrategies)) {
3739 continue;
3740 }
3741 affectedStrategies.push_back(client->strategy());
3742 }
3743 }
3744 }
3745 // reroute outputs if necessary
3746 for (const auto& strategy : affectedStrategies) {
3747 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
3748 }
3749
3750 // remove input routes associated with this uid
3751 SortedVector<audio_source_t> affectedSources;
3752 for (size_t i = 0; i < mInputs.size(); i++) {
3753 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3754 for (const auto& client : inputDesc->getClientIterable()) {
3755 if (client->hasPreferredDevice() && client->uid() == uid) {
3756 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
3757 affectedSources.add(client->source());
3758 }
3759 }
3760 }
3761 // reroute inputs if necessary
3762 SortedVector<audio_io_handle_t> inputsToClose;
3763 for (size_t i = 0; i < mInputs.size(); i++) {
3764 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
3765 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
3766 inputsToClose.add(inputDesc->mIoHandle);
3767 }
3768 }
3769 for (const auto& input : inputsToClose) {
3770 closeInput(input);
3771 }
3772 }
3773
clearAudioSources(uid_t uid)3774 void AudioPolicyManager::clearAudioSources(uid_t uid)
3775 {
3776 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
3777 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
3778 if (sourceDesc->uid() == uid) {
3779 stopAudioSource(mAudioSources.keyAt(i));
3780 }
3781 }
3782 }
3783
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)3784 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
3785 audio_io_handle_t *ioHandle,
3786 audio_devices_t *device)
3787 {
3788 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
3789 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
3790 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
3791 *device = mEngine->getInputDeviceForAttributes(attr)->type();
3792
3793 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
3794 }
3795
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId,uid_t uid)3796 status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
3797 const audio_attributes_t *attributes,
3798 audio_port_handle_t *portId,
3799 uid_t uid)
3800 {
3801 ALOGV("%s", __FUNCTION__);
3802 *portId = AUDIO_PORT_HANDLE_NONE;
3803
3804 if (source == NULL || attributes == NULL || portId == NULL) {
3805 ALOGW("%s invalid argument: source %p attributes %p handle %p",
3806 __FUNCTION__, source, attributes, portId);
3807 return BAD_VALUE;
3808 }
3809
3810 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
3811 source->type != AUDIO_PORT_TYPE_DEVICE) {
3812 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
3813 __FUNCTION__, source->role, source->type);
3814 return INVALID_OPERATION;
3815 }
3816
3817 sp<DeviceDescriptor> srcDevice =
3818 mAvailableInputDevices.getDevice(source->ext.device.type,
3819 String8(source->ext.device.address),
3820 AUDIO_FORMAT_DEFAULT);
3821 if (srcDevice == 0) {
3822 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
3823 return BAD_VALUE;
3824 }
3825
3826 *portId = AudioPort::getNextUniqueId();
3827
3828 struct audio_patch dummyPatch = {};
3829 sp<AudioPatch> patchDesc = new AudioPatch(&dummyPatch, uid);
3830
3831 sp<SourceClientDescriptor> sourceDesc =
3832 new SourceClientDescriptor(*portId, uid, *attributes, patchDesc, srcDevice,
3833 mEngine->getStreamTypeForAttributes(*attributes),
3834 mEngine->getProductStrategyForAttributes(*attributes),
3835 toVolumeSource(*attributes));
3836
3837 status_t status = connectAudioSource(sourceDesc);
3838 if (status == NO_ERROR) {
3839 mAudioSources.add(*portId, sourceDesc);
3840 }
3841 return status;
3842 }
3843
connectAudioSource(const sp<SourceClientDescriptor> & sourceDesc)3844 status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
3845 {
3846 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
3847
3848 // make sure we only have one patch per source.
3849 disconnectAudioSource(sourceDesc);
3850
3851 audio_attributes_t attributes = sourceDesc->attributes();
3852 audio_stream_type_t stream = sourceDesc->stream();
3853 sp<DeviceDescriptor> srcDevice = sourceDesc->srcDevice();
3854
3855 DeviceVector sinkDevices =
3856 mEngine->getOutputDevicesForAttributes(attributes, nullptr, true);
3857 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
3858 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
3859 ALOG_ASSERT(mAvailableOutputDevices.contains(sinkDevice), "%s: Device %s not available",
3860 __FUNCTION__, sinkDevice->toString().c_str());
3861
3862 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3863
3864 if (srcDevice->hasSameHwModuleAs(sinkDevice) &&
3865 srcDevice->getModuleVersionMajor() >= 3 &&
3866 sinkDevice->getModule()->supportsPatch(srcDevice, sinkDevice) &&
3867 srcDevice->getAudioPort()->mGains.size() > 0) {
3868 ALOGV("%s Device to Device route supported by >=3.0 HAL", __FUNCTION__);
3869 // TODO: may explicitly specify whether we should use HW or SW patch
3870 // create patch between src device and output device
3871 // create Hwoutput and add to mHwOutputs
3872 } else {
3873 audio_attributes_t resultAttr;
3874 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3875 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3876 config.sample_rate = sourceDesc->config().sample_rate;
3877 config.channel_mask = sourceDesc->config().channel_mask;
3878 config.format = sourceDesc->config().format;
3879 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3880 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
3881 bool isRequestedDeviceForExclusiveUse = false;
3882 std::vector<sp<SwAudioOutputDescriptor>> secondaryOutputs;
3883 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE,
3884 &attributes, &stream, sourceDesc->uid(), &config, &flags,
3885 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
3886 &secondaryOutputs);
3887 if (output == AUDIO_IO_HANDLE_NONE) {
3888 ALOGV("%s no output for device %08x", __FUNCTION__, sinkDevices.types());
3889 return INVALID_OPERATION;
3890 }
3891 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3892 if (outputDesc->isDuplicated()) {
3893 ALOGV("%s output for device %08x is duplicated", __FUNCTION__, sinkDevices.types());
3894 return INVALID_OPERATION;
3895 }
3896 status_t status = outputDesc->start();
3897 if (status != NO_ERROR) {
3898 return status;
3899 }
3900
3901 // create a special patch with no sink and two sources:
3902 // - the second source indicates to PatchPanel through which output mix this patch should
3903 // be connected as well as the stream type for volume control
3904 // - the sink is defined by whatever output device is currently selected for the output
3905 // though which this patch is routed.
3906 PatchBuilder patchBuilder;
3907 patchBuilder.addSource(srcDevice).addSource(outputDesc, { .stream = stream });
3908 status = mpClientInterface->createAudioPatch(patchBuilder.patch(),
3909 &afPatchHandle,
3910 0);
3911 ALOGV("%s patch panel returned %d patchHandle %d", __FUNCTION__,
3912 status, afPatchHandle);
3913 sourceDesc->patchDesc()->mPatch = *patchBuilder.patch();
3914 if (status != NO_ERROR) {
3915 ALOGW("%s patch panel could not connect device patch, error %d",
3916 __FUNCTION__, status);
3917 return INVALID_OPERATION;
3918 }
3919
3920 if (outputDesc->getClient(sourceDesc->portId()) != nullptr) {
3921 ALOGW("%s source portId has already been attached to outputDesc", __func__);
3922 return INVALID_OPERATION;
3923 }
3924 outputDesc->addClient(sourceDesc);
3925
3926 uint32_t delayMs = 0;
3927 status = startSource(outputDesc, sourceDesc, &delayMs);
3928
3929 if (status != NO_ERROR) {
3930 mpClientInterface->releaseAudioPatch(sourceDesc->patchDesc()->mAfPatchHandle, 0);
3931 outputDesc->removeClient(sourceDesc->portId());
3932 outputDesc->stop();
3933 return status;
3934 }
3935 sourceDesc->setSwOutput(outputDesc);
3936 if (delayMs != 0) {
3937 usleep(delayMs * 1000);
3938 }
3939 }
3940
3941 sourceDesc->patchDesc()->mAfPatchHandle = afPatchHandle;
3942 addAudioPatch(sourceDesc->patchDesc()->mHandle, sourceDesc->patchDesc());
3943
3944 return NO_ERROR;
3945 }
3946
stopAudioSource(audio_port_handle_t portId)3947 status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
3948 {
3949 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
3950 ALOGV("%s port ID %d", __FUNCTION__, portId);
3951 if (sourceDesc == 0) {
3952 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
3953 return BAD_VALUE;
3954 }
3955 status_t status = disconnectAudioSource(sourceDesc);
3956
3957 mAudioSources.removeItem(portId);
3958 return status;
3959 }
3960
setMasterMono(bool mono)3961 status_t AudioPolicyManager::setMasterMono(bool mono)
3962 {
3963 if (mMasterMono == mono) {
3964 return NO_ERROR;
3965 }
3966 mMasterMono = mono;
3967 // if enabling mono we close all offloaded devices, which will invalidate the
3968 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
3969 // for recreating the new AudioTrack as non-offloaded PCM.
3970 //
3971 // If disabling mono, we leave all tracks as is: we don't know which clients
3972 // and tracks are able to be recreated as offloaded. The next "song" should
3973 // play back offloaded.
3974 if (mMasterMono) {
3975 Vector<audio_io_handle_t> offloaded;
3976 for (size_t i = 0; i < mOutputs.size(); ++i) {
3977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3978 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
3979 offloaded.push(desc->mIoHandle);
3980 }
3981 }
3982 for (const auto& handle : offloaded) {
3983 closeOutput(handle);
3984 }
3985 }
3986 // update master mono for all remaining outputs
3987 for (size_t i = 0; i < mOutputs.size(); ++i) {
3988 updateMono(mOutputs.keyAt(i));
3989 }
3990 return NO_ERROR;
3991 }
3992
getMasterMono(bool * mono)3993 status_t AudioPolicyManager::getMasterMono(bool *mono)
3994 {
3995 *mono = mMasterMono;
3996 return NO_ERROR;
3997 }
3998
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)3999 float AudioPolicyManager::getStreamVolumeDB(
4000 audio_stream_type_t stream, int index, audio_devices_t device)
4001 {
4002 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, device);
4003 }
4004
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled,bool reported)4005 status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4006 audio_format_t *surroundFormats,
4007 bool *surroundFormatsEnabled,
4008 bool reported)
4009 {
4010 if (numSurroundFormats == NULL || (*numSurroundFormats != 0 &&
4011 (surroundFormats == NULL || surroundFormatsEnabled == NULL))) {
4012 return BAD_VALUE;
4013 }
4014 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p reported %d",
4015 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled, reported);
4016
4017 size_t formatsWritten = 0;
4018 size_t formatsMax = *numSurroundFormats;
4019 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4020 if (reported) {
4021 // Return formats from all device profiles that have already been resolved by
4022 // checkOutputsForDevice().
4023 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4024 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4025 FormatVector supportedFormats =
4026 device->getAudioPort()->getAudioProfiles().getSupportedFormats();
4027 for (size_t j = 0; j < supportedFormats.size(); j++) {
4028 if (mConfig.getSurroundFormats().count(supportedFormats[j]) != 0) {
4029 formats.insert(supportedFormats[j]);
4030 } else {
4031 for (const auto& pair : mConfig.getSurroundFormats()) {
4032 if (pair.second.count(supportedFormats[j]) != 0) {
4033 formats.insert(pair.first);
4034 break;
4035 }
4036 }
4037 }
4038 }
4039 }
4040 } else {
4041 for (const auto& pair : mConfig.getSurroundFormats()) {
4042 formats.insert(pair.first);
4043 }
4044 }
4045 *numSurroundFormats = formats.size();
4046 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4047 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
4048 for (const auto& format: formats) {
4049 if (formatsWritten < formatsMax) {
4050 surroundFormats[formatsWritten] = format;
4051 bool formatEnabled = true;
4052 switch (forceUse) {
4053 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
4054 formatEnabled = mManualSurroundFormats.count(format) != 0;
4055 break;
4056 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4057 formatEnabled = false;
4058 break;
4059 default: // AUTO or ALWAYS => true
4060 break;
4061 }
4062 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4063 }
4064 }
4065 return NO_ERROR;
4066 }
4067
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)4068 status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4069 {
4070 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
4071 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4072 if (formatIter == mConfig.getSurroundFormats().end()) {
4073 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
4074 return BAD_VALUE;
4075 }
4076
4077 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4078 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4079 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
4080 return INVALID_OPERATION;
4081 }
4082
4083 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
4084 return NO_ERROR;
4085 }
4086
4087 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
4088 if (enabled) {
4089 mManualSurroundFormats.insert(audioFormat);
4090 for (const auto& subFormat : formatIter->second) {
4091 mManualSurroundFormats.insert(subFormat);
4092 }
4093 } else {
4094 mManualSurroundFormats.erase(audioFormat);
4095 for (const auto& subFormat : formatIter->second) {
4096 mManualSurroundFormats.erase(subFormat);
4097 }
4098 }
4099
4100 sp<SwAudioOutputDescriptor> outputDesc;
4101 bool profileUpdated = false;
4102 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypeMask(
4103 AUDIO_DEVICE_OUT_HDMI);
4104 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4105 // Simulate reconnection to update enabled surround sound formats.
4106 String8 address = hdmiOutputDevices[i]->address();
4107 String8 name = hdmiOutputDevices[i]->getName();
4108 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4109 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4110 address.c_str(),
4111 name.c_str(),
4112 AUDIO_FORMAT_DEFAULT);
4113 if (status != NO_ERROR) {
4114 continue;
4115 }
4116 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4117 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4118 address.c_str(),
4119 name.c_str(),
4120 AUDIO_FORMAT_DEFAULT);
4121 profileUpdated |= (status == NO_ERROR);
4122 }
4123 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
4124 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromTypeMask(
4125 AUDIO_DEVICE_IN_HDMI);
4126 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4127 // Simulate reconnection to update enabled surround sound formats.
4128 String8 address = hdmiInputDevices[i]->address();
4129 String8 name = hdmiInputDevices[i]->getName();
4130 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4131 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4132 address.c_str(),
4133 name.c_str(),
4134 AUDIO_FORMAT_DEFAULT);
4135 if (status != NO_ERROR) {
4136 continue;
4137 }
4138 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4139 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4140 address.c_str(),
4141 name.c_str(),
4142 AUDIO_FORMAT_DEFAULT);
4143 profileUpdated |= (status == NO_ERROR);
4144 }
4145
4146 if (!profileUpdated) {
4147 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
4148 mManualSurroundFormats = std::move(surroundFormatsBackup);
4149 }
4150
4151 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4152 }
4153
setAppState(uid_t uid,app_state_t state)4154 void AudioPolicyManager::setAppState(uid_t uid, app_state_t state)
4155 {
4156 ALOGV("%s(uid:%d, state:%d)", __func__, uid, state);
4157 for (size_t i = 0; i < mInputs.size(); i++) {
4158 mInputs.valueAt(i)->setAppState(uid, state);
4159 }
4160 }
4161
isHapticPlaybackSupported()4162 bool AudioPolicyManager::isHapticPlaybackSupported()
4163 {
4164 for (const auto& hwModule : mHwModules) {
4165 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
4166 for (const auto &outProfile : outputProfiles) {
4167 struct audio_port audioPort;
4168 outProfile->toAudioPort(&audioPort);
4169 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
4170 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
4171 return true;
4172 }
4173 }
4174 }
4175 }
4176 return false;
4177 }
4178
disconnectAudioSource(const sp<SourceClientDescriptor> & sourceDesc)4179 status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
4180 {
4181 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
4182
4183 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(sourceDesc->patchDesc()->mHandle);
4184 if (patchDesc == 0) {
4185 ALOGW("%s source has no patch with handle %d", __FUNCTION__,
4186 sourceDesc->patchDesc()->mHandle);
4187 return BAD_VALUE;
4188 }
4189 removeAudioPatch(sourceDesc->patchDesc()->mHandle);
4190
4191 sp<SwAudioOutputDescriptor> swOutputDesc = sourceDesc->swOutput().promote();
4192 if (swOutputDesc != 0) {
4193 status_t status = stopSource(swOutputDesc, sourceDesc);
4194 if (status == NO_ERROR) {
4195 swOutputDesc->stop();
4196 }
4197 swOutputDesc->removeClient(sourceDesc->portId());
4198 mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4199 } else {
4200 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4201 if (hwOutputDesc != 0) {
4202 // release patch between src device and output device
4203 // close Hwoutput and remove from mHwOutputs
4204 } else {
4205 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4206 }
4207 }
4208 return NO_ERROR;
4209 }
4210
getSourceForAttributesOnOutput(audio_io_handle_t output,const audio_attributes_t & attr)4211 sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
4212 audio_io_handle_t output, const audio_attributes_t &attr)
4213 {
4214 sp<SourceClientDescriptor> source;
4215 for (size_t i = 0; i < mAudioSources.size(); i++) {
4216 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4217 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
4218 if (followsSameRouting(attr, sourceDesc->attributes()) &&
4219 outputDesc != 0 && outputDesc->mIoHandle == output) {
4220 source = sourceDesc;
4221 break;
4222 }
4223 }
4224 return source;
4225 }
4226
4227 // ----------------------------------------------------------------------------
4228 // AudioPolicyManager
4229 // ----------------------------------------------------------------------------
nextAudioPortGeneration()4230 uint32_t AudioPolicyManager::nextAudioPortGeneration()
4231 {
4232 return mAudioPortGeneration++;
4233 }
4234
4235 // Treblized audio policy xml config will be located in /odm/etc or /vendor/etc.
4236 static const char *kConfigLocationList[] =
4237 {"/odm/etc", "/vendor/etc", "/system/etc"};
4238 static const int kConfigLocationListSize =
4239 (sizeof(kConfigLocationList) / sizeof(kConfigLocationList[0]));
4240
deserializeAudioPolicyXmlConfig(AudioPolicyConfig & config)4241 static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
4242 char audioPolicyXmlConfigFile[AUDIO_POLICY_XML_CONFIG_FILE_PATH_MAX_LENGTH];
4243 std::vector<const char*> fileNames;
4244 status_t ret;
4245
4246 if (property_get_bool("ro.bluetooth.a2dp_offload.supported", false)) {
4247 if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false) &&
4248 property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4249 // Both BluetoothAudio@2.0 and BluetoothA2dp@1.0 (Offlaod) are disabled, and uses
4250 // the legacy hardware module for A2DP and hearing aid.
4251 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4252 } else if (property_get_bool("persist.bluetooth.a2dp_offload.disabled", false)) {
4253 // A2DP offload supported but disabled: try to use special XML file
4254 fileNames.push_back(AUDIO_POLICY_A2DP_OFFLOAD_DISABLED_XML_CONFIG_FILE_NAME);
4255 }
4256 } else if (property_get_bool("persist.bluetooth.bluetooth_audio_hal.disabled", false)) {
4257 fileNames.push_back(AUDIO_POLICY_BLUETOOTH_LEGACY_HAL_XML_CONFIG_FILE_NAME);
4258 }
4259 fileNames.push_back(AUDIO_POLICY_XML_CONFIG_FILE_NAME);
4260
4261 for (const char* fileName : fileNames) {
4262 for (int i = 0; i < kConfigLocationListSize; i++) {
4263 snprintf(audioPolicyXmlConfigFile, sizeof(audioPolicyXmlConfigFile),
4264 "%s/%s", kConfigLocationList[i], fileName);
4265 ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile, &config);
4266 if (ret == NO_ERROR) {
4267 config.setSource(audioPolicyXmlConfigFile);
4268 return ret;
4269 }
4270 }
4271 }
4272 return ret;
4273 }
4274
AudioPolicyManager(AudioPolicyClientInterface * clientInterface,bool)4275 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
4276 bool /*forTesting*/)
4277 :
4278 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
4279 mpClientInterface(clientInterface),
4280 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
4281 mA2dpSuspended(false),
4282 mConfig(mHwModulesAll, mAvailableOutputDevices, mAvailableInputDevices, mDefaultOutputDevice),
4283 mAudioPortGeneration(1),
4284 mBeaconMuteRefCount(0),
4285 mBeaconPlayingRefCount(0),
4286 mBeaconMuted(false),
4287 mTtsOutputAvailable(false),
4288 mMasterMono(false),
4289 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
4290 {
4291 }
4292
AudioPolicyManager(AudioPolicyClientInterface * clientInterface)4293 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
4294 : AudioPolicyManager(clientInterface, false /*forTesting*/)
4295 {
4296 loadConfig();
4297 initialize();
4298 }
4299
4300 // This check is to catch any legacy platform updating to Q without having
4301 // switched to XML since its deprecation on O.
4302 // TODO: after Q release, remove this check and flag as XML is now the only
4303 // option and all legacy platform should have transitioned to XML.
4304 #ifndef USE_XML_AUDIO_POLICY_CONF
4305 #error Audio policy no longer supports legacy .conf configuration format
4306 #endif
4307
loadConfig()4308 void AudioPolicyManager::loadConfig() {
4309 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
4310 ALOGE("could not load audio policy configuration file, setting defaults");
4311 getConfig().setDefault();
4312 }
4313 }
4314
initialize()4315 status_t AudioPolicyManager::initialize() {
4316 // Once policy config has been parsed, retrieve an instance of the engine and initialize it.
4317 audio_policy::EngineInstance *engineInstance = audio_policy::EngineInstance::getInstance();
4318 if (!engineInstance) {
4319 ALOGE("%s: Could not get an instance of policy engine", __FUNCTION__);
4320 return NO_INIT;
4321 }
4322 // Retrieve the Policy Manager Interface
4323 mEngine = engineInstance->queryInterface<AudioPolicyManagerInterface>();
4324 if (mEngine == NULL) {
4325 ALOGE("%s: Failed to get Policy Engine Interface", __FUNCTION__);
4326 return NO_INIT;
4327 }
4328 mEngine->setObserver(this);
4329 status_t status = mEngine->initCheck();
4330 if (status != NO_ERROR) {
4331 LOG_FATAL("Policy engine not initialized(err=%d)", status);
4332 return status;
4333 }
4334
4335 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
4336 // open all output streams needed to access attached devices
4337 for (const auto& hwModule : mHwModulesAll) {
4338 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
4339 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
4340 ALOGW("could not open HW module %s", hwModule->getName());
4341 continue;
4342 }
4343 mHwModules.push_back(hwModule);
4344 // open all output streams needed to access attached devices
4345 // except for direct output streams that are only opened when they are actually
4346 // required by an app.
4347 // This also validates mAvailableOutputDevices list
4348 for (const auto& outProfile : hwModule->getOutputProfiles()) {
4349 if (!outProfile->canOpenNewIo()) {
4350 ALOGE("Invalid Output profile max open count %u for profile %s",
4351 outProfile->maxOpenCount, outProfile->getTagName().c_str());
4352 continue;
4353 }
4354 if (!outProfile->hasSupportedDevices()) {
4355 ALOGW("Output profile contains no device on module %s", hwModule->getName());
4356 continue;
4357 }
4358 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0) {
4359 mTtsOutputAvailable = true;
4360 }
4361
4362 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
4363 continue;
4364 }
4365 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
4366 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableOutputDevices);
4367 sp<DeviceDescriptor> supportedDevice = 0;
4368 if (supportedDevices.contains(mDefaultOutputDevice)) {
4369 supportedDevice = mDefaultOutputDevice;
4370 } else {
4371 // choose first device present in profile's SupportedDevices also part of
4372 // mAvailableOutputDevices.
4373 if (availProfileDevices.isEmpty()) {
4374 continue;
4375 }
4376 supportedDevice = availProfileDevices.itemAt(0);
4377 }
4378 if (!mAvailableOutputDevices.contains(supportedDevice)) {
4379 continue;
4380 }
4381 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
4382 mpClientInterface);
4383 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4384 status_t status = outputDesc->open(nullptr, DeviceVector(supportedDevice),
4385 AUDIO_STREAM_DEFAULT,
4386 AUDIO_OUTPUT_FLAG_NONE, &output);
4387 if (status != NO_ERROR) {
4388 ALOGW("Cannot open output stream for devices %s on hw module %s",
4389 supportedDevice->toString().c_str(), hwModule->getName());
4390 continue;
4391 }
4392 for (const auto &device : availProfileDevices) {
4393 // give a valid ID to an attached device once confirmed it is reachable
4394 if (!device->isAttached()) {
4395 device->attach(hwModule);
4396 }
4397 }
4398 if (mPrimaryOutput == 0 &&
4399 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
4400 mPrimaryOutput = outputDesc;
4401 }
4402 addOutput(output, outputDesc);
4403 setOutputDevices(outputDesc,
4404 DeviceVector(supportedDevice),
4405 true,
4406 0,
4407 NULL);
4408 }
4409 // open input streams needed to access attached devices to validate
4410 // mAvailableInputDevices list
4411 for (const auto& inProfile : hwModule->getInputProfiles()) {
4412 if (!inProfile->canOpenNewIo()) {
4413 ALOGE("Invalid Input profile max open count %u for profile %s",
4414 inProfile->maxOpenCount, inProfile->getTagName().c_str());
4415 continue;
4416 }
4417 if (!inProfile->hasSupportedDevices()) {
4418 ALOGW("Input profile contains no device on module %s", hwModule->getName());
4419 continue;
4420 }
4421 // chose first device present in profile's SupportedDevices also part of
4422 // available input devices
4423 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
4424 DeviceVector availProfileDevices = supportedDevices.filter(mAvailableInputDevices);
4425 if (availProfileDevices.isEmpty()) {
4426 ALOGE("%s: Input device list is empty!", __FUNCTION__);
4427 continue;
4428 }
4429 sp<AudioInputDescriptor> inputDesc =
4430 new AudioInputDescriptor(inProfile, mpClientInterface);
4431
4432 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4433 status_t status = inputDesc->open(nullptr,
4434 availProfileDevices.itemAt(0),
4435 AUDIO_SOURCE_MIC,
4436 AUDIO_INPUT_FLAG_NONE,
4437 &input);
4438 if (status != NO_ERROR) {
4439 ALOGW("Cannot open input stream for device %s on hw module %s",
4440 availProfileDevices.toString().c_str(),
4441 hwModule->getName());
4442 continue;
4443 }
4444 for (const auto &device : availProfileDevices) {
4445 // give a valid ID to an attached device once confirmed it is reachable
4446 if (!device->isAttached()) {
4447 device->attach(hwModule);
4448 device->importAudioPort(inProfile, true);
4449 }
4450 }
4451 inputDesc->close();
4452 }
4453 }
4454 // make sure all attached devices have been allocated a unique ID
4455 auto checkAndSetAvailable = [this](auto& devices) {
4456 for (size_t i = 0; i < devices.size();) {
4457 const auto &device = devices[i];
4458 if (!device->isAttached()) {
4459 ALOGW("device %s is unreachable", device->toString().c_str());
4460 devices.remove(device);
4461 continue;
4462 }
4463 // Device is now validated and can be appended to the available devices of the engine
4464 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
4465 i++;
4466 }
4467 };
4468 checkAndSetAvailable(mAvailableOutputDevices);
4469 checkAndSetAvailable(mAvailableInputDevices);
4470
4471 // make sure default device is reachable
4472 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
4473 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
4474 mDefaultOutputDevice->toString().c_str());
4475 status = NO_INIT;
4476 }
4477 // If microphones address is empty, set it according to device type
4478 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
4479 if (mAvailableInputDevices[i]->address().isEmpty()) {
4480 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
4481 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BOTTOM_MICROPHONE_ADDRESS));
4482 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
4483 mAvailableInputDevices[i]->setAddress(String8(AUDIO_BACK_MICROPHONE_ADDRESS));
4484 }
4485 }
4486 }
4487
4488 if (mPrimaryOutput == 0) {
4489 ALOGE("Failed to open primary output");
4490 status = NO_INIT;
4491 }
4492
4493 // Silence ALOGV statements
4494 property_set("log.tag." LOG_TAG, "D");
4495
4496 updateDevicesAndOutputs();
4497 return status;
4498 }
4499
~AudioPolicyManager()4500 AudioPolicyManager::~AudioPolicyManager()
4501 {
4502 for (size_t i = 0; i < mOutputs.size(); i++) {
4503 mOutputs.valueAt(i)->close();
4504 }
4505 for (size_t i = 0; i < mInputs.size(); i++) {
4506 mInputs.valueAt(i)->close();
4507 }
4508 mAvailableOutputDevices.clear();
4509 mAvailableInputDevices.clear();
4510 mOutputs.clear();
4511 mInputs.clear();
4512 mHwModules.clear();
4513 mHwModulesAll.clear();
4514 mManualSurroundFormats.clear();
4515 }
4516
initCheck()4517 status_t AudioPolicyManager::initCheck()
4518 {
4519 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
4520 }
4521
4522 // ---
4523
addOutput(audio_io_handle_t output,const sp<SwAudioOutputDescriptor> & outputDesc)4524 void AudioPolicyManager::addOutput(audio_io_handle_t output,
4525 const sp<SwAudioOutputDescriptor>& outputDesc)
4526 {
4527 mOutputs.add(output, outputDesc);
4528 applyStreamVolumes(outputDesc, AUDIO_DEVICE_NONE, 0 /* delayMs */, true /* force */);
4529 updateMono(output); // update mono status when adding to output list
4530 selectOutputForMusicEffects();
4531 nextAudioPortGeneration();
4532 }
4533
removeOutput(audio_io_handle_t output)4534 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
4535 {
4536 mOutputs.removeItem(output);
4537 selectOutputForMusicEffects();
4538 }
4539
addInput(audio_io_handle_t input,const sp<AudioInputDescriptor> & inputDesc)4540 void AudioPolicyManager::addInput(audio_io_handle_t input,
4541 const sp<AudioInputDescriptor>& inputDesc)
4542 {
4543 mInputs.add(input, inputDesc);
4544 nextAudioPortGeneration();
4545 }
4546
checkOutputsForDevice(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state,SortedVector<audio_io_handle_t> & outputs)4547 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
4548 audio_policy_dev_state_t state,
4549 SortedVector<audio_io_handle_t>& outputs)
4550 {
4551 audio_devices_t deviceType = device->type();
4552 const String8 &address = device->address();
4553 sp<SwAudioOutputDescriptor> desc;
4554
4555 if (audio_device_is_digital(deviceType)) {
4556 // erase all current sample rates, formats and channel masks
4557 device->clearAudioProfiles();
4558 }
4559
4560 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4561 // first list already open outputs that can be routed to this device
4562 for (size_t i = 0; i < mOutputs.size(); i++) {
4563 desc = mOutputs.valueAt(i);
4564 if (!desc->isDuplicated() && desc->supportsDevice(device)
4565 && desc->deviceSupportsEncodedFormats(deviceType)) {
4566 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
4567 mOutputs.keyAt(i), device->toString().c_str());
4568 outputs.add(mOutputs.keyAt(i));
4569 }
4570 }
4571 // then look for output profiles that can be routed to this device
4572 SortedVector< sp<IOProfile> > profiles;
4573 for (const auto& hwModule : mHwModules) {
4574 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4575 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
4576 if (profile->supportsDevice(device)) {
4577 profiles.add(profile);
4578 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
4579 j, hwModule->getName());
4580 }
4581 }
4582 }
4583
4584 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
4585
4586 if (profiles.isEmpty() && outputs.isEmpty()) {
4587 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
4588 return BAD_VALUE;
4589 }
4590
4591 // open outputs for matching profiles if needed. Direct outputs are also opened to
4592 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4593 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4594 sp<IOProfile> profile = profiles[profile_index];
4595
4596 // nothing to do if one output is already opened for this profile
4597 size_t j;
4598 for (j = 0; j < outputs.size(); j++) {
4599 desc = mOutputs.valueFor(outputs.itemAt(j));
4600 if (!desc->isDuplicated() && desc->mProfile == profile) {
4601 // matching profile: save the sample rates, format and channel masks supported
4602 // by the profile in our device descriptor
4603 if (audio_device_is_digital(deviceType)) {
4604 device->importAudioPort(profile);
4605 }
4606 break;
4607 }
4608 }
4609 if (j != outputs.size()) {
4610 continue;
4611 }
4612
4613 if (!profile->canOpenNewIo()) {
4614 ALOGW("Max Output number %u already opened for this profile %s",
4615 profile->maxOpenCount, profile->getTagName().c_str());
4616 continue;
4617 }
4618
4619 ALOGV("opening output for device %08x with params %s profile %p name %s",
4620 deviceType, address.string(), profile.get(), profile->getName().string());
4621 desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
4622 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4623 status_t status = desc->open(nullptr, DeviceVector(device),
4624 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
4625
4626 if (status == NO_ERROR) {
4627 // Here is where the out_set_parameters() for card & device gets called
4628 if (!address.isEmpty()) {
4629 char *param = audio_device_address_to_parameter(deviceType, address);
4630 mpClientInterface->setParameters(output, String8(param));
4631 free(param);
4632 }
4633 updateAudioProfiles(device, output, profile->getAudioProfiles());
4634 if (!profile->hasValidAudioProfile()) {
4635 ALOGW("checkOutputsForDevice() missing param");
4636 desc->close();
4637 output = AUDIO_IO_HANDLE_NONE;
4638 } else if (profile->hasDynamicAudioProfile()) {
4639 desc->close();
4640 output = AUDIO_IO_HANDLE_NONE;
4641 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4642 profile->pickAudioProfile(
4643 config.sample_rate, config.channel_mask, config.format);
4644 config.offload_info.sample_rate = config.sample_rate;
4645 config.offload_info.channel_mask = config.channel_mask;
4646 config.offload_info.format = config.format;
4647
4648 status_t status = desc->open(&config, DeviceVector(device),
4649 AUDIO_STREAM_DEFAULT,
4650 AUDIO_OUTPUT_FLAG_NONE, &output);
4651 if (status != NO_ERROR) {
4652 output = AUDIO_IO_HANDLE_NONE;
4653 }
4654 }
4655
4656 if (output != AUDIO_IO_HANDLE_NONE) {
4657 addOutput(output, desc);
4658 if (device_distinguishes_on_address(deviceType) && address != "0") {
4659 sp<AudioPolicyMix> policyMix;
4660 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix)
4661 == NO_ERROR) {
4662 policyMix->setOutput(desc);
4663 desc->mPolicyMix = policyMix;
4664 } else {
4665 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
4666 address.string());
4667 }
4668
4669 } else if (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
4670 hasPrimaryOutput()) {
4671 // no duplicated output for direct outputs and
4672 // outputs used by dynamic policy mixes
4673 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
4674
4675 //TODO: configure audio effect output stage here
4676
4677 // open a duplicating output thread for the new output and the primary output
4678 sp<SwAudioOutputDescriptor> dupOutputDesc =
4679 new SwAudioOutputDescriptor(NULL, mpClientInterface);
4680 status_t status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc,
4681 &duplicatedOutput);
4682 if (status == NO_ERROR) {
4683 // add duplicated output descriptor
4684 addOutput(duplicatedOutput, dupOutputDesc);
4685 } else {
4686 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
4687 mPrimaryOutput->mIoHandle, output);
4688 desc->close();
4689 removeOutput(output);
4690 nextAudioPortGeneration();
4691 output = AUDIO_IO_HANDLE_NONE;
4692 }
4693 }
4694 }
4695 } else {
4696 output = AUDIO_IO_HANDLE_NONE;
4697 }
4698 if (output == AUDIO_IO_HANDLE_NONE) {
4699 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
4700 profiles.removeAt(profile_index);
4701 profile_index--;
4702 } else {
4703 outputs.add(output);
4704 // Load digital format info only for digital devices
4705 if (audio_device_is_digital(deviceType)) {
4706 device->importAudioPort(profile);
4707 }
4708
4709 if (device_distinguishes_on_address(deviceType)) {
4710 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
4711 device->toString().c_str());
4712 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
4713 NULL/*patch handle*/);
4714 }
4715 ALOGV("checkOutputsForDevice(): adding output %d", output);
4716 }
4717 }
4718
4719 if (profiles.isEmpty()) {
4720 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
4721 return BAD_VALUE;
4722 }
4723 } else { // Disconnect
4724 // check if one opened output is not needed any more after disconnecting one device
4725 for (size_t i = 0; i < mOutputs.size(); i++) {
4726 desc = mOutputs.valueAt(i);
4727 if (!desc->isDuplicated()) {
4728 // exact match on device
4729 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
4730 && desc->deviceSupportsEncodedFormats(deviceType)) {
4731 outputs.add(mOutputs.keyAt(i));
4732 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
4733 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
4734 mOutputs.keyAt(i));
4735 outputs.add(mOutputs.keyAt(i));
4736 }
4737 }
4738 }
4739 // Clear any profiles associated with the disconnected device.
4740 for (const auto& hwModule : mHwModules) {
4741 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
4742 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
4743 if (profile->supportsDevice(device)) {
4744 ALOGV("checkOutputsForDevice(): "
4745 "clearing direct output profile %zu on module %s",
4746 j, hwModule->getName());
4747 profile->clearAudioProfiles();
4748 }
4749 }
4750 }
4751 }
4752 return NO_ERROR;
4753 }
4754
checkInputsForDevice(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state)4755 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
4756 audio_policy_dev_state_t state)
4757 {
4758 sp<AudioInputDescriptor> desc;
4759
4760 if (audio_device_is_digital(device->type())) {
4761 // erase all current sample rates, formats and channel masks
4762 device->clearAudioProfiles();
4763 }
4764
4765 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4766 // look for input profiles that can be routed to this device
4767 SortedVector< sp<IOProfile> > profiles;
4768 for (const auto& hwModule : mHwModules) {
4769 for (size_t profile_index = 0;
4770 profile_index < hwModule->getInputProfiles().size();
4771 profile_index++) {
4772 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
4773
4774 if (profile->supportsDevice(device)) {
4775 profiles.add(profile);
4776 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
4777 profile_index, hwModule->getName());
4778 }
4779 }
4780 }
4781
4782 if (profiles.isEmpty()) {
4783 ALOGW("%s: No input profile available for device %s",
4784 __func__, device->toString().c_str());
4785 return BAD_VALUE;
4786 }
4787
4788 // open inputs for matching profiles if needed. Direct inputs are also opened to
4789 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
4790 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
4791
4792 sp<IOProfile> profile = profiles[profile_index];
4793
4794 // nothing to do if one input is already opened for this profile
4795 size_t input_index;
4796 for (input_index = 0; input_index < mInputs.size(); input_index++) {
4797 desc = mInputs.valueAt(input_index);
4798 if (desc->mProfile == profile) {
4799 if (audio_device_is_digital(device->type())) {
4800 device->importAudioPort(profile);
4801 }
4802 break;
4803 }
4804 }
4805 if (input_index != mInputs.size()) {
4806 continue;
4807 }
4808
4809 if (!profile->canOpenNewIo()) {
4810 ALOGW("Max Input number %u already opened for this profile %s",
4811 profile->maxOpenCount, profile->getTagName().c_str());
4812 continue;
4813 }
4814
4815 desc = new AudioInputDescriptor(profile, mpClientInterface);
4816 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
4817 status_t status = desc->open(nullptr,
4818 device,
4819 AUDIO_SOURCE_MIC,
4820 AUDIO_INPUT_FLAG_NONE,
4821 &input);
4822
4823 if (status == NO_ERROR) {
4824 const String8& address = device->address();
4825 if (!address.isEmpty()) {
4826 char *param = audio_device_address_to_parameter(device->type(), address);
4827 mpClientInterface->setParameters(input, String8(param));
4828 free(param);
4829 }
4830 updateAudioProfiles(device, input, profile->getAudioProfiles());
4831 if (!profile->hasValidAudioProfile()) {
4832 ALOGW("checkInputsForDevice() direct input missing param");
4833 desc->close();
4834 input = AUDIO_IO_HANDLE_NONE;
4835 }
4836
4837 if (input != AUDIO_IO_HANDLE_NONE) {
4838 addInput(input, desc);
4839 }
4840 } // endif input != 0
4841
4842 if (input == AUDIO_IO_HANDLE_NONE) {
4843 ALOGW("%s could not open input for device %s", __func__,
4844 device->toString().c_str());
4845 profiles.removeAt(profile_index);
4846 profile_index--;
4847 } else {
4848 if (audio_device_is_digital(device->type())) {
4849 device->importAudioPort(profile);
4850 }
4851 ALOGV("checkInputsForDevice(): adding input %d", input);
4852 }
4853 } // end scan profiles
4854
4855 if (profiles.isEmpty()) {
4856 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
4857 return BAD_VALUE;
4858 }
4859 } else {
4860 // Disconnect
4861 // Clear any profiles associated with the disconnected device.
4862 for (const auto& hwModule : mHwModules) {
4863 for (size_t profile_index = 0;
4864 profile_index < hwModule->getInputProfiles().size();
4865 profile_index++) {
4866 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
4867 if (profile->supportsDevice(device)) {
4868 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
4869 profile_index, hwModule->getName());
4870 profile->clearAudioProfiles();
4871 }
4872 }
4873 }
4874 } // end disconnect
4875
4876 return NO_ERROR;
4877 }
4878
4879
closeOutput(audio_io_handle_t output)4880 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
4881 {
4882 ALOGV("closeOutput(%d)", output);
4883
4884 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
4885 if (closingOutput == NULL) {
4886 ALOGW("closeOutput() unknown output %d", output);
4887 return;
4888 }
4889 const bool closingOutputWasActive = closingOutput->isActive();
4890 mPolicyMixes.closeOutput(closingOutput);
4891
4892 // look for duplicated outputs connected to the output being removed.
4893 for (size_t i = 0; i < mOutputs.size(); i++) {
4894 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
4895 if (dupOutput->isDuplicated() &&
4896 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
4897 sp<SwAudioOutputDescriptor> remainingOutput =
4898 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
4899 // As all active tracks on duplicated output will be deleted,
4900 // and as they were also referenced on the other output, the reference
4901 // count for their stream type must be adjusted accordingly on
4902 // the other output.
4903 const bool wasActive = remainingOutput->isActive();
4904 // Note: no-op on the closing output where all clients has already been set inactive
4905 dupOutput->setAllClientsInactive();
4906 // stop() will be a no op if the output is still active but is needed in case all
4907 // active streams refcounts where cleared above
4908 if (wasActive) {
4909 remainingOutput->stop();
4910 }
4911 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4912 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4913
4914 mpClientInterface->closeOutput(duplicatedOutput);
4915 removeOutput(duplicatedOutput);
4916 }
4917 }
4918
4919 nextAudioPortGeneration();
4920
4921 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
4922 if (index >= 0) {
4923 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4924 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4925 mAudioPatches.removeItemsAt(index);
4926 mpClientInterface->onAudioPatchListUpdate();
4927 }
4928
4929 if (closingOutputWasActive) {
4930 closingOutput->stop();
4931 }
4932 closingOutput->close();
4933
4934 removeOutput(output);
4935 mPreviousOutputs = mOutputs;
4936
4937 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
4938 // no direct outputs are open.
4939 if (!getMsdAudioOutDevices().isEmpty()) {
4940 bool directOutputOpen = false;
4941 for (size_t i = 0; i < mOutputs.size(); i++) {
4942 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
4943 directOutputOpen = true;
4944 break;
4945 }
4946 }
4947 if (!directOutputOpen) {
4948 ALOGV("no direct outputs open, reset MSD patch");
4949 setMsdPatch();
4950 }
4951 }
4952
4953 cleanUpEffectsForIo(output);
4954 }
4955
closeInput(audio_io_handle_t input)4956 void AudioPolicyManager::closeInput(audio_io_handle_t input)
4957 {
4958 ALOGV("closeInput(%d)", input);
4959
4960 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4961 if (inputDesc == NULL) {
4962 ALOGW("closeInput() unknown input %d", input);
4963 return;
4964 }
4965
4966 nextAudioPortGeneration();
4967
4968 sp<DeviceDescriptor> device = inputDesc->getDevice();
4969 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
4970 if (index >= 0) {
4971 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4972 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4973 mAudioPatches.removeItemsAt(index);
4974 mpClientInterface->onAudioPatchListUpdate();
4975 }
4976
4977 inputDesc->close();
4978 mInputs.removeItem(input);
4979
4980 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
4981 if (primaryInputDevices.contains(device) &&
4982 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
4983 SoundTrigger::setCaptureState(false);
4984 }
4985
4986 cleanUpEffectsForIo(input);
4987 }
4988
getOutputsForDevices(const DeviceVector & devices,const SwAudioOutputCollection & openOutputs)4989 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
4990 const DeviceVector &devices,
4991 const SwAudioOutputCollection& openOutputs)
4992 {
4993 SortedVector<audio_io_handle_t> outputs;
4994
4995 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
4996 for (size_t i = 0; i < openOutputs.size(); i++) {
4997 ALOGVV("output %zu isDuplicated=%d device=%s",
4998 i, openOutputs.valueAt(i)->isDuplicated(),
4999 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
5000 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
5001 && openOutputs.valueAt(i)->deviceSupportsEncodedFormats(devices.types())) {
5002 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
5003 outputs.add(openOutputs.keyAt(i));
5004 }
5005 }
5006 return outputs;
5007 }
5008
checkForDeviceAndOutputChanges(std::function<bool ()> onOutputsChecked)5009 void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
5010 {
5011 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
5012 // output is suspended before any tracks are moved to it
5013 checkA2dpSuspend();
5014 checkOutputForAllStrategies();
5015 checkSecondaryOutputs();
5016 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
5017 updateDevicesAndOutputs();
5018 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
5019 setMsdPatch();
5020 }
5021 }
5022
followsSameRouting(const audio_attributes_t & lAttr,const audio_attributes_t & rAttr) const5023 bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
5024 const audio_attributes_t &rAttr) const
5025 {
5026 return mEngine->getProductStrategyForAttributes(lAttr) ==
5027 mEngine->getProductStrategyForAttributes(rAttr);
5028 }
5029
checkOutputForAttributes(const audio_attributes_t & attr)5030 void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
5031 {
5032 auto psId = mEngine->getProductStrategyForAttributes(attr);
5033
5034 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
5035 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
5036 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
5037 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
5038
5039 // also take into account external policy-related changes: add all outputs which are
5040 // associated with policies in the "before" and "after" output vectors
5041 ALOGVV("%s(): policy related outputs", __func__);
5042 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
5043 const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
5044 if (desc != 0 && desc->mPolicyMix != NULL) {
5045 srcOutputs.add(desc->mIoHandle);
5046 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
5047 }
5048 }
5049 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
5050 const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5051 if (desc != 0 && desc->mPolicyMix != NULL) {
5052 dstOutputs.add(desc->mIoHandle);
5053 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
5054 }
5055 }
5056
5057 if (srcOutputs != dstOutputs) {
5058 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
5059 // audio from invalidated tracks will be rendered when unmuting
5060 uint32_t maxLatency = 0;
5061 for (audio_io_handle_t srcOut : srcOutputs) {
5062 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
5063 if (desc != 0 && maxLatency < desc->latency()) {
5064 maxLatency = desc->latency();
5065 }
5066 }
5067 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
5068 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
5069 std::to_string(srcOutputs[0]).c_str(),
5070 std::to_string(dstOutputs[0]).c_str());
5071 // mute strategy while moving tracks from one output to another
5072 for (audio_io_handle_t srcOut : srcOutputs) {
5073 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
5074 if (desc != 0 && desc->isStrategyActive(psId)) {
5075 setStrategyMute(psId, true, desc);
5076 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
5077 newDevices.types());
5078 }
5079 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
5080 if (source != 0){
5081 connectAudioSource(source);
5082 }
5083 }
5084
5085 // Move effects associated to this stream from previous output to new output
5086 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
5087 selectOutputForMusicEffects();
5088 }
5089 // Move tracks associated to this stream (and linked) from previous output to new output
5090 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
5091 mpClientInterface->invalidateStream(stream);
5092 }
5093 }
5094 }
5095
checkOutputForAllStrategies()5096 void AudioPolicyManager::checkOutputForAllStrategies()
5097 {
5098 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
5099 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
5100 checkOutputForAttributes(attributes);
5101 }
5102 }
5103
checkSecondaryOutputs()5104 void AudioPolicyManager::checkSecondaryOutputs() {
5105 std::set<audio_stream_type_t> streamsToInvalidate;
5106 for (size_t i = 0; i < mOutputs.size(); i++) {
5107 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
5108 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
5109 sp<SwAudioOutputDescriptor> desc;
5110 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
5111 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
5112 client->flags(), desc, &secondaryDescs);
5113 if (status != OK ||
5114 !std::equal(client->getSecondaryOutputs().begin(),
5115 client->getSecondaryOutputs().end(),
5116 secondaryDescs.begin(), secondaryDescs.end())) {
5117 streamsToInvalidate.insert(client->stream());
5118 }
5119 }
5120 }
5121 for (audio_stream_type_t stream : streamsToInvalidate) {
5122 ALOGD("%s Invalidate stream %d due to secondary output change", __func__, stream);
5123 mpClientInterface->invalidateStream(stream);
5124 }
5125 }
5126
checkA2dpSuspend()5127 void AudioPolicyManager::checkA2dpSuspend()
5128 {
5129 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
5130 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
5131 mA2dpSuspended = false;
5132 return;
5133 }
5134
5135 bool isScoConnected =
5136 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
5137 ~AUDIO_DEVICE_BIT_IN) != 0) ||
5138 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
5139
5140 // if suspended, restore A2DP output if:
5141 // ((SCO device is NOT connected) ||
5142 // ((forced usage communication is NOT SCO) && (forced usage for record is NOT SCO) &&
5143 // (phone state is NOT in call) && (phone state is NOT ringing)))
5144 //
5145 // if not suspended, suspend A2DP output if:
5146 // (SCO device is connected) &&
5147 // ((forced usage for communication is SCO) || (forced usage for record is SCO) ||
5148 // ((phone state is in call) || (phone state is ringing)))
5149 //
5150 if (mA2dpSuspended) {
5151 if (!isScoConnected ||
5152 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) !=
5153 AUDIO_POLICY_FORCE_BT_SCO) &&
5154 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) !=
5155 AUDIO_POLICY_FORCE_BT_SCO) &&
5156 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
5157 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
5158
5159 mpClientInterface->restoreOutput(a2dpOutput);
5160 mA2dpSuspended = false;
5161 }
5162 } else {
5163 if (isScoConnected &&
5164 ((mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ==
5165 AUDIO_POLICY_FORCE_BT_SCO) ||
5166 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_RECORD) ==
5167 AUDIO_POLICY_FORCE_BT_SCO) ||
5168 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
5169 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
5170
5171 mpClientInterface->suspendOutput(a2dpOutput);
5172 mA2dpSuspended = true;
5173 }
5174 }
5175 }
5176
getNewOutputDevices(const sp<SwAudioOutputDescriptor> & outputDesc,bool fromCache)5177 DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5178 bool fromCache)
5179 {
5180 DeviceVector devices;
5181
5182 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
5183 if (index >= 0) {
5184 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5185 if (patchDesc->mUid != mUidCached) {
5186 ALOGV("%s device %s forced by patch %d", __func__,
5187 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
5188 return outputDesc->devices();
5189 }
5190 }
5191
5192 // Honor explicit routing requests only if no client using default routing is active on this
5193 // input: a specific app can not force routing for other apps by setting a preferred device.
5194 bool active; // unused
5195 sp<DeviceDescriptor> device =
5196 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
5197 if (device != nullptr) {
5198 return DeviceVector(device);
5199 }
5200
5201 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
5202 // of setForceUse / Default Bus device here
5203 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
5204 if (device != nullptr) {
5205 return DeviceVector(device);
5206 }
5207
5208 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
5209 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
5210 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5211
5212 if ((hasVoiceStream(streams) &&
5213 (isInCall() || mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) ||
5214 ((hasStream(streams, AUDIO_STREAM_ALARM) || hasStream(streams, AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5215 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) ||
5216 outputDesc->isStrategyActive(productStrategy)) {
5217 // Retrieval of devices for voice DL is done on primary output profile, cannot
5218 // check the route (would force modifying configuration file for this profile)
5219 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
5220 break;
5221 }
5222 }
5223 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
5224 return devices;
5225 }
5226
getNewInputDevice(const sp<AudioInputDescriptor> & inputDesc)5227 sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
5228 const sp<AudioInputDescriptor>& inputDesc)
5229 {
5230 sp<DeviceDescriptor> device;
5231
5232 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
5233 if (index >= 0) {
5234 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5235 if (patchDesc->mUid != mUidCached) {
5236 ALOGV("getNewInputDevice() device %s forced by patch %d",
5237 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
5238 return inputDesc->getDevice();
5239 }
5240 }
5241
5242 // Honor explicit routing requests only if no client using default routing is active on this
5243 // input: a specific app can not force routing for other apps by setting a preferred device.
5244 bool active;
5245 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
5246 if (device != nullptr) {
5247 return device;
5248 }
5249
5250 // If we are not in call and no client is active on this input, this methods returns
5251 // a null sp<>, causing the patch on the input stream to be released.
5252 audio_attributes_t attributes = inputDesc->getHighestPriorityAttributes();
5253 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
5254 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
5255 }
5256 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
5257 device = mEngine->getInputDeviceForAttributes(attributes);
5258 }
5259
5260 return device;
5261 }
5262
streamsMatchForvolume(audio_stream_type_t stream1,audio_stream_type_t stream2)5263 bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
5264 audio_stream_type_t stream2) {
5265 return (stream1 == stream2);
5266 }
5267
getDevicesForStream(audio_stream_type_t stream)5268 audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
5269 // By checking the range of stream before calling getStrategy, we avoid
5270 // getOutputDevicesForStream's behavior for invalid streams.
5271 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
5272 // device for music stream), but we want to return the empty set.
5273 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
5274 return AUDIO_DEVICE_NONE;
5275 }
5276 DeviceVector activeDevices;
5277 DeviceVector devices;
5278 for (audio_stream_type_t curStream = AUDIO_STREAM_MIN; curStream < AUDIO_STREAM_PUBLIC_CNT;
5279 curStream = (audio_stream_type_t) (curStream + 1)) {
5280 if (!streamsMatchForvolume(stream, curStream)) {
5281 continue;
5282 }
5283 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
5284 devices.merge(curDevices);
5285 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
5286 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
5287 if (outputDesc->isActive(toVolumeSource(curStream))) {
5288 activeDevices.merge(outputDesc->devices());
5289 }
5290 }
5291 }
5292
5293 // Favor devices selected on active streams if any to report correct device in case of
5294 // explicit device selection
5295 if (!activeDevices.isEmpty()) {
5296 devices = activeDevices;
5297 }
5298 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
5299 and doesn't really need to.*/
5300 DeviceVector speakerSafeDevices = devices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
5301 if (!speakerSafeDevices.isEmpty()) {
5302 devices.merge(mAvailableOutputDevices.getDevicesFromTypeMask(AUDIO_DEVICE_OUT_SPEAKER));
5303 devices.remove(speakerSafeDevices);
5304 }
5305 return devices.types();
5306 }
5307
handleNotificationRoutingForStream(audio_stream_type_t stream)5308 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
5309 switch(stream) {
5310 case AUDIO_STREAM_MUSIC:
5311 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
5312 updateDevicesAndOutputs();
5313 break;
5314 default:
5315 break;
5316 }
5317 }
5318
handleEventForBeacon(int event)5319 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
5320
5321 // skip beacon mute management if a dedicated TTS output is available
5322 if (mTtsOutputAvailable) {
5323 return 0;
5324 }
5325
5326 switch(event) {
5327 case STARTING_OUTPUT:
5328 mBeaconMuteRefCount++;
5329 break;
5330 case STOPPING_OUTPUT:
5331 if (mBeaconMuteRefCount > 0) {
5332 mBeaconMuteRefCount--;
5333 }
5334 break;
5335 case STARTING_BEACON:
5336 mBeaconPlayingRefCount++;
5337 break;
5338 case STOPPING_BEACON:
5339 if (mBeaconPlayingRefCount > 0) {
5340 mBeaconPlayingRefCount--;
5341 }
5342 break;
5343 }
5344
5345 if (mBeaconMuteRefCount > 0) {
5346 // any playback causes beacon to be muted
5347 return setBeaconMute(true);
5348 } else {
5349 // no other playback: unmute when beacon starts playing, mute when it stops
5350 return setBeaconMute(mBeaconPlayingRefCount == 0);
5351 }
5352 }
5353
setBeaconMute(bool mute)5354 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
5355 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
5356 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
5357 // keep track of muted state to avoid repeating mute/unmute operations
5358 if (mBeaconMuted != mute) {
5359 // mute/unmute AUDIO_STREAM_TTS on all outputs
5360 ALOGV("\t muting %d", mute);
5361 uint32_t maxLatency = 0;
5362 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
5363 for (size_t i = 0; i < mOutputs.size(); i++) {
5364 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5365 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, AUDIO_DEVICE_NONE);
5366 const uint32_t latency = desc->latency() * 2;
5367 if (latency > maxLatency) {
5368 maxLatency = latency;
5369 }
5370 }
5371 mBeaconMuted = mute;
5372 return maxLatency;
5373 }
5374 return 0;
5375 }
5376
updateDevicesAndOutputs()5377 void AudioPolicyManager::updateDevicesAndOutputs()
5378 {
5379 mEngine->updateDeviceSelectionCache();
5380 mPreviousOutputs = mOutputs;
5381 }
5382
checkDeviceMuteStrategies(const sp<AudioOutputDescriptor> & outputDesc,const DeviceVector & prevDevices,uint32_t delayMs)5383 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
5384 const DeviceVector &prevDevices,
5385 uint32_t delayMs)
5386 {
5387 // mute/unmute strategies using an incompatible device combination
5388 // if muting, wait for the audio in pcm buffer to be drained before proceeding
5389 // if unmuting, unmute only after the specified delay
5390 if (outputDesc->isDuplicated()) {
5391 return 0;
5392 }
5393
5394 uint32_t muteWaitMs = 0;
5395 DeviceVector devices = outputDesc->devices();
5396 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
5397
5398 auto productStrategies = mEngine->getOrderedProductStrategies();
5399 for (const auto &productStrategy : productStrategies) {
5400 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
5401 DeviceVector curDevices =
5402 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
5403 curDevices = curDevices.filter(outputDesc->supportedDevices());
5404 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
5405 bool doMute = false;
5406
5407 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
5408 doMute = true;
5409 outputDesc->setStrategyMutedByDevice(productStrategy, true);
5410 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
5411 doMute = true;
5412 outputDesc->setStrategyMutedByDevice(productStrategy, false);
5413 }
5414 if (doMute) {
5415 for (size_t j = 0; j < mOutputs.size(); j++) {
5416 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
5417 // skip output if it does not share any device with current output
5418 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
5419 continue;
5420 }
5421 ALOGVV("%s() %s (curDevice %s)", __func__,
5422 mute ? "muting" : "unmuting", curDevices.toString().c_str());
5423 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
5424 if (desc->isStrategyActive(productStrategy)) {
5425 if (mute) {
5426 // FIXME: should not need to double latency if volume could be applied
5427 // immediately by the audioflinger mixer. We must account for the delay
5428 // between now and the next time the audioflinger thread for this output
5429 // will process a buffer (which corresponds to one buffer size,
5430 // usually 1/2 or 1/4 of the latency).
5431 if (muteWaitMs < desc->latency() * 2) {
5432 muteWaitMs = desc->latency() * 2;
5433 }
5434 }
5435 }
5436 }
5437 }
5438 }
5439
5440 // temporary mute output if device selection changes to avoid volume bursts due to
5441 // different per device volumes
5442 if (outputDesc->isActive() && (devices != prevDevices)) {
5443 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
5444 // temporary mute duration is conservatively set to 4 times the reported latency
5445 uint32_t tempMuteDurationMs = outputDesc->latency() * 4;
5446 if (muteWaitMs < tempMuteWaitMs) {
5447 muteWaitMs = tempMuteWaitMs;
5448 }
5449 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
5450 // make sure that we do not start the temporary mute period too early in case of
5451 // delayed device change
5452 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
5453 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
5454 devices.types());
5455 }
5456 }
5457
5458 // wait for the PCM output buffers to empty before proceeding with the rest of the command
5459 if (muteWaitMs > delayMs) {
5460 muteWaitMs -= delayMs;
5461 usleep(muteWaitMs * 1000);
5462 return muteWaitMs;
5463 }
5464 return 0;
5465 }
5466
setOutputDevices(const sp<SwAudioOutputDescriptor> & outputDesc,const DeviceVector & devices,bool force,int delayMs,audio_patch_handle_t * patchHandle,bool requiresMuteCheck)5467 uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
5468 const DeviceVector &devices,
5469 bool force,
5470 int delayMs,
5471 audio_patch_handle_t *patchHandle,
5472 bool requiresMuteCheck)
5473 {
5474 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
5475 uint32_t muteWaitMs;
5476
5477 if (outputDesc->isDuplicated()) {
5478 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
5479 nullptr /* patchHandle */, requiresMuteCheck);
5480 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
5481 nullptr /* patchHandle */, requiresMuteCheck);
5482 return muteWaitMs;
5483 }
5484
5485 // filter devices according to output selected
5486 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
5487 DeviceVector prevDevices = outputDesc->devices();
5488
5489 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
5490 // output profile or if new device is not supported AND previous device(s) is(are) still
5491 // available (otherwise reset device must be done on the output)
5492 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
5493 !mAvailableOutputDevices.filter(prevDevices).empty()) {
5494 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
5495 return 0;
5496 }
5497
5498 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
5499
5500 if (!filteredDevices.isEmpty()) {
5501 outputDesc->setDevices(filteredDevices);
5502 }
5503
5504 // if the outputs are not materially active, there is no need to mute.
5505 if (requiresMuteCheck) {
5506 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
5507 } else {
5508 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
5509 muteWaitMs = 0;
5510 }
5511
5512 // Do not change the routing if:
5513 // the requested device is AUDIO_DEVICE_NONE
5514 // OR the requested device is the same as current device
5515 // AND force is not specified
5516 // AND the output is connected by a valid audio patch.
5517 // Doing this check here allows the caller to call setOutputDevices() without conditions
5518 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
5519 !force && outputDesc->getPatchHandle() != 0) {
5520 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
5521 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
5522 return muteWaitMs;
5523 }
5524
5525 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
5526
5527 // do the routing
5528 if (filteredDevices.isEmpty()) {
5529 resetOutputDevice(outputDesc, delayMs, NULL);
5530 } else {
5531 PatchBuilder patchBuilder;
5532 patchBuilder.addSource(outputDesc);
5533 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
5534 for (const auto &filteredDevice : filteredDevices) {
5535 patchBuilder.addSink(filteredDevice);
5536 }
5537
5538 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), delayMs);
5539 }
5540
5541 // update stream volumes according to new device
5542 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
5543
5544 return muteWaitMs;
5545 }
5546
resetOutputDevice(const sp<AudioOutputDescriptor> & outputDesc,int delayMs,audio_patch_handle_t * patchHandle)5547 status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
5548 int delayMs,
5549 audio_patch_handle_t *patchHandle)
5550 {
5551 ssize_t index;
5552 if (patchHandle) {
5553 index = mAudioPatches.indexOfKey(*patchHandle);
5554 } else {
5555 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
5556 }
5557 if (index < 0) {
5558 return INVALID_OPERATION;
5559 }
5560 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5561 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
5562 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5563 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
5564 removeAudioPatch(patchDesc->mHandle);
5565 nextAudioPortGeneration();
5566 mpClientInterface->onAudioPatchListUpdate();
5567 return status;
5568 }
5569
setInputDevice(audio_io_handle_t input,const sp<DeviceDescriptor> & device,bool force,audio_patch_handle_t * patchHandle)5570 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5571 const sp<DeviceDescriptor> &device,
5572 bool force,
5573 audio_patch_handle_t *patchHandle)
5574 {
5575 status_t status = NO_ERROR;
5576
5577 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5578 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
5579 inputDesc->setDevice(device);
5580
5581 if (mAvailableInputDevices.contains(device)) {
5582 PatchBuilder patchBuilder;
5583 patchBuilder.addSink(inputDesc,
5584 // AUDIO_SOURCE_HOTWORD is for internal use only:
5585 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
5586 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
5587 auto result = usecase;
5588 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
5589 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5590 }
5591 return result; }).
5592 //only one input device for now
5593 addSource(device);
5594 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
5595 }
5596 }
5597 return status;
5598 }
5599
resetInputDevice(audio_io_handle_t input,audio_patch_handle_t * patchHandle)5600 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5601 audio_patch_handle_t *patchHandle)
5602 {
5603 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5604 ssize_t index;
5605 if (patchHandle) {
5606 index = mAudioPatches.indexOfKey(*patchHandle);
5607 } else {
5608 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
5609 }
5610 if (index < 0) {
5611 return INVALID_OPERATION;
5612 }
5613 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5614 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
5615 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5616 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
5617 removeAudioPatch(patchDesc->mHandle);
5618 nextAudioPortGeneration();
5619 mpClientInterface->onAudioPatchListUpdate();
5620 return status;
5621 }
5622
getInputProfile(const sp<DeviceDescriptor> & device,uint32_t & samplingRate,audio_format_t & format,audio_channel_mask_t & channelMask,audio_input_flags_t flags)5623 sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
5624 uint32_t& samplingRate,
5625 audio_format_t& format,
5626 audio_channel_mask_t& channelMask,
5627 audio_input_flags_t flags)
5628 {
5629 // Choose an input profile based on the requested capture parameters: select the first available
5630 // profile supporting all requested parameters.
5631 //
5632 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
5633 // the best matching profile, not the first one.
5634
5635 sp<IOProfile> firstInexact;
5636 uint32_t updatedSamplingRate = 0;
5637 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
5638 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
5639 for (const auto& hwModule : mHwModules) {
5640 for (const auto& profile : hwModule->getInputProfiles()) {
5641 // profile->log();
5642 //updatedFormat = format;
5643 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
5644 &samplingRate /*updatedSamplingRate*/,
5645 format,
5646 &format, /*updatedFormat*/
5647 channelMask,
5648 &channelMask /*updatedChannelMask*/,
5649 // FIXME ugly cast
5650 (audio_output_flags_t) flags,
5651 true /*exactMatchRequiredForInputFlags*/)) {
5652 return profile;
5653 }
5654 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
5655 samplingRate,
5656 &updatedSamplingRate,
5657 format,
5658 &updatedFormat,
5659 channelMask,
5660 &updatedChannelMask,
5661 // FIXME ugly cast
5662 (audio_output_flags_t) flags,
5663 false /*exactMatchRequiredForInputFlags*/)) {
5664 firstInexact = profile;
5665 }
5666
5667 }
5668 }
5669 if (firstInexact != nullptr) {
5670 samplingRate = updatedSamplingRate;
5671 format = updatedFormat;
5672 channelMask = updatedChannelMask;
5673 return firstInexact;
5674 }
5675 return NULL;
5676 }
5677
computeVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,audio_devices_t device)5678 float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
5679 VolumeSource volumeSource,
5680 int index,
5681 audio_devices_t device)
5682 {
5683 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(device), index);
5684
5685 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
5686 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
5687 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
5688 // the ringtone volume
5689 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5690 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
5691 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
5692 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
5693
5694 if (volumeSource == toVolumeSource(AUDIO_STREAM_ACCESSIBILITY)
5695 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
5696 mOutputs.isActive(ringVolumeSrc, 0)) {
5697 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
5698 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, device);
5699 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
5700 }
5701
5702 // in-call: always cap volume by voice volume + some low headroom
5703 if ((volumeSource != callVolumeSrc && (isInCall() ||
5704 mOutputs.isActiveLocally(callVolumeSrc))) &&
5705 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
5706 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
5707 volumeSource == alarmVolumeSrc ||
5708 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
5709 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5710 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
5711 volumeSource == toVolumeSource(AUDIO_STREAM_ACCESSIBILITY))) {
5712 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
5713 int voiceVolumeIndex = voiceCurves.getVolumeIndex(device);
5714 const float maxVoiceVolDb =
5715 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, device)
5716 + IN_CALL_EARPIECE_HEADROOM_DB;
5717 // FIXME: Workaround for call screening applications until a proper audio mode is defined
5718 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
5719 // programmatically muted.
5720 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
5721 // 0. We don't want to cap volume when the system has programmatically muted the voice call
5722 // stream. See setVolumeCurveIndex() for more information.
5723 bool exemptFromCapping = (volumeSource == ringVolumeSrc) && (voiceVolumeIndex == 0);
5724 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
5725 volumeSource, volumeDb);
5726 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
5727 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
5728 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
5729 volumeDb = maxVoiceVolDb;
5730 }
5731 }
5732 // if a headset is connected, apply the following rules to ring tones and notifications
5733 // to avoid sound level bursts in user's ears:
5734 // - always attenuate notifications volume by 6dB
5735 // - attenuate ring tones volume by 6dB unless music is not playing and
5736 // speaker is part of the select devices
5737 // - if music is playing, always limit the volume to current music volume,
5738 // with a minimum threshold at -36dB so that notification is always perceived.
5739 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP | AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5740 AUDIO_DEVICE_OUT_WIRED_HEADSET | AUDIO_DEVICE_OUT_WIRED_HEADPHONE |
5741 AUDIO_DEVICE_OUT_USB_HEADSET | AUDIO_DEVICE_OUT_HEARING_AID)) &&
5742 ((volumeSource == alarmVolumeSrc ||
5743 volumeSource == ringVolumeSrc) ||
5744 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
5745 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
5746 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
5747 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
5748 curves.canBeMuted()) {
5749
5750 // when the phone is ringing we must consider that music could have been paused just before
5751 // by the music application and behave as if music was active if the last music track was
5752 // just stopped
5753 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
5754 mLimitRingtoneVolume) {
5755 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
5756 audio_devices_t musicDevice =
5757 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
5758 nullptr, true /*fromCache*/).types();
5759 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
5760 float musicVolDb = computeVolume(musicCurves, musicVolumeSrc,
5761 musicCurves.getVolumeIndex(musicDevice), musicDevice);
5762 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
5763 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
5764 if (volumeDb > minVolDb) {
5765 volumeDb = minVolDb;
5766 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
5767 }
5768 if (device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5769 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES)) {
5770 // on A2DP, also ensure notification volume is not too low compared to media when
5771 // intended to be played
5772 if ((volumeDb > -96.0f) &&
5773 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
5774 ALOGV("%s increasing volume for volume source=%d device=0x%X from %f to %f",
5775 __func__, volumeSource, device, volumeDb,
5776 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
5777 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
5778 }
5779 }
5780 } else if ((Volume::getDeviceForVolume(device) != AUDIO_DEVICE_OUT_SPEAKER) ||
5781 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
5782 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
5783 }
5784 }
5785
5786 return volumeDb;
5787 }
5788
rescaleVolumeIndex(int srcIndex,VolumeSource fromVolumeSource,VolumeSource toVolumeSource)5789 int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
5790 VolumeSource fromVolumeSource,
5791 VolumeSource toVolumeSource)
5792 {
5793 if (fromVolumeSource == toVolumeSource) {
5794 return srcIndex;
5795 }
5796 auto &srcCurves = getVolumeCurves(fromVolumeSource);
5797 auto &dstCurves = getVolumeCurves(toVolumeSource);
5798 float minSrc = (float)srcCurves.getVolumeIndexMin();
5799 float maxSrc = (float)srcCurves.getVolumeIndexMax();
5800 float minDst = (float)dstCurves.getVolumeIndexMin();
5801 float maxDst = (float)dstCurves.getVolumeIndexMax();
5802
5803 // preserve mute request or correct range
5804 if (srcIndex < minSrc) {
5805 if (srcIndex == 0) {
5806 return 0;
5807 }
5808 srcIndex = minSrc;
5809 } else if (srcIndex > maxSrc) {
5810 srcIndex = maxSrc;
5811 }
5812 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
5813 }
5814
checkAndSetVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const sp<AudioOutputDescriptor> & outputDesc,audio_devices_t device,int delayMs,bool force)5815 status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
5816 VolumeSource volumeSource,
5817 int index,
5818 const sp<AudioOutputDescriptor>& outputDesc,
5819 audio_devices_t device,
5820 int delayMs,
5821 bool force)
5822 {
5823 // do not change actual attributes volume if the attributes is muted
5824 if (outputDesc->isMuted(volumeSource)) {
5825 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
5826 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
5827 return NO_ERROR;
5828 }
5829 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
5830 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
5831 bool isVoiceVolSrc = callVolSrc == volumeSource;
5832 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
5833
5834 audio_policy_forced_cfg_t forceUseForComm =
5835 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_COMMUNICATION);
5836 // do not change in call volume if bluetooth is connected and vice versa
5837 // if sco and call follow same curves, bypass forceUseForComm
5838 if ((callVolSrc != btScoVolSrc) &&
5839 ((isVoiceVolSrc && forceUseForComm == AUDIO_POLICY_FORCE_BT_SCO) ||
5840 (isBtScoVolSrc && forceUseForComm != AUDIO_POLICY_FORCE_BT_SCO))) {
5841 ALOGV("%s cannot set volume group %d volume with force use = %d for comm", __func__,
5842 volumeSource, forceUseForComm);
5843 return INVALID_OPERATION;
5844 }
5845 if (device == AUDIO_DEVICE_NONE) {
5846 device = outputDesc->devices().types();
5847 }
5848
5849 float volumeDb = computeVolume(curves, volumeSource, index, device);
5850 if (outputDesc->isFixedVolume(device) ||
5851 // Force VoIP volume to max for bluetooth SCO
5852 ((isVoiceVolSrc || isBtScoVolSrc) && (device & AUDIO_DEVICE_OUT_ALL_SCO) != 0)) {
5853 volumeDb = 0.0f;
5854 }
5855 outputDesc->setVolume(volumeDb, volumeSource, curves.getStreamTypes(), device, delayMs, force);
5856
5857 if (isVoiceVolSrc || isBtScoVolSrc) {
5858 float voiceVolume;
5859 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
5860 if (isVoiceVolSrc) {
5861 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
5862 } else {
5863 voiceVolume = index == 0 ? 0.0 : 1.0;
5864 }
5865 if (voiceVolume != mLastVoiceVolume) {
5866 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5867 mLastVoiceVolume = voiceVolume;
5868 }
5869 }
5870 return NO_ERROR;
5871 }
5872
applyStreamVolumes(const sp<AudioOutputDescriptor> & outputDesc,audio_devices_t device,int delayMs,bool force)5873 void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
5874 audio_devices_t device,
5875 int delayMs,
5876 bool force)
5877 {
5878 ALOGVV("applyStreamVolumes() for device %08x", device);
5879 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
5880 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
5881 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
5882 curves.getVolumeIndex(device), outputDesc, device, delayMs, force);
5883 }
5884 }
5885
setStrategyMute(product_strategy_t strategy,bool on,const sp<AudioOutputDescriptor> & outputDesc,int delayMs,audio_devices_t device)5886 void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
5887 bool on,
5888 const sp<AudioOutputDescriptor>& outputDesc,
5889 int delayMs,
5890 audio_devices_t device)
5891 {
5892 std::vector<VolumeSource> sourcesToMute;
5893 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
5894 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
5895 toString(attributes).c_str(), on, outputDesc->getId());
5896 VolumeSource source = toVolumeSource(attributes);
5897 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
5898 sourcesToMute.push_back(source);
5899 }
5900 }
5901 for (auto source : sourcesToMute) {
5902 setVolumeSourceMute(source, on, outputDesc, delayMs, device);
5903 }
5904
5905 }
5906
setVolumeSourceMute(VolumeSource volumeSource,bool on,const sp<AudioOutputDescriptor> & outputDesc,int delayMs,audio_devices_t device)5907 void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
5908 bool on,
5909 const sp<AudioOutputDescriptor>& outputDesc,
5910 int delayMs,
5911 audio_devices_t device)
5912 {
5913 if (device == AUDIO_DEVICE_NONE) {
5914 device = outputDesc->devices().types();
5915 }
5916 auto &curves = getVolumeCurves(volumeSource);
5917 if (on) {
5918 if (!outputDesc->isMuted(volumeSource)) {
5919 if (curves.canBeMuted() &&
5920 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5921 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
5922 AUDIO_POLICY_FORCE_NONE))) {
5923 checkAndSetVolume(curves, volumeSource, 0, outputDesc, device, delayMs);
5924 }
5925 }
5926 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
5927 // ignored
5928 outputDesc->incMuteCount(volumeSource);
5929 } else {
5930 if (!outputDesc->isMuted(volumeSource)) {
5931 ALOGV("%s unmuting non muted attributes!", __func__);
5932 return;
5933 }
5934 if (outputDesc->decMuteCount(volumeSource) == 0) {
5935 checkAndSetVolume(curves, volumeSource,
5936 curves.getVolumeIndex(device),
5937 outputDesc,
5938 device,
5939 delayMs);
5940 }
5941 }
5942 }
5943
isValidAttributes(const audio_attributes_t * paa)5944 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
5945 {
5946 // has flags that map to a stream type?
5947 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
5948 return true;
5949 }
5950
5951 // has known usage?
5952 switch (paa->usage) {
5953 case AUDIO_USAGE_UNKNOWN:
5954 case AUDIO_USAGE_MEDIA:
5955 case AUDIO_USAGE_VOICE_COMMUNICATION:
5956 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
5957 case AUDIO_USAGE_ALARM:
5958 case AUDIO_USAGE_NOTIFICATION:
5959 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
5960 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
5961 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
5962 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
5963 case AUDIO_USAGE_NOTIFICATION_EVENT:
5964 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
5965 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
5966 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
5967 case AUDIO_USAGE_GAME:
5968 case AUDIO_USAGE_VIRTUAL_SOURCE:
5969 case AUDIO_USAGE_ASSISTANT:
5970 break;
5971 default:
5972 return false;
5973 }
5974 return true;
5975 }
5976
getForceUse(audio_policy_force_use_t usage)5977 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
5978 {
5979 return mEngine->getForceUse(usage);
5980 }
5981
isInCall()5982 bool AudioPolicyManager::isInCall()
5983 {
5984 return isStateInCall(mEngine->getPhoneState());
5985 }
5986
isStateInCall(int state)5987 bool AudioPolicyManager::isStateInCall(int state)
5988 {
5989 return is_state_in_call(state);
5990 }
5991
cleanUpForDevice(const sp<DeviceDescriptor> & deviceDesc)5992 void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
5993 {
5994 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5995 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5996 if (sourceDesc->srcDevice()->equals(deviceDesc)) {
5997 ALOGV("%s releasing audio source %d", __FUNCTION__, sourceDesc->portId());
5998 stopAudioSource(sourceDesc->portId());
5999 }
6000 }
6001
6002 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
6003 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
6004 bool release = false;
6005 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
6006 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
6007 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
6008 source->ext.device.type == deviceDesc->type()) {
6009 release = true;
6010 }
6011 }
6012 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
6013 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
6014 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
6015 sink->ext.device.type == deviceDesc->type()) {
6016 release = true;
6017 }
6018 }
6019 if (release) {
6020 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->mHandle);
6021 releaseAudioPatch(patchDesc->mHandle, patchDesc->mUid);
6022 }
6023 }
6024
6025 mInputs.clearSessionRoutesForDevice(deviceDesc);
6026
6027 mHwModules.cleanUpForDevice(deviceDesc);
6028 }
6029
modifySurroundFormats(const sp<DeviceDescriptor> & devDesc,FormatVector * formatsPtr)6030 void AudioPolicyManager::modifySurroundFormats(
6031 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
6032 std::unordered_set<audio_format_t> enforcedSurround(
6033 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
6034 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
6035 for (const auto& pair : mConfig.getSurroundFormats()) {
6036 allSurround.insert(pair.first);
6037 for (const auto& subformat : pair.second) allSurround.insert(subformat);
6038 }
6039
6040 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6041 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6042 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
6043 // This is the resulting set of formats depending on the surround mode:
6044 // 'all surround' = allSurround
6045 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
6046 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
6047 // 'manual surround' = mManualSurroundFormats
6048 // AUTO: formats v 'enforced surround'
6049 // ALWAYS: formats v 'all surround' v 'enforced surround'
6050 // NEVER: formats ^ 'non-surround'
6051 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
6052
6053 std::unordered_set<audio_format_t> formatSet;
6054 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
6055 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6056 // formatSet is (formats ^ 'non-surround')
6057 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
6058 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
6059 formatSet.insert(*formatIter);
6060 }
6061 }
6062 } else {
6063 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
6064 }
6065 formatsPtr->clear(); // Re-filled from the formatSet at the end.
6066
6067 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
6068 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
6069 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
6070 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
6071 formatSet.insert(AUDIO_FORMAT_IEC61937);
6072 }
6073 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
6074 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
6075 formatSet.insert(allSurround.begin(), allSurround.end());
6076 }
6077 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
6078 }
6079 for (const auto& format : formatSet) {
6080 formatsPtr->push(format);
6081 }
6082 }
6083
modifySurroundChannelMasks(ChannelsVector * channelMasksPtr)6084 void AudioPolicyManager::modifySurroundChannelMasks(ChannelsVector *channelMasksPtr) {
6085 ChannelsVector &channelMasks = *channelMasksPtr;
6086 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6087 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
6088
6089 // If NEVER, then remove support for channelMasks > stereo.
6090 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
6091 for (size_t maskIndex = 0; maskIndex < channelMasks.size(); ) {
6092 audio_channel_mask_t channelMask = channelMasks[maskIndex];
6093 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
6094 ALOGI("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
6095 channelMasks.removeAt(maskIndex);
6096 } else {
6097 maskIndex++;
6098 }
6099 }
6100 // If ALWAYS or MANUAL, then make sure we at least support 5.1
6101 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
6102 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
6103 bool supports5dot1 = false;
6104 // Are there any channel masks that can be considered "surround"?
6105 for (audio_channel_mask_t channelMask : channelMasks) {
6106 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
6107 supports5dot1 = true;
6108 break;
6109 }
6110 }
6111 // If not then add 5.1 support.
6112 if (!supports5dot1) {
6113 channelMasks.add(AUDIO_CHANNEL_OUT_5POINT1);
6114 ALOGI("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
6115 }
6116 }
6117 }
6118
updateAudioProfiles(const sp<DeviceDescriptor> & devDesc,audio_io_handle_t ioHandle,AudioProfileVector & profiles)6119 void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
6120 audio_io_handle_t ioHandle,
6121 AudioProfileVector &profiles)
6122 {
6123 String8 reply;
6124 audio_devices_t device = devDesc->type();
6125
6126 // Format MUST be checked first to update the list of AudioProfile
6127 if (profiles.hasDynamicFormat()) {
6128 reply = mpClientInterface->getParameters(
6129 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
6130 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
6131 AudioParameter repliedParameters(reply);
6132 if (repliedParameters.get(
6133 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
6134 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
6135 return;
6136 }
6137 FormatVector formats = formatsFromString(reply.string());
6138 if (device == AUDIO_DEVICE_OUT_HDMI
6139 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
6140 modifySurroundFormats(devDesc, &formats);
6141 }
6142 profiles.setFormats(formats);
6143 }
6144
6145 for (audio_format_t format : profiles.getSupportedFormats()) {
6146 ChannelsVector channelMasks;
6147 SampleRateVector samplingRates;
6148 AudioParameter requestedParameters;
6149 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
6150
6151 if (profiles.hasDynamicRateFor(format)) {
6152 reply = mpClientInterface->getParameters(
6153 ioHandle,
6154 requestedParameters.toString() + ";" +
6155 AudioParameter::keyStreamSupportedSamplingRates);
6156 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
6157 AudioParameter repliedParameters(reply);
6158 if (repliedParameters.get(
6159 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
6160 samplingRates = samplingRatesFromString(reply.string());
6161 }
6162 }
6163 if (profiles.hasDynamicChannelsFor(format)) {
6164 reply = mpClientInterface->getParameters(ioHandle,
6165 requestedParameters.toString() + ";" +
6166 AudioParameter::keyStreamSupportedChannels);
6167 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
6168 AudioParameter repliedParameters(reply);
6169 if (repliedParameters.get(
6170 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
6171 channelMasks = channelMasksFromString(reply.string());
6172 if (device == AUDIO_DEVICE_OUT_HDMI
6173 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
6174 modifySurroundChannelMasks(&channelMasks);
6175 }
6176 }
6177 }
6178 profiles.addProfileFromHal(new AudioProfile(format, channelMasks, samplingRates));
6179 }
6180 }
6181
installPatch(const char * caller,audio_patch_handle_t * patchHandle,AudioIODescriptorInterface * ioDescriptor,const struct audio_patch * patch,int delayMs)6182 status_t AudioPolicyManager::installPatch(const char *caller,
6183 audio_patch_handle_t *patchHandle,
6184 AudioIODescriptorInterface *ioDescriptor,
6185 const struct audio_patch *patch,
6186 int delayMs)
6187 {
6188 ssize_t index = mAudioPatches.indexOfKey(
6189 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
6190 *patchHandle : ioDescriptor->getPatchHandle());
6191 sp<AudioPatch> patchDesc;
6192 status_t status = installPatch(
6193 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
6194 if (status == NO_ERROR) {
6195 ioDescriptor->setPatchHandle(patchDesc->mHandle);
6196 }
6197 return status;
6198 }
6199
installPatch(const char * caller,ssize_t index,audio_patch_handle_t * patchHandle,const struct audio_patch * patch,int delayMs,uid_t uid,sp<AudioPatch> * patchDescPtr)6200 status_t AudioPolicyManager::installPatch(const char *caller,
6201 ssize_t index,
6202 audio_patch_handle_t *patchHandle,
6203 const struct audio_patch *patch,
6204 int delayMs,
6205 uid_t uid,
6206 sp<AudioPatch> *patchDescPtr)
6207 {
6208 sp<AudioPatch> patchDesc;
6209 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
6210 if (index >= 0) {
6211 patchDesc = mAudioPatches.valueAt(index);
6212 afPatchHandle = patchDesc->mAfPatchHandle;
6213 }
6214
6215 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
6216 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
6217 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
6218 if (status == NO_ERROR) {
6219 if (index < 0) {
6220 patchDesc = new AudioPatch(patch, uid);
6221 addAudioPatch(patchDesc->mHandle, patchDesc);
6222 } else {
6223 patchDesc->mPatch = *patch;
6224 }
6225 patchDesc->mAfPatchHandle = afPatchHandle;
6226 if (patchHandle) {
6227 *patchHandle = patchDesc->mHandle;
6228 }
6229 nextAudioPortGeneration();
6230 mpClientInterface->onAudioPatchListUpdate();
6231 }
6232 if (patchDescPtr) *patchDescPtr = patchDesc;
6233 return status;
6234 }
6235
6236 } // namespace android
6237