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 #include "utils/Errors.h"
18 #define LOG_TAG "APM_AudioPolicyManager"
19
20 // Need to keep the log statements even in production builds
21 // to enable VERBOSE logging dynamically.
22 // You can enable VERBOSE logging as follows:
23 // adb shell setprop log.tag.APM_AudioPolicyManager V
24 #define LOG_NDEBUG 0
25
26 //#define VERY_VERBOSE_LOGGING
27 #ifdef VERY_VERBOSE_LOGGING
28 #define ALOGVV ALOGV
29 #else
30 #define ALOGVV(a...) do { } while(0)
31 #endif
32
33 #include <algorithm>
34 #include <inttypes.h>
35 #include <map>
36 #include <math.h>
37 #include <set>
38 #include <type_traits>
39 #include <unordered_set>
40 #include <vector>
41
42 #include <Serializer.h>
43 #include <android/media/audio/common/AudioPort.h>
44 #include <com_android_media_audio.h>
45 #include <android_media_audiopolicy.h>
46 #include <com_android_media_audioserver.h>
47 #include <cutils/bitops.h>
48 #include <cutils/properties.h>
49 #include <media/AudioParameter.h>
50 #include <policy.h>
51 #include <private/android_filesystem_config.h>
52 #include <system/audio.h>
53 #include <system/audio_config.h>
54 #include <system/audio_effects/effect_hapticgenerator.h>
55 #include <utils/Log.h>
56
57 #include "AudioPolicyManager.h"
58 #include "TypeConverter.h"
59
60 namespace android {
61
62
63 namespace audio_flags = android::media::audiopolicy;
64
65 using android::media::audio::common::AudioDevice;
66 using android::media::audio::common::AudioDeviceAddress;
67 using android::media::audio::common::AudioPortDeviceExt;
68 using android::media::audio::common::AudioPortExt;
69 using content::AttributionSourceState;
70
71 //FIXME: workaround for truncated touch sounds
72 // to be removed when the problem is handled by system UI
73 #define TOUCH_SOUND_FIXED_DELAY_MS 100
74
75 // Largest difference in dB on earpiece in call between the voice volume and another
76 // media / notification / system volume.
77 constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
79 template <typename T>
operator ==(const SortedVector<T> & left,const SortedVector<T> & right)80 bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81 {
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91 }
92
93 template <typename T>
operator !=(const SortedVector<T> & left,const SortedVector<T> & right)94 bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95 {
96 return !(left == right);
97 }
98
99 // ----------------------------------------------------------------------------
100 // AudioPolicyInterface implementation
101 // ----------------------------------------------------------------------------
102
setDeviceConnectionState(audio_policy_dev_state_t state,const android::media::audio::common::AudioPort & port,audio_format_t encodedFormat)103 status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
106 nextAudioPortGeneration();
107 return status;
108 }
109
setDeviceConnectionState(audio_devices_t device,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)110 status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
115 media::AudioPortFw aidlPort;
116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123 }
124
broadcastDeviceConnectionState(const sp<DeviceDescriptor> & device,media::DeviceConnectedState state)125 void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
126 media::DeviceConnectedState state)
127 {
128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
131 status != OK) {
132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
136 }
137
setDeviceConnectionStateInt(audio_policy_dev_state_t state,const android::media::audio::common::AudioPort & port,audio_format_t encodedFormat)138 status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
166 }
167
setDeviceConnectionStateInt(audio_devices_t deviceType,audio_policy_dev_state_t state,const char * device_address,const char * device_name,audio_format_t encodedFormat)168 status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
169 audio_policy_dev_state_t state,
170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
173 media::AudioPortFw aidlPort;
174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
181 }
182
setDeviceConnectionStateInt(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state)183 status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185 {
186 // handle output devices
187 if (audio_is_output_device(device->type())) {
188 SortedVector <audio_io_handle_t> outputs;
189
190 ssize_t index = mAvailableOutputDevices.indexOf(device);
191
192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
198 switch (state)
199 {
200 // handle output device connection
201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
202 if (index >= 0) {
203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
204 return INVALID_OPERATION;
205 }
206 ALOGV("%s() connecting device %s format %x",
207 __func__, device->toString().c_str(), device->getEncodedFormat());
208
209 // register new device as available
210 if (mAvailableOutputDevices.add(device) < 0) {
211 return NO_MEMORY;
212 }
213
214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
217
218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
220
221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
222
223 mHwModules.cleanUpForDevice(device);
224 return INVALID_OPERATION;
225 }
226
227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
234
235 } break;
236 // handle output device disconnection
237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
238 if (index < 0) {
239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
240 return INVALID_OPERATION;
241 }
242
243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
244
245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
248
249 // remove device from available output devices
250 mAvailableOutputDevices.remove(device);
251
252 mOutputs.clearSessionRoutesForDevice(device);
253
254 checkOutputsForDevice(device, state, outputs);
255
256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
268 } break;
269
270 default:
271 ALOGE("%s() invalid state: %x", __func__, state);
272 return BAD_VALUE;
273 }
274
275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
288 && device->address() == policyMix->mDeviceAddress.c_str()) {
289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
302 // "outputs" vector never contains duplicated outputs
303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
308 clearAudioSourcesForOutput(output);
309 closeOutput(output);
310 }
311 }
312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
314 }
315 return false;
316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
323 (void)updateCallRouting(false /*fromCache*/);
324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
328 for (size_t i = 0; i < mOutputs.size(); i++) {
329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
337 && !desc->isDuplicated()
338 && (!device_distinguishes_on_address(device->type())
339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
348 setOutputDevices(__func__, desc, newDevices, force, 0);
349 }
350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
368 reopenOutputsWithDevices(outputsToReopenWithDevices);
369
370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
371 cleanUpForDevice(device);
372 }
373
374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
376 mpClientInterface->onAudioPortListUpdate();
377 return NO_ERROR;
378 } // end if is output device
379
380 // handle input devices
381 if (audio_is_input_device(device->type())) {
382 ssize_t index = mAvailableInputDevices.indexOf(device);
383 switch (state)
384 {
385 // handle input device connection
386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
387 if (index >= 0) {
388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
389 return INVALID_OPERATION;
390 }
391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
399 // Propagate device availability to Engine
400 setEngineDeviceConnectionState(device, state);
401
402 if (checkInputsForDevice(device, state) != NO_ERROR) {
403 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
404
405 mAvailableInputDevices.remove(device);
406
407 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
408
409 mHwModules.cleanUpForDevice(device);
410
411 return INVALID_OPERATION;
412 }
413
414 } break;
415
416 // handle input device disconnection
417 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
418 if (index < 0) {
419 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
420 return INVALID_OPERATION;
421 }
422
423 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
424
425 // Notify the HAL to prepare to disconnect device
426 broadcastDeviceConnectionState(
427 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
428
429 mAvailableInputDevices.remove(device);
430
431 checkInputsForDevice(device, state);
432
433 // Set Disconnect to HALs
434 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
435
436 // remove device from mReportedFormatsMap cache
437 mReportedFormatsMap.erase(device);
438
439 // Propagate device availability to Engine
440 setEngineDeviceConnectionState(device, state);
441 } break;
442
443 default:
444 ALOGE("%s() invalid state: %x", __func__, state);
445 return BAD_VALUE;
446 }
447
448 checkCloseInputs();
449 // As the input device list can impact the output device selection, update
450 // getDeviceForStrategy() cache
451 updateDevicesAndOutputs();
452
453 (void)updateCallRouting(false /*fromCache*/);
454 // Reconnect Audio Source
455 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
456 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
457 checkAudioSourceForAttributes(attributes);
458 }
459 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
460 cleanUpForDevice(device);
461 }
462
463 mpClientInterface->onAudioPortListUpdate();
464 return NO_ERROR;
465 } // end if is input device
466
467 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
468 return BAD_VALUE;
469 }
470
deviceToAudioPort(audio_devices_t device,const char * device_address,const char * device_name,media::AudioPortFw * aidlPort)471 status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
472 const char* device_name,
473 media::AudioPortFw* aidlPort) {
474 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
475 devDescr->setName(device_name);
476 return devDescr->writeToParcelable(aidlPort);
477 }
478
setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,audio_policy_dev_state_t state)479 void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
480 audio_policy_dev_state_t state) {
481
482 // the Engine does not have to know about remote submix devices used by dynamic audio policies
483 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
484 return;
485 }
486 mEngine->setDeviceConnectionState(device, state);
487 }
488
489
getDeviceConnectionState(audio_devices_t device,const char * device_address)490 audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
491 const char *device_address)
492 {
493 sp<DeviceDescriptor> devDesc =
494 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
495 false /* allowToCreate */,
496 (strlen(device_address) != 0)/*matchAddress*/);
497
498 if (devDesc == 0) {
499 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
500 device, device_address);
501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
502 }
503
504 DeviceVector *deviceVector;
505
506 if (audio_is_output_device(device)) {
507 deviceVector = &mAvailableOutputDevices;
508 } else if (audio_is_input_device(device)) {
509 deviceVector = &mAvailableInputDevices;
510 } else {
511 ALOGW("%s() invalid device type %08x", __func__, device);
512 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
513 }
514
515 return (deviceVector->getDevice(
516 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
518 }
519
handleDeviceConfigChange(audio_devices_t device,const char * device_address,const char * device_name,audio_format_t encodedFormat)520 status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
521 const char *device_address,
522 const char *device_name,
523 audio_format_t encodedFormat)
524 {
525 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
526 device, device_address, device_name, encodedFormat);
527
528 // connect/disconnect only 1 device at a time
529 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
530
531 // Check if the device is currently connected
532 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
533 if (deviceList.empty()) {
534 // Nothing to do: device is not connected
535 return NO_ERROR;
536 }
537 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
538
539 // For offloaded A2DP, Hw modules may have the capability to
540 // configure codecs.
541 // Handle two specific cases by sending a set parameter to
542 // configure A2DP codecs. No need to toggle device state.
543 // Case 1: A2DP active device switches from primary to primary
544 // module
545 // Case 2: A2DP device config changes on primary module.
546 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
547 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
548 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
549 if (availablePrimaryOutputDevices().contains(devDesc) &&
550 (module != 0 && module->getHandle() == primaryHandle)) {
551 bool isA2dp = audio_is_a2dp_out_device(device);
552 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
553 : String8(AudioParameter::keyReconfigLeSupported);
554 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
555 AudioParameter repliedParameters(reply);
556 int isReconfigSupported;
557 repliedParameters.getInt(supportKey, isReconfigSupported);
558 if (isReconfigSupported) {
559 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
560 : String8(AudioParameter::keyReconfigLe);
561 AudioParameter param;
562 param.add(key, String8("true"));
563 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
564 devDesc->setEncodedFormat(encodedFormat);
565 return NO_ERROR;
566 }
567 }
568 }
569 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
570 uint32_t muteWaitMs = 0;
571 for (size_t i = 0; i < mOutputs.size(); i++) {
572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
573 // mute media strategies to avoid sending the music tail into
574 // the earpiece or headset.
575 if (desc->isStrategyActive(musicStrategy)) {
576 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
577 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
578 tempRecommendedMuteDuration : desc->latency() * 4;
579 if (muteWaitMs < tempMuteDurationMs) {
580 muteWaitMs = tempMuteDurationMs;
581 }
582 }
583 setStrategyMute(musicStrategy, true, desc);
584 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
585 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
586 nullptr, true /*fromCache*/).types());
587 }
588 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
589 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
590 // happens after the actual device switch.
591 if (muteWaitMs > 0) {
592 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
593 usleep(muteWaitMs * 1000);
594 }
595 // Toggle the device state: UNAVAILABLE -> AVAILABLE
596 // This will force reading again the device configuration
597 status_t status = setDeviceConnectionState(device,
598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
599 device_address, device_name,
600 devDesc->getEncodedFormat());
601 if (status != NO_ERROR) {
602 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
603 status);
604 return status;
605 }
606
607 status = setDeviceConnectionState(device,
608 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
609 device_address, device_name, encodedFormat);
610 if (status != NO_ERROR) {
611 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
612 status);
613 return status;
614 }
615
616 return NO_ERROR;
617 }
618
getHwOffloadFormatsSupportedForBluetoothMedia(audio_devices_t device,std::vector<audio_format_t> * formats)619 status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
620 audio_devices_t device, std::vector<audio_format_t> *formats)
621 {
622 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
623 status_t status = NO_ERROR;
624 std::unordered_set<audio_format_t> formatSet;
625 sp<HwModule> primaryModule =
626 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
627 if (primaryModule == nullptr) {
628 ALOGE("%s() unable to get primary module", __func__);
629 return NO_INIT;
630 }
631
632 DeviceTypeSet audioDeviceSet;
633
634 switch(device) {
635 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
636 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
637 break;
638 case AUDIO_DEVICE_OUT_BLE_HEADSET:
639 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
640 break;
641 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
642 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
643 break;
644 default:
645 ALOGE("%s() device type 0x%08x not supported", __func__, device);
646 return BAD_VALUE;
647 }
648
649 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
650 audioDeviceSet);
651 for (const auto& device : declaredDevices) {
652 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
653 }
654 formats->assign(formatSet.begin(), formatSet.end());
655 return status;
656 }
657
selectBestRxSinkDevicesForCall(bool fromCache)658 DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
659 {
660 DeviceVector rxSinkdevices{};
661 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
662 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
663 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
664 auto rxSinkDevice = rxSinkdevices.itemAt(0);
665 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
666 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
667 // retrieve Rx Source device descriptor
668 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
669 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
670
671 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
672 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
673 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
674 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
675 return DeviceVector(rxSinkDevice);
676 }
677 }
678 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
679 // the device returned is not necessarily reachable via this output
680 // (filter later by setOutputDevices())
681 return getNewOutputDevices(mPrimaryOutput, fromCache);
682 }
683
updateCallRouting(bool fromCache,uint32_t delayMs,uint32_t * waitMs)684 status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
685 {
686 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
687 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
688 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
689 }
690 return INVALID_OPERATION;
691 }
692
updateCallRoutingInternal(const DeviceVector & rxDevices,uint32_t delayMs,uint32_t * waitMs)693 status_t AudioPolicyManager::updateCallRoutingInternal(
694 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
695 {
696 bool createTxPatch = false;
697 bool createRxPatch = false;
698 uint32_t muteWaitMs = 0;
699 if (hasPrimaryOutput() &&
700 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
701 return INVALID_OPERATION;
702 }
703
704 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
705 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
706
707 disconnectTelephonyAudioSource(mCallRxSourceClient);
708 disconnectTelephonyAudioSource(mCallTxSourceClient);
709
710 if (rxDevices.isEmpty()) {
711 ALOGW("%s() no selected output device", __func__);
712 return INVALID_OPERATION;
713 }
714 if (txSourceDevice == nullptr) {
715 ALOGE("%s() selected input device not available", __func__);
716 return INVALID_OPERATION;
717 }
718
719 ALOGV("%s device rxDevice %s txDevice %s", __func__,
720 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
721
722 auto telephonyRxModule =
723 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
724 auto telephonyTxModule =
725 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
726 // retrieve Rx Source and Tx Sink device descriptors
727 sp<DeviceDescriptor> rxSourceDevice =
728 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731 sp<DeviceDescriptor> txSinkDevice =
732 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735
736 // RX and TX Telephony device are declared by Primary Audio HAL
737 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
738 (telephonyRxModule->getHalVersionMajor() >= 3)) {
739 if (rxSourceDevice == 0 || txSinkDevice == 0) {
740 // RX / TX Telephony device(s) is(are) not currently available
741 ALOGE("%s() no telephony Tx and/or RX device", __func__);
742 return INVALID_OPERATION;
743 }
744 // createAudioPatchInternal now supports both HW / SW bridging
745 createRxPatch = true;
746 createTxPatch = true;
747 } else {
748 // If the RX device is on the primary HW module, then use legacy routing method for
749 // voice calls via setOutputDevice() on primary output.
750 // Otherwise, create two audio patches for TX and RX path.
751 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
752 (rxSourceDevice != 0);
753 // If the TX device is also on the primary HW module, setOutputDevice() will take care
754 // of it due to legacy implementation. If not, create a patch.
755 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
756 (txSinkDevice != 0);
757 }
758 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
759 // Otherwise, create two audio patches for TX and RX path.
760 if (!createRxPatch) {
761 if (!hasPrimaryOutput()) {
762 ALOGW("%s() no primary output available", __func__);
763 return INVALID_OPERATION;
764 }
765 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
766 } else { // create RX path audio patch
767 connectTelephonyRxAudioSource(delayMs);
768 // If the TX device is on the primary HW module but RX device is
769 // on other HW module, SinkMetaData of telephony input should handle it
770 // assuming the device uses audio HAL V5.0 and above
771 }
772 if (createTxPatch) { // create TX path audio patch
773 // terminate active capture if on the same HW module as the call TX source device
774 // FIXME: would be better to refine to only inputs whose profile connects to the
775 // call TX device but this information is not in the audio patch and logic here must be
776 // symmetric to the one in startInput()
777 for (const auto& activeDesc : mInputs.getActiveInputs()) {
778 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
779 closeActiveClients(activeDesc);
780 }
781 }
782 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
783 }
784 if (waitMs != nullptr) {
785 *waitMs = muteWaitMs;
786 }
787 return NO_ERROR;
788 }
789
isDeviceOfModule(const sp<DeviceDescriptor> & devDesc,const char * moduleId) const790 bool AudioPolicyManager::isDeviceOfModule(
791 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
792 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
793 if (module != 0) {
794 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
795 .indexOf(devDesc) != NAME_NOT_FOUND
796 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
797 .indexOf(devDesc) != NAME_NOT_FOUND;
798 }
799 return false;
800 }
801
connectTelephonyRxAudioSource(uint32_t delayMs)802 void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
803 {
804 disconnectTelephonyAudioSource(mCallRxSourceClient);
805 const struct audio_port_config source = {
806 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
807 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
808 };
809 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
810
811 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
812 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
813 true /*internal*/, true /*isCallRx*/, delayMs);
814 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
815 mCallRxSourceClient = mAudioSources.valueFor(portId);
816 ALOGE_IF(mCallRxSourceClient == nullptr,
817 "%s failed to start Telephony Rx AudioSource", __func__);
818 }
819
disconnectTelephonyAudioSource(sp<SourceClientDescriptor> & clientDesc)820 void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
821 {
822 if (clientDesc == nullptr) {
823 return;
824 }
825 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
826 "%s error stopping audio source", __func__);
827 clientDesc.clear();
828 }
829
connectTelephonyTxAudioSource(const sp<DeviceDescriptor> & srcDevice,const sp<DeviceDescriptor> & sinkDevice,uint32_t delayMs)830 void AudioPolicyManager::connectTelephonyTxAudioSource(
831 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
832 uint32_t delayMs)
833 {
834 disconnectTelephonyAudioSource(mCallTxSourceClient);
835 if (srcDevice == nullptr || sinkDevice == nullptr) {
836 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
837 return;
838 }
839 PatchBuilder patchBuilder;
840 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
841 ALOGV("%s between source %s and sink %s", __func__,
842 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
843 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
844 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
845
846 struct audio_port_config source = {};
847 srcDevice->toAudioPortConfig(&source);
848 mCallTxSourceClient = new SourceClientDescriptor(
849 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
850 mCommunnicationStrategy, toVolumeSource(aa), true,
851 false /*isCallRx*/, true /*isCallTx*/);
852 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
853
854 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
855 status_t status = connectAudioSourceToSink(
856 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
857 delayMs);
858 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
859 if (status == NO_ERROR) {
860 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
861 }
862 }
863
setPhoneState(audio_mode_t state)864 void AudioPolicyManager::setPhoneState(audio_mode_t state)
865 {
866 ALOGV("setPhoneState() state %d", state);
867 // store previous phone state for management of sonification strategy below
868 int oldState = mEngine->getPhoneState();
869 bool wasLeUnicastActive = isLeUnicastActive();
870
871 if (mEngine->setPhoneState(state) != NO_ERROR) {
872 ALOGW("setPhoneState() invalid or same state %d", state);
873 return;
874 }
875 /// Opens: can these line be executed after the switch of volume curves???
876 if (isStateInCall(oldState)) {
877 ALOGV("setPhoneState() in call state management: new state is %d", state);
878 // force reevaluating accessibility routing when call stops
879 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
880 }
881
882 /**
883 * Switching to or from incall state or switching between telephony and VoIP lead to force
884 * routing command.
885 */
886 bool force = ((isStateInCall(oldState) != isStateInCall(state))
887 || (isStateInCall(state) && (state != oldState)));
888
889 // check for device and output changes triggered by new phone state
890 checkForDeviceAndOutputChanges();
891
892 int delayMs = 0;
893 if (isStateInCall(state)) {
894 nsecs_t sysTime = systemTime();
895 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
896 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
897 for (size_t i = 0; i < mOutputs.size(); i++) {
898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
899 // mute media and sonification strategies and delay device switch by the largest
900 // latency of any output where either strategy is active.
901 // This avoid sending the ring tone or music tail into the earpiece or headset.
902 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
903 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
904 sysTime)) &&
905 (delayMs < (int)desc->latency()*2)) {
906 delayMs = desc->latency()*2;
907 }
908 setStrategyMute(musicStrategy, true, desc);
909 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
910 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
911 nullptr, true /*fromCache*/).types());
912 setStrategyMute(sonificationStrategy, true, desc);
913 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
914 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
915 nullptr, true /*fromCache*/).types());
916 }
917 }
918
919 if (state == AUDIO_MODE_IN_CALL) {
920 (void)updateCallRouting(false /*fromCache*/, delayMs);
921 } else {
922 if (oldState == AUDIO_MODE_IN_CALL) {
923 disconnectTelephonyAudioSource(mCallRxSourceClient);
924 disconnectTelephonyAudioSource(mCallTxSourceClient);
925 }
926 if (hasPrimaryOutput()) {
927 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
928 // force routing command to audio hardware when ending call
929 // even if no device change is needed
930 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
931 rxDevices = mPrimaryOutput->devices();
932 }
933 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
934 }
935 }
936
937 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
938 // reevaluate routing on all outputs in case tracks have been started during the call
939 for (size_t i = 0; i < mOutputs.size(); i++) {
940 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
941 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
942 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
943 && desc->mPreferredAttrInfo != nullptr) {
944 // If the output is using preferred mixer attributes and the audio mode is not normal,
945 // the output need to reopen with default configuration.
946 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
947 continue;
948 }
949 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
950 bool forceRouting = !newDevices.isEmpty();
951 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
952 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
953 }
954 }
955 reopenOutputsWithDevices(outputsToReopen);
956
957 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
958
959 if (isStateInCall(state)) {
960 ALOGV("setPhoneState() in call state management: new state is %d", state);
961 // force reevaluating accessibility routing when call starts
962 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
963 }
964
965 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
966 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
967 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
968 }
969
getPhoneState()970 audio_mode_t AudioPolicyManager::getPhoneState() {
971 return mEngine->getPhoneState();
972 }
973
setForceUse(audio_policy_force_use_t usage,audio_policy_forced_cfg_t config)974 void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
975 audio_policy_forced_cfg_t config)
976 {
977 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
978 if (config == mEngine->getForceUse(usage)) {
979 return;
980 }
981
982 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
983 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
984 return;
985 }
986 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
987 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
988 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
989
990 // check for device and output changes triggered by new force usage
991 checkForDeviceAndOutputChanges();
992
993 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
994 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
995 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
996 }
997
998 //FIXME: workaround for truncated touch sounds
999 // to be removed when the problem is handled by system UI
1000 uint32_t delayMs = 0;
1001 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1002 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1003 }
1004
1005 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
1006 updateInputRouting();
1007 }
1008
setSystemProperty(const char * property,const char * value)1009 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
1010 {
1011 ALOGV("setSystemProperty() property %s, value %s", property, value);
1012 }
1013
1014 // Find an MSD output profile compatible with the parameters passed.
1015 // When "directOnly" is set, restrict search to profiles for direct outputs.
getMsdProfileForOutput(const DeviceVector & devices,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,bool directOnly)1016 sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1017 const DeviceVector& devices,
1018 uint32_t samplingRate,
1019 audio_format_t format,
1020 audio_channel_mask_t channelMask,
1021 audio_output_flags_t flags,
1022 bool directOnly)
1023 {
1024 flags = getRelevantFlags(flags, directOnly);
1025
1026 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1027 if (msdModule != nullptr) {
1028 // for the msd module check if there are patches to the output devices
1029 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1030 HwModuleCollection modules;
1031 modules.add(msdModule);
1032 return searchCompatibleProfileHwModules(
1033 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1034 flags, directOnly);
1035 }
1036 }
1037 return nullptr;
1038 }
1039
1040 // Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1041 // 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)1042 sp<IOProfile> AudioPolicyManager::getProfileForOutput(
1043 const DeviceVector& devices,
1044 uint32_t samplingRate,
1045 audio_format_t format,
1046 audio_channel_mask_t channelMask,
1047 audio_output_flags_t flags,
1048 bool directOnly)
1049 {
1050 flags = getRelevantFlags(flags, directOnly);
1051
1052 return searchCompatibleProfileHwModules(
1053 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1054 }
1055
getRelevantFlags(audio_output_flags_t flags,bool directOnly)1056 audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1057 audio_output_flags_t flags, bool directOnly) {
1058 if (directOnly) {
1059 // only retain flags that will drive the direct output profile selection
1060 // if explicitly requested
1061 static const uint32_t kRelevantFlags =
1062 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1063 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1064 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
1065 }
1066 return flags;
1067 }
1068
searchCompatibleProfileHwModules(const HwModuleCollection & hwModules,const DeviceVector & devices,uint32_t samplingRate,audio_format_t format,audio_channel_mask_t channelMask,audio_output_flags_t flags,bool directOnly)1069 sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1070 const HwModuleCollection& hwModules,
1071 const DeviceVector& devices,
1072 uint32_t samplingRate,
1073 audio_format_t format,
1074 audio_channel_mask_t channelMask,
1075 audio_output_flags_t flags,
1076 bool directOnly) {
1077 sp<IOProfile> profile;
1078 for (const auto& hwModule : hwModules) {
1079 for (const auto& curProfile : hwModule->getOutputProfiles()) {
1080 if (curProfile->getCompatibilityScore(devices,
1081 samplingRate, NULL /*updatedSamplingRate*/,
1082 format, NULL /*updatedFormat*/,
1083 channelMask, NULL /*updatedChannelMask*/,
1084 flags) == IOProfile::NO_MATCH) {
1085 continue;
1086 }
1087 // reject profiles not corresponding to a device currently available
1088 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1089 continue;
1090 }
1091 // reject profiles if connected device does not support codec
1092 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1093 continue;
1094 }
1095 if (!directOnly) {
1096 return curProfile;
1097 }
1098
1099 // when searching for direct outputs, if several profiles are compatible, give priority
1100 // to one with offload capability
1101 if (profile != 0 &&
1102 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
1103 continue;
1104 }
1105 profile = curProfile;
1106 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1107 break;
1108 }
1109 }
1110 }
1111 return profile;
1112 }
1113
getSpatializerOutputProfile(const audio_config_t * config __unused,const AudioDeviceTypeAddrVector & devices) const1114 sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
1115 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
1116 {
1117 for (const auto& hwModule : mHwModules) {
1118 for (const auto& curProfile : hwModule->getOutputProfiles()) {
1119 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
1120 continue;
1121 }
1122 if (!devices.empty()) {
1123 // reject profiles not corresponding to a device currently available
1124 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1125 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1126 continue;
1127 }
1128 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1129 != devices.size()) {
1130 continue;
1131 }
1132 }
1133 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1134 return curProfile;
1135 }
1136 }
1137 return nullptr;
1138 }
1139
getOutput(audio_stream_type_t stream)1140 audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
1141 {
1142 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
1143
1144 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1145 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1146 // format, flags, etc. This may result in some discrepancy for functions that utilize
1147 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1148 // and AudioSystem::getOutputSamplingRate().
1149
1150 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
1151 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1152 if (stream == AUDIO_STREAM_MUSIC &&
1153 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1154 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1155 }
1156 const audio_io_handle_t output = selectOutput(outputs, flags);
1157
1158 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1159 devices.toString().c_str(), output);
1160 return output;
1161 }
1162
getAudioAttributes(audio_attributes_t * dstAttr,const audio_attributes_t * srcAttr,audio_stream_type_t srcStream)1163 status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1164 const audio_attributes_t *srcAttr,
1165 audio_stream_type_t srcStream)
1166 {
1167 if (srcAttr != NULL) {
1168 if (!isValidAttributes(srcAttr)) {
1169 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1170 __func__,
1171 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1172 srcAttr->tags);
1173 return BAD_VALUE;
1174 }
1175 *dstAttr = *srcAttr;
1176 } else {
1177 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1178 ALOGE("%s: invalid stream type", __func__);
1179 return BAD_VALUE;
1180 }
1181 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
1182 }
1183
1184 // Only honor audibility enforced when required. The client will be
1185 // forced to reconnect if the forced usage changes.
1186 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
1187 dstAttr->flags = static_cast<audio_flags_mask_t>(
1188 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
1189 }
1190
1191 return NO_ERROR;
1192 }
1193
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,audio_config_t * config,audio_output_flags_t * flags,audio_port_handle_t * selectedDeviceId,bool * isRequestedDeviceForExclusiveUse,std::vector<sp<AudioPolicyMix>> * secondaryMixes,output_type_t * outputType,bool * isSpatialized,bool * isBitPerfect)1194 status_t AudioPolicyManager::getOutputForAttrInt(
1195 audio_attributes_t *resultAttr,
1196 audio_io_handle_t *output,
1197 audio_session_t session,
1198 const audio_attributes_t *attr,
1199 audio_stream_type_t *stream,
1200 uid_t uid,
1201 audio_config_t *config,
1202 audio_output_flags_t *flags,
1203 audio_port_handle_t *selectedDeviceId,
1204 bool *isRequestedDeviceForExclusiveUse,
1205 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
1206 output_type_t *outputType,
1207 bool *isSpatialized,
1208 bool *isBitPerfect)
1209 {
1210 DeviceVector outputDevices;
1211 const audio_port_handle_t requestedPortId = *selectedDeviceId;
1212 DeviceVector msdDevices = getMsdAudioOutDevices();
1213 const sp<DeviceDescriptor> requestedDevice =
1214 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1215
1216 *outputType = API_OUTPUT_INVALID;
1217 *isSpatialized = false;
1218
1219 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1220 if (status != NO_ERROR) {
1221 return status;
1222 }
1223 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
1224 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
1225 }
1226 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
1227
1228 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1229 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
1230
1231 bool usePrimaryOutputFromPolicyMixes = false;
1232
1233 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1234 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1235 // Secondary outputs are always found by dynamic policies as the engine do not support them
1236 sp<AudioPolicyMix> primaryMix;
1237 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1238 .channel_mask = config->channel_mask,
1239 .format = config->format,
1240 };
1241 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1242 mAvailableOutputDevices, requestedDevice, primaryMix,
1243 secondaryMixes, usePrimaryOutputFromPolicyMixes);
1244 if (status != OK) {
1245 return status;
1246 }
1247
1248 // FIXME: in case of RENDER policy, the output capabilities should be checked
1249 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1250 && !audio_is_linear_pcm(config->format)) {
1251 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
1252 return BAD_VALUE;
1253 }
1254 if (usePrimaryOutputFromPolicyMixes) {
1255 sp<DeviceDescriptor> policyMixDevice =
1256 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1257 primaryMix->mDeviceAddress,
1258 AUDIO_FORMAT_DEFAULT);
1259 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
1260 bool tryDirectForFlags = policyDesc == nullptr ||
1261 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1262 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
1263 // if a direct output can be opened to deliver the track's multi-channel content to the
1264 // output rather than being downmixed by the primary output, then use this direct
1265 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1266 // mix.
1267 bool tryDirectForChannelMask = policyDesc != nullptr
1268 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1269 audio_channel_count_from_out_mask(config->channel_mask));
1270 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
1271 audio_io_handle_t newOutput;
1272 status = openDirectOutput(
1273 *stream, session, config,
1274 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1275 DeviceVector(policyMixDevice), &newOutput);
1276 if (status == NO_ERROR) {
1277 policyDesc = mOutputs.valueFor(newOutput);
1278 primaryMix->setOutput(policyDesc);
1279 } else if (tryDirectForFlags) {
1280 ALOGW("%s, failed open direct, status: %d", __func__, status);
1281 policyDesc = nullptr;
1282 } // otherwise use primary if available.
1283 }
1284 if (policyDesc != nullptr) {
1285 policyDesc->mPolicyMix = primaryMix;
1286 *output = policyDesc->mIoHandle;
1287 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1288 : AUDIO_PORT_HANDLE_NONE;
1289 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1290 // Remove direct flag as it is not on a direct output.
1291 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1292 }
1293
1294 ALOGV("getOutputForAttr() returns output %d", *output);
1295 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1296 *outputType = API_OUT_MIX_PLAYBACK;
1297 } else {
1298 *outputType = API_OUTPUT_LEGACY;
1299 }
1300 return NO_ERROR;
1301 } else {
1302 if (policyMixDevice != nullptr) {
1303 ALOGE("%s, try to use primary mix but no output found", __func__);
1304 return INVALID_OPERATION;
1305 }
1306 // Fallback to default engine selection as the selected primary mix device is not
1307 // available.
1308 }
1309 }
1310 // Virtual sources must always be dynamicaly or explicitly routed
1311 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1312 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1313 return BAD_VALUE;
1314 }
1315 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1316 // in order to let the choice of the order to future vendor engine
1317 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
1318
1319 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
1320 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1321 }
1322
1323 // Set incall music only if device was explicitly set, and fallback to the device which is
1324 // chosen by the engine if not.
1325 // FIXME: provide a more generic approach which is not device specific and move this back
1326 // to getOutputForDevice.
1327 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
1328 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
1329 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
1330 audio_is_linear_pcm(config->format) &&
1331 isCallAudioAccessible()) {
1332 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
1333 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
1334 *isRequestedDeviceForExclusiveUse = true;
1335 }
1336 }
1337
1338 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1339 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1340 config->channel_mask, *flags, toString(*stream).c_str());
1341
1342 *output = AUDIO_IO_HANDLE_NONE;
1343 if (!msdDevices.isEmpty()) {
1344 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
1345 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
1346 ALOGV("%s() Using MSD devices %s instead of devices %s",
1347 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
1348 } else {
1349 *output = AUDIO_IO_HANDLE_NONE;
1350 }
1351 }
1352 if (*output == AUDIO_IO_HANDLE_NONE) {
1353 sp<PreferredMixerAttributesInfo> info = nullptr;
1354 if (outputDevices.size() == 1) {
1355 info = getPreferredMixerAttributesInfo(
1356 outputDevices.itemAt(0)->getId(),
1357 mEngine->getProductStrategyForAttributes(*resultAttr),
1358 true /*activeBitPerfectPreferred*/);
1359 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1360 // and it is currently active.
1361 if (info != nullptr && info->getUid() != uid &&
1362 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
1363 info = nullptr;
1364 }
1365 if (com::android::media::audioserver::
1366 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1367 if (info != nullptr && info->getUid() == uid &&
1368 info->configMatches(*config) &&
1369 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1370 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1371 [this, &outputDevices](audio_usage_t usage) {
1372 return mOutputs.isUsageActiveOnDevice(
1373 usage, outputDevices[0]); }))) {
1374 // Bit-perfect request is not allowed when the phone mode is not normal or
1375 // there is any higher priority user case active.
1376 return INVALID_OPERATION;
1377 }
1378 }
1379 }
1380 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
1381 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
1382 // The client will be active if the client is currently preferred mixer owner and the
1383 // requested configuration matches the preferred mixer configuration.
1384 *isBitPerfect = (info != nullptr
1385 && info->isBitPerfect()
1386 && info->getUid() == uid
1387 && *output != AUDIO_IO_HANDLE_NONE
1388 // When bit-perfect output is selected for the preferred mixer attributes owner,
1389 // only need to consider the config matches.
1390 && mOutputs.valueFor(*output)->isConfigurationMatched(
1391 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
1392
1393 if (*isBitPerfect) {
1394 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1395 }
1396 }
1397 if (*output == AUDIO_IO_HANDLE_NONE) {
1398 AudioProfileVector profiles;
1399 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1400 if (ret == NO_ERROR && !profiles.empty()) {
1401 const auto channels = profiles[0]->getChannels();
1402 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1403 config->channel_mask = *channels.begin();
1404 }
1405 const auto sampleRates = profiles[0]->getSampleRates();
1406 if (!sampleRates.empty() &&
1407 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1408 config->sample_rate = *sampleRates.begin();
1409 }
1410 config->format = profiles[0]->getFormat();
1411 }
1412 return INVALID_OPERATION;
1413 }
1414
1415 *selectedDeviceId = getFirstDeviceId(outputDevices);
1416 for (auto &outputDevice : outputDevices) {
1417 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
1418 *selectedDeviceId = outputDevice->getId();
1419 break;
1420 }
1421 }
1422
1423 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1424 *outputType = API_OUTPUT_TELEPHONY_TX;
1425 } else {
1426 *outputType = API_OUTPUT_LEGACY;
1427 }
1428
1429 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1430
1431 return NO_ERROR;
1432 }
1433
getOutputForAttr(const audio_attributes_t * attr,audio_io_handle_t * output,audio_session_t session,audio_stream_type_t * stream,const AttributionSourceState & attributionSource,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,output_type_t * outputType,bool * isSpatialized,bool * isBitPerfect)1434 status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1435 audio_io_handle_t *output,
1436 audio_session_t session,
1437 audio_stream_type_t *stream,
1438 const AttributionSourceState& attributionSource,
1439 audio_config_t *config,
1440 audio_output_flags_t *flags,
1441 audio_port_handle_t *selectedDeviceId,
1442 audio_port_handle_t *portId,
1443 std::vector<audio_io_handle_t> *secondaryOutputs,
1444 output_type_t *outputType,
1445 bool *isSpatialized,
1446 bool *isBitPerfect)
1447 {
1448 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1449 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1450 return INVALID_OPERATION;
1451 }
1452 const uid_t uid = VALUE_OR_RETURN_STATUS(
1453 aidl2legacy_int32_t_uid_t(attributionSource.uid));
1454 const audio_port_handle_t requestedPortId = *selectedDeviceId;
1455 audio_attributes_t resultAttr;
1456 bool isRequestedDeviceForExclusiveUse = false;
1457 std::vector<sp<AudioPolicyMix>> secondaryMixes;
1458 const sp<DeviceDescriptor> requestedDevice =
1459 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1460
1461 // Prevent from storing invalid requested device id in clients
1462 const audio_port_handle_t sanitizedRequestedPortId =
1463 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1464 *selectedDeviceId = sanitizedRequestedPortId;
1465
1466 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
1467 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
1468 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1469 isBitPerfect);
1470 if (status != NO_ERROR) {
1471 return status;
1472 }
1473 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
1474 if (secondaryOutputs != nullptr) {
1475 for (auto &secondaryMix : secondaryMixes) {
1476 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1477 if (outputDesc != nullptr &&
1478 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1479 secondaryOutputs->push_back(outputDesc->mIoHandle);
1480 weakSecondaryOutputDescs.push_back(outputDesc);
1481 }
1482 }
1483 }
1484
1485 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1486 .channel_mask = config->channel_mask,
1487 .format = config->format,
1488 };
1489 *portId = PolicyAudioPort::getNextUniqueId();
1490
1491 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
1492 sp<TrackClientDescriptor> clientDesc =
1493 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
1494 sanitizedRequestedPortId, *stream,
1495 mEngine->getProductStrategyForAttributes(resultAttr),
1496 toVolumeSource(resultAttr),
1497 *flags, isRequestedDeviceForExclusiveUse,
1498 std::move(weakSecondaryOutputDescs),
1499 outputDesc->mPolicyMix);
1500 outputDesc->addClient(clientDesc);
1501
1502 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1503 *output, requestedPortId, *selectedDeviceId, *portId);
1504
1505 return NO_ERROR;
1506 }
1507
openDirectOutput(audio_stream_type_t stream,audio_session_t session,const audio_config_t * config,audio_output_flags_t flags,const DeviceVector & devices,audio_io_handle_t * output)1508 status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1509 audio_session_t session,
1510 const audio_config_t *config,
1511 audio_output_flags_t flags,
1512 const DeviceVector &devices,
1513 audio_io_handle_t *output) {
1514
1515 *output = AUDIO_IO_HANDLE_NONE;
1516
1517 // skip direct output selection if the request can obviously be attached to a mixed output
1518 // and not explicitly requested
1519 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1520 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1521 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1522 return NAME_NOT_FOUND;
1523 }
1524
1525 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1526 // This prevents creating an offloaded track and tearing it down immediately after start
1527 // when audioflinger detects there is an active non offloadable effect.
1528 // FIXME: We should check the audio session here but we do not have it in this context.
1529 // This may prevent offloading in rare situations where effects are left active by apps
1530 // in the background.
1531 sp<IOProfile> profile;
1532 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1533 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1534 profile = getProfileForOutput(
1535 devices, config->sample_rate, config->format, config->channel_mask,
1536 flags, true /* directOnly */);
1537 }
1538
1539 if (profile == nullptr) {
1540 return NAME_NOT_FOUND;
1541 }
1542
1543 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1544 for (size_t i = 0; i < mOutputs.size(); i++) {
1545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1546 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1547 // reuse direct output if currently open by the same client
1548 // and configured with same parameters
1549 if ((config->sample_rate == desc->getSamplingRate()) &&
1550 (config->format == desc->getFormat()) &&
1551 (config->channel_mask == desc->getChannelMask()) &&
1552 (session == desc->mDirectClientSession)) {
1553 desc->mDirectOpenCount++;
1554 ALOGV("%s reusing direct output %d for session %d", __func__,
1555 mOutputs.keyAt(i), session);
1556 *output = mOutputs.keyAt(i);
1557 return NO_ERROR;
1558 }
1559 }
1560 }
1561
1562 if (!profile->canOpenNewIo()) {
1563 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1564 return NAME_NOT_FOUND;
1565 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1566 // MMAP gracefully handles lack of an exclusive track resource by mixing
1567 // above the audio framework. For AAudio to know that the limit is reached,
1568 // return an error.
1569 return NAME_NOT_FOUND;
1570 } else {
1571 // Close outputs on this profile, if available, to free resources for this request
1572 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1573 const auto desc = mOutputs.valueAt(i);
1574 if (desc->mProfile == profile) {
1575 closeOutput(desc->mIoHandle);
1576 }
1577 }
1578 }
1579 }
1580
1581 // Unable to close streams to find free resources for this request
1582 if (!profile->canOpenNewIo()) {
1583 return NAME_NOT_FOUND;
1584 }
1585
1586 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
1587
1588 // An MSD patch may be using the only output stream that can service this request. Release
1589 // all MSD patches to prioritize this request over any active output on MSD.
1590 releaseMsdOutputPatches(devices);
1591
1592 status_t status =
1593 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
1594
1595 // only accept an output with the requested parameters
1596 if (status != NO_ERROR ||
1597 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1598 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1599 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1600 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1601 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1602 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1603 config->channel_mask, outputDesc->getChannelMask());
1604 if (*output != AUDIO_IO_HANDLE_NONE) {
1605 outputDesc->close();
1606 }
1607 // fall back to mixer output if possible when the direct output could not be open
1608 if (audio_is_linear_pcm(config->format) &&
1609 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1610 return NAME_NOT_FOUND;
1611 }
1612 *output = AUDIO_IO_HANDLE_NONE;
1613 return BAD_VALUE;
1614 }
1615 outputDesc->mDirectOpenCount = 1;
1616 outputDesc->mDirectClientSession = session;
1617
1618 addOutput(*output, outputDesc);
1619 setOutputDevices(__func__, outputDesc,
1620 devices,
1621 true,
1622 0,
1623 NULL);
1624 mPreviousOutputs = mOutputs;
1625 ALOGV("%s returns new direct output %d", __func__, *output);
1626 mpClientInterface->onAudioPortListUpdate();
1627 return NO_ERROR;
1628 }
1629
getOutputForDevices(const DeviceVector & devices,audio_session_t session,const audio_attributes_t * attr,const audio_config_t * config,audio_output_flags_t * flags,bool * isSpatialized,sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,bool forceMutingHaptic)1630 audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1631 const DeviceVector &devices,
1632 audio_session_t session,
1633 const audio_attributes_t *attr,
1634 const audio_config_t *config,
1635 audio_output_flags_t *flags,
1636 bool *isSpatialized,
1637 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
1638 bool forceMutingHaptic)
1639 {
1640 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
1641
1642 // Discard haptic channel mask when forcing muting haptic channels.
1643 audio_channel_mask_t channelMask = forceMutingHaptic
1644 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1645 : config->channel_mask;
1646
1647 // open a direct output if required by specified parameters
1648 //force direct flag if offload flag is set: offloading implies a direct output stream
1649 // and all common behaviors are driven by checking only the direct flag
1650 // this should normally be set appropriately in the policy configuration file
1651 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1652 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1653 }
1654 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1655 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
1656 }
1657
1658 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1659
1660 // only allow deep buffering for music stream type
1661 if (stream != AUDIO_STREAM_MUSIC) {
1662 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1663 } else if (/* stream == AUDIO_STREAM_MUSIC && */
1664 *flags == AUDIO_OUTPUT_FLAG_NONE &&
1665 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1666 // use DEEP_BUFFER as default output for music stream type
1667 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1668 }
1669 if (stream == AUDIO_STREAM_TTS) {
1670 *flags = AUDIO_OUTPUT_FLAG_TTS;
1671 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
1672 audio_is_linear_pcm(config->format) &&
1673 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
1674 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
1675 AUDIO_OUTPUT_FLAG_DIRECT);
1676 ALOGV("Set VoIP and Direct output flags for PCM format");
1677 }
1678
1679 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1680 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1681 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1682 }
1683
1684 // Use the spatializer output if the content can be spatialized, no preferred mixer
1685 // was specified and offload or direct playback is not explicitly requested, and there is no
1686 // haptic channel included in playback
1687 *isSpatialized = false;
1688 if (mSpatializerOutput != nullptr &&
1689 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1690 prefMixerConfigInfo == nullptr &&
1691 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1692 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
1693 *isSpatialized = true;
1694 return mSpatializerOutput->mIoHandle;
1695 }
1696
1697 audio_config_t directConfig = *config;
1698 directConfig.channel_mask = channelMask;
1699 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1700 if (status != NAME_NOT_FOUND) {
1701 return output;
1702 }
1703
1704 // A request for HW A/V sync cannot fallback to a mixed output because time
1705 // stamps are embedded in audio data
1706 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1707 return AUDIO_IO_HANDLE_NONE;
1708 }
1709 // A request for Tuner cannot fallback to a mixed output
1710 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1711 return AUDIO_IO_HANDLE_NONE;
1712 }
1713
1714 // ignoring channel mask due to downmix capability in mixer
1715
1716 // open a non direct output
1717
1718 // for non direct outputs, only PCM is supported
1719 if (audio_is_linear_pcm(config->format)) {
1720 // get which output is suitable for the specified stream. The actual
1721 // routing change will happen when startOutput() will be called
1722 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
1723 if (prefMixerConfigInfo != nullptr) {
1724 for (audio_io_handle_t outputHandle : outputs) {
1725 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1726 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1727 output = outputHandle;
1728 break;
1729 }
1730 }
1731 if (output == AUDIO_IO_HANDLE_NONE) {
1732 // No output open with the preferred profile. Open a new one.
1733 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1734 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1735 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1736 config.format = prefMixerConfigInfo->getConfigBase().format;
1737 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1738 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1739 &config, prefMixerConfigInfo->getFlags());
1740 if (preferredOutput == nullptr) {
1741 ALOGE("%s failed to open output with preferred mixer config", __func__);
1742 } else {
1743 output = preferredOutput->mIoHandle;
1744 }
1745 }
1746 } else {
1747 // at this stage we should ignore the DIRECT flag as no direct output could be
1748 // found earlier
1749 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1750 if (com::android::media::audioserver::
1751 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1752 // If the preferred mixer attributes is null, do not select the bit-perfect output
1753 // unless the bit-perfect output is the only output.
1754 // The bit-perfect output can exist while the passed in preferred mixer attributes
1755 // info is null when it is a high priority client. The high priority clients are
1756 // ringtone or alarm, which is not a bit-perfect use case.
1757 size_t i = 0;
1758 while (i < outputs.size() && outputs.size() > 1) {
1759 auto desc = mOutputs.valueFor(outputs[i]);
1760 // The output descriptor must not be null here.
1761 if (desc->isBitPerfect()) {
1762 outputs.removeItemsAt(i);
1763 } else {
1764 i += 1;
1765 }
1766 }
1767 }
1768 output = selectOutput(
1769 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1770 }
1771 }
1772 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
1773 "sampling rate %d, format %#x, channels %#x, flags %#x",
1774 stream, config->sample_rate, config->format, channelMask, *flags);
1775
1776 return output;
1777 }
1778
getMsdAudioInDevice() const1779 sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
1780 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1781 mAvailableInputDevices);
1782 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1783 }
1784
getMsdAudioOutDevices() const1785 DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1786 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1787 mAvailableOutputDevices);
1788 }
1789
getMsdOutputPatches() const1790 const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
1791 AudioPatchCollection msdPatches;
1792 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1793 if (msdModule != 0) {
1794 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1795 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1796 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1797 const struct audio_port_config *source = &patch->mPatch.sources[j];
1798 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1799 source->ext.device.hw_module == msdModule->getHandle()) {
1800 msdPatches.addAudioPatch(patch->getHandle(), patch);
1801 }
1802 }
1803 }
1804 }
1805 return msdPatches;
1806 }
1807
isMsdPatch(const audio_patch_handle_t & handle) const1808 bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1809 ssize_t index = mAudioPatches.indexOfKey(handle);
1810 if (index < 0) {
1811 return false;
1812 }
1813 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1814 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1815 if (msdModule == nullptr) {
1816 return false;
1817 }
1818 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1819 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1820 return true;
1821 }
1822 index = getMsdOutputPatches().indexOfKey(handle);
1823 if (index < 0) {
1824 return false;
1825 }
1826 return true;
1827 }
1828
getMsdProfiles(bool hwAvSync,const InputProfileCollection & inputProfiles,const OutputProfileCollection & outputProfiles,const sp<DeviceDescriptor> & sourceDevice,const sp<DeviceDescriptor> & sinkDevice,AudioProfileVector & sourceProfiles,AudioProfileVector & sinkProfiles) const1829 status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1830 const InputProfileCollection &inputProfiles,
1831 const OutputProfileCollection &outputProfiles,
1832 const sp<DeviceDescriptor> &sourceDevice,
1833 const sp<DeviceDescriptor> &sinkDevice,
1834 AudioProfileVector& sourceProfiles,
1835 AudioProfileVector& sinkProfiles) const {
1836 if (inputProfiles.isEmpty()) {
1837 ALOGE("%s() no input profiles for source module", __func__);
1838 return NO_INIT;
1839 }
1840 if (outputProfiles.isEmpty()) {
1841 ALOGE("%s() no output profiles for sink module", __func__);
1842 return NO_INIT;
1843 }
1844 for (const auto &inProfile : inputProfiles) {
1845 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1846 inProfile->supportsDevice(sourceDevice)) {
1847 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
1848 }
1849 }
1850 for (const auto &outProfile : outputProfiles) {
1851 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
1852 outProfile->supportsDevice(sinkDevice)) {
1853 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
1854 }
1855 }
1856 return NO_ERROR;
1857 }
1858
getBestMsdConfig(bool hwAvSync,const AudioProfileVector & sourceProfiles,const AudioProfileVector & sinkProfiles,audio_port_config * sourceConfig,audio_port_config * sinkConfig) const1859 status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1860 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1861 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1862 {
1863 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1864 static const std::vector<audio_format_t> formatsOrder = {{
1865 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1866 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1867 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
1868 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1869 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1870 // preferred).
1871 std::vector<audio_channel_mask_t> masks = {{
1872 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1873 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1874 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1875 // insert index masks (higher counts most preferred) as preferred over position masks
1876 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1877 masks.insert(
1878 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1879 }
1880 return masks;
1881 }();
1882
1883 struct audio_config_base bestSinkConfig;
1884 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1885 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
1886 if (result != NO_ERROR) {
1887 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1888 __func__, hwAvSync);
1889 return result;
1890 }
1891 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1892 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1893 sinkConfig->format = bestSinkConfig.format;
1894 // For encoded streams force direct flag to prevent downstream mixing.
1895 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1896 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
1897 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1898 // For formats compatible with IEC61937 encapsulation, assume that
1899 // the input is IEC61937 framed (for proportional buffer sizing).
1900 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1901 // raw and IEC61937 framed streams.
1902 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1903 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1904 }
1905 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1906 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1907 sourceConfig->channel_mask =
1908 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1909 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1910 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1911 sourceConfig->format = bestSinkConfig.format;
1912 // Copy input stream directly without any processing (e.g. resampling).
1913 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1914 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1915 if (hwAvSync) {
1916 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1917 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1918 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1919 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1920 }
1921 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1922 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1923 sinkConfig->config_mask |= config_mask;
1924 sourceConfig->config_mask |= config_mask;
1925 return NO_ERROR;
1926 }
1927
buildMsdPatch(bool msdIsSource,const sp<DeviceDescriptor> & device) const1928 PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1929 const sp<DeviceDescriptor> &device) const
1930 {
1931 PatchBuilder patchBuilder;
1932 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1933 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1934 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1935 if (deviceModule == nullptr) {
1936 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1937 return patchBuilder;
1938 }
1939 const InputProfileCollection inputProfiles = msdIsSource ?
1940 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1941 const OutputProfileCollection outputProfiles = msdIsSource ?
1942 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1943
1944 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1945 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1946 device : getMsdAudioOutDevices().itemAt(0);
1947 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1948
1949 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1950 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
1951 AudioProfileVector sourceProfiles;
1952 AudioProfileVector sinkProfiles;
1953 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1954 // For now, we just forcefully try with HwAvSync first.
1955 for (auto hwAvSync : { true, false }) {
1956 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1957 sourceProfiles, sinkProfiles) != NO_ERROR) {
1958 continue;
1959 }
1960 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1961 &sinkConfig) == NO_ERROR) {
1962 // Found a matching config. Re-create PatchBuilder with this config.
1963 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1964 }
1965 }
1966 ALOGV("%s() no matching config found. Fall through to default PCM patch"
1967 " supporting PCM format conversion.", __func__);
1968 return patchBuilder;
1969 }
1970
setMsdOutputPatches(const DeviceVector * outputDevices)1971 status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
1972 DeviceVector devices;
1973 if (outputDevices != nullptr && outputDevices->size() > 0) {
1974 devices.add(*outputDevices);
1975 } else {
1976 // Use media strategy for unspecified output device. This should only
1977 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1978 // therefore invalidate explicit routing requests.
1979 devices = mEngine->getOutputDevicesForAttributes(
1980 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
1981 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
1982 }
1983 std::vector<PatchBuilder> patchesToCreate;
1984 for (auto i = 0u; i < devices.size(); ++i) {
1985 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
1986 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
1987 }
1988 // Retain only the MSD patches associated with outputDevices request.
1989 // Tear down the others, and create new ones as needed.
1990 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
1991 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1992 auto retainedPatch = false;
1993 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1994 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1995 patchesToRemove.removeItemsAt(i);
1996 retainedPatch = true;
1997 break;
1998 }
1999 }
2000 if (retainedPatch) {
2001 it = patchesToCreate.erase(it);
2002 continue;
2003 }
2004 ++it;
2005 }
2006 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2007 return NO_ERROR;
2008 }
2009 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2010 auto ¤tPatch = patchesToRemove.valueAt(i);
2011 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
2012 }
2013 status_t status = NO_ERROR;
2014 for (const auto &p : patchesToCreate) {
2015 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2016 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2017 char message[256];
2018 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2019 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2020 currStatus == NO_ERROR ? "Success" : "Error",
2021 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2022 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2023 if (currStatus == NO_ERROR) {
2024 ALOGD("%s", message);
2025 } else {
2026 ALOGE("%s", message);
2027 if (status == NO_ERROR) {
2028 status = currStatus;
2029 }
2030 }
2031 }
2032 return status;
2033 }
2034
releaseMsdOutputPatches(const DeviceVector & devices)2035 void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2036 AudioPatchCollection msdPatches = getMsdOutputPatches();
2037 for (size_t i = 0; i < msdPatches.size(); i++) {
2038 const auto& patch = msdPatches[i];
2039 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2040 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2041 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2042 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2043 releaseAudioPatch(patch->getHandle(), mUidCached);
2044 break;
2045 }
2046 }
2047 }
2048 }
2049
msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector & devices)2050 bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
2051 DeviceVector devicesToCheck =
2052 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
2053 AudioPatchCollection msdPatches = getMsdOutputPatches();
2054 for (size_t i = 0; i < msdPatches.size(); i++) {
2055 const auto& patch = msdPatches[i];
2056 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2057 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2058 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2059 const auto& foundDevice = devicesToCheck.getDevice(
2060 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2061 if (foundDevice != nullptr) {
2062 devicesToCheck.remove(foundDevice);
2063 if (devicesToCheck.isEmpty()) {
2064 return true;
2065 }
2066 }
2067 }
2068 }
2069 }
2070 return false;
2071 }
2072
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,audio_session_t sessionId)2073 audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
2074 audio_output_flags_t flags,
2075 audio_format_t format,
2076 audio_channel_mask_t channelMask,
2077 uint32_t samplingRate,
2078 audio_session_t sessionId)
2079 {
2080 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2081 "%s called with format %#x", __func__, format);
2082
2083 // Return the output that haptic-generating attached to when 1) session id is specified,
2084 // 2) haptic-generating effect exists for given session id and 3) the output that
2085 // haptic-generating effect attached to is in given outputs.
2086 if (sessionId != AUDIO_SESSION_NONE) {
2087 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2088 sessionId, FX_IID_HAPTICGENERATOR);
2089 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2090 return hapticGeneratingOutput;
2091 }
2092 }
2093
2094 // Flags disqualifying an output: the match must happen before calling selectOutput()
2095 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2096 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2097
2098 // Flags expressing a functional request: must be honored in priority over
2099 // other criteria
2100 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2101 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
2102 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2103 AUDIO_OUTPUT_FLAG_SPATIALIZER);
2104 // Flags expressing a performance request: have lower priority than serving
2105 // requested sampling rate or channel mask
2106 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2107 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2108 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2109
2110 const audio_output_flags_t functionalFlags =
2111 (audio_output_flags_t)(flags & kFunctionalFlags);
2112 const audio_output_flags_t performanceFlags =
2113 (audio_output_flags_t)(flags & kPerformanceFlags);
2114
2115 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2116
2117 // select one output among several that provide a path to a particular device or set of
2118 // devices (the list was previously build by getOutputsForDevices()).
2119 // The priority is as follows:
2120 // 1: the output supporting haptic playback when requesting haptic playback
2121 // 2: the output with the highest number of requested functional flags
2122 // with tiebreak preferring the minimum number of extra functional flags
2123 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
2124 // 3: the output supporting the exact channel mask
2125 // 4: the output with a higher channel count than requested
2126 // 5: the output with the highest sampling rate if the requested sample rate is
2127 // greater than default sampling rate
2128 // 6: the output with the highest number of requested performance flags
2129 // 7: the output with the bit depth the closest to the requested one
2130 // 8: the primary output
2131 // 9: the first output in the list
2132
2133 // matching criteria values in priority order for best matching output so far
2134 std::vector<uint32_t> bestMatchCriteria(8, 0);
2135
2136 const bool hasOrphanHaptic =
2137 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
2138 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2139 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2140 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
2141
2142 for (audio_io_handle_t output : outputs) {
2143 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2144 // matching criteria values in priority order for current output
2145 std::vector<uint32_t> currentMatchCriteria(8, 0);
2146
2147 if (outputDesc->isDuplicated()) {
2148 continue;
2149 }
2150 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2151 continue;
2152 }
2153
2154 // If haptic channel is specified, use the haptic output if present.
2155 // When using haptic output, same audio format and sample rate are required.
2156 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
2157 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
2158 // skip if haptic channel specified but output does not support it, or output support haptic
2159 // but there is no haptic channel requested AND no orphan haptic effect exist
2160 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2161 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
2162 continue;
2163 }
2164 // In the case of audio-coupled-haptic playback, there is no format conversion and
2165 // resampling in the framework, same format/channel/sampleRate for client and the output
2166 // thread is required. In the case of HapticGenerator effect, do not require format
2167 // matching.
2168 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2169 samplingRate == outputDesc->getSamplingRate()) ||
2170 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
2171 currentMatchCriteria[0] = outputHapticChannelCount;
2172 }
2173
2174 // functional flags match
2175 const int matchingFunctionalFlags =
2176 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2177 const int totalFunctionalFlags =
2178 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2179 // Prefer matching functional flags, but subtract unnecessary functional flags.
2180 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
2181
2182 // channel mask and channel count match
2183 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2184 outputDesc->getChannelMask());
2185 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2186 channelCount <= outputChannelCount) {
2187 if ((audio_channel_mask_get_representation(channelMask) ==
2188 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2189 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
2190 currentMatchCriteria[2] = outputChannelCount;
2191 }
2192 currentMatchCriteria[3] = outputChannelCount;
2193 }
2194
2195 // sampling rate match
2196 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
2197 int diff; // avoid unsigned integer overflow.
2198 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2199
2200 // prefer the closest output sampling rate greater than or equal to target
2201 // if none exists, prefer the closest output sampling rate less than target.
2202 //
2203 // criteria is offset to make non-negative.
2204 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
2205 }
2206
2207 // performance flags match
2208 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2209
2210 // format match
2211 if (format != AUDIO_FORMAT_INVALID) {
2212 currentMatchCriteria[6] =
2213 PolicyAudioPort::kFormatDistanceMax -
2214 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
2215 }
2216
2217 // primary output match
2218 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2219
2220 // compare match criteria by priority then value
2221 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2222 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2223 bestMatchCriteria = currentMatchCriteria;
2224 bestOutput = output;
2225
2226 std::stringstream result;
2227 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2228 std::ostream_iterator<int>(result, " "));
2229 ALOGV("%s new bestOutput %d criteria %s",
2230 __func__, bestOutput, result.str().c_str());
2231 }
2232 }
2233
2234 return bestOutput;
2235 }
2236
startOutput(audio_port_handle_t portId)2237 status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
2238 {
2239 ALOGV("%s portId %d", __FUNCTION__, portId);
2240
2241 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2242 if (outputDesc == 0) {
2243 ALOGW("startOutput() no output for client %d", portId);
2244 return BAD_VALUE;
2245 }
2246 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2247
2248 ALOGV("startOutput() output %d, stream %d, session %d",
2249 outputDesc->mIoHandle, client->stream(), client->session());
2250
2251 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2252 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2253 && outputDesc->isBitPerfect()) {
2254 // Usually, APM selects bit-perfect output for high priority use cases only when
2255 // bit-perfect output is the only output that can be routed to the selected device.
2256 // However, here is no need to play high priority use cases such as ringtone and alarm
2257 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2258 // can attach to new output.
2259 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2260 __func__, client->stream());
2261 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2262 return DEAD_OBJECT;
2263 }
2264
2265 status_t status = outputDesc->start();
2266 if (status != NO_ERROR) {
2267 return status;
2268 }
2269
2270 uint32_t delayMs;
2271 status = startSource(outputDesc, client, &delayMs);
2272
2273 if (status != NO_ERROR) {
2274 outputDesc->stop();
2275 if (status == DEAD_OBJECT) {
2276 sp<SwAudioOutputDescriptor> desc =
2277 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2278 if (desc == nullptr) {
2279 // This is not common, it may indicate something wrong with the HAL.
2280 ALOGE("%s unable to open output with default config", __func__);
2281 return status;
2282 }
2283 }
2284 return status;
2285 }
2286
2287 // If the client is the first one active on preferred mixer parameters, reopen the output
2288 // if the current mixer parameters doesn't match the preferred one.
2289 if (outputDesc->devices().size() == 1) {
2290 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2291 outputDesc->devices()[0]->getId(), client->strategy());
2292 if (info != nullptr && info->getUid() == client->uid()) {
2293 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2294 info->getConfigBase(), info->getFlags())) {
2295 stopSource(outputDesc, client);
2296 outputDesc->stop();
2297 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2298 config.channel_mask = info->getConfigBase().channel_mask;
2299 config.sample_rate = info->getConfigBase().sample_rate;
2300 config.format = info->getConfigBase().format;
2301 sp<SwAudioOutputDescriptor> desc =
2302 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2303 if (desc == nullptr) {
2304 return BAD_VALUE;
2305 }
2306 desc->mPreferredAttrInfo = info;
2307 // Intentionally return error to let the client side resending request for
2308 // creating and starting.
2309 return DEAD_OBJECT;
2310 }
2311 info->increaseActiveClient();
2312 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
2313 // If it is first bit-perfect client, reroute all clients that will be routed to
2314 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2315 PortHandleVector clientsToInvalidate;
2316 for (size_t i = 0; i < mOutputs.size(); i++) {
2317 if (mOutputs[i] == outputDesc ||
2318 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
2319 continue;
2320 }
2321 for (const auto& c : mOutputs[i]->getClientIterable()) {
2322 clientsToInvalidate.push_back(c->portId());
2323 }
2324 }
2325 if (!clientsToInvalidate.empty()) {
2326 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2327 __func__);
2328 mpClientInterface->invalidateTracks(clientsToInvalidate);
2329 }
2330 }
2331 }
2332 }
2333
2334 if (client->hasPreferredDevice()) {
2335 // playback activity with preferred device impacts routing occurred, inform upper layers
2336 mpClientInterface->onRoutingUpdated();
2337 }
2338 if (delayMs != 0) {
2339 usleep(delayMs * 1000);
2340 }
2341
2342 if (status == NO_ERROR &&
2343 outputDesc->mPreferredAttrInfo != nullptr &&
2344 outputDesc->isBitPerfect() &&
2345 com::android::media::audioserver::
2346 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2347 // A new client is started on bit-perfect output, update all clients internal mute.
2348 updateClientsInternalMute(outputDesc);
2349 }
2350
2351 return status;
2352 }
2353
isLeUnicastActive() const2354 bool AudioPolicyManager::isLeUnicastActive() const {
2355 if (isInCall()) {
2356 return true;
2357 }
2358 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2359 }
2360
isAnyDeviceTypeActive(const DeviceTypeSet & deviceTypes) const2361 bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2362 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2363 return false;
2364 }
2365 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2366 ALOGV("%s active %d", __func__, active);
2367 return active;
2368 }
2369
startSource(const sp<SwAudioOutputDescriptor> & outputDesc,const sp<TrackClientDescriptor> & client,uint32_t * delayMs)2370 status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2371 const sp<TrackClientDescriptor>& client,
2372 uint32_t *delayMs)
2373 {
2374 // cannot start playback of STREAM_TTS if any other output is being used
2375 uint32_t beaconMuteLatency = 0;
2376
2377 *delayMs = 0;
2378 audio_stream_type_t stream = client->stream();
2379 auto clientVolSrc = client->volumeSource();
2380 auto clientStrategy = client->strategy();
2381 auto clientAttr = client->attributes();
2382 if (stream == AUDIO_STREAM_TTS) {
2383 ALOGV("\t found BEACON stream");
2384 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
2385 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
2386 return INVALID_OPERATION;
2387 } else {
2388 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2389 }
2390 } else {
2391 // some playback other than beacon starts
2392 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2393 }
2394
2395 // force device change if the output is inactive and no audio patch is already present.
2396 // check active before incrementing usage count
2397 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
2398
2399 DeviceVector devices;
2400 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
2401 const char *address = NULL;
2402 if (policyMix != nullptr) {
2403 audio_devices_t newDeviceType;
2404 address = policyMix->mDeviceAddress.c_str();
2405 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
2406 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
2407 } else {
2408 newDeviceType = policyMix->mDeviceType;
2409 }
2410 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2411 AUDIO_FORMAT_DEFAULT);
2412 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2413 devices.add(device);
2414 }
2415
2416 // requiresMuteCheck is false when we can bypass mute strategy.
2417 // It covers a common case when there is no materially active audio
2418 // and muting would result in unnecessary delay and dropped audio.
2419 const uint32_t outputLatencyMs = outputDesc->latency();
2420 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
2421 bool wasLeUnicastActive = isLeUnicastActive();
2422
2423 // increment usage count for this stream on the requested output:
2424 // NOTE that the usage count is the same for duplicated output and hardware output which is
2425 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
2426 outputDesc->setClientActive(client, true);
2427
2428 if (client->hasPreferredDevice(true)) {
2429 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
2430 // Preferred device may be exclusive, use only if no other active clients on this output
2431 devices = DeviceVector(
2432 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2433 } else {
2434 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2435 }
2436 if (devices != outputDesc->devices()) {
2437 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
2438 }
2439 }
2440
2441 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
2442 selectOutputForMusicEffects();
2443 }
2444
2445 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
2446 // starting an output being rerouted?
2447 if (devices.isEmpty()) {
2448 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2449 }
2450 bool shouldWait =
2451 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2452 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2453 (beaconMuteLatency > 0));
2454 uint32_t waitMs = beaconMuteLatency;
2455 const bool needToCloseBitPerfectOutput =
2456 (com::android::media::audioserver::
2457 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2458 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2459 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
2460 for (size_t i = 0; i < mOutputs.size(); i++) {
2461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2462 if (desc != outputDesc) {
2463 // An output has a shared device if
2464 // - managed by the same hw module
2465 // - supports the currently selected device
2466 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
2467 && (!desc->filterSupportedDevices(devices).isEmpty());
2468
2469 // force a device change if any other output is:
2470 // - managed by the same hw module
2471 // - supports currently selected device
2472 // - has a current device selection that differs from selected device.
2473 // - has an active audio patch
2474 // In this case, the audio HAL must receive the new device selection so that it can
2475 // change the device currently selected by the other output.
2476 if (sharedDevice &&
2477 desc->devices() != devices &&
2478 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2479 force = true;
2480 }
2481 // wait for audio on other active outputs to be presented when starting
2482 // a notification so that audio focus effect can propagate, or that a mute/unmute
2483 // event occurred for beacon
2484 const uint32_t latencyMs = desc->latency();
2485 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2486
2487 if (shouldWait && isActive && (waitMs < latencyMs)) {
2488 waitMs = latencyMs;
2489 }
2490
2491 // Require mute check if another output is on a shared device
2492 // and currently active to have proper drain and avoid pops.
2493 // Note restoring AudioTracks onto this output needs to invoke
2494 // a volume ramp if there is no mute.
2495 requiresMuteCheck |= sharedDevice && isActive;
2496
2497 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2498 outputsToReopen.push_back(desc);
2499 }
2500 }
2501 }
2502
2503 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
2504 // If the output is open with preferred mixer attributes, but the routed device is
2505 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2506 // changed.
2507 return DEAD_OBJECT;
2508 }
2509 for (auto& outputToReopen : outputsToReopen) {
2510 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2511 }
2512 const uint32_t muteWaitMs =
2513 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2514 requiresMuteCheck);
2515
2516 // apply volume rules for current stream and device if necessary
2517 auto &curves = getVolumeCurves(client->attributes());
2518 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
2519 curves.getVolumeIndex(outputDesc->devices().types()),
2520 outputDesc,
2521 outputDesc->devices().types(), 0 /*delay*/,
2522 outputDesc->useHwGain() /*force*/)) {
2523 // request AudioService to reinitialize the volume curves asynchronously
2524 ALOGE("checkAndSetVolume failed, requesting volume range init");
2525 mpClientInterface->onVolumeRangeInitRequest();
2526 };
2527
2528 // update the outputs if starting an output with a stream that can affect notification
2529 // routing
2530 handleNotificationRoutingForStream(stream);
2531
2532 // force reevaluating accessibility routing when ringtone or alarm starts
2533 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
2534 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
2535 }
2536
2537 if (waitMs > muteWaitMs) {
2538 *delayMs = waitMs - muteWaitMs;
2539 }
2540
2541 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2542 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2543 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2544 // change occurs after the MixerThread starts and causes a stream volume
2545 // glitch.
2546 //
2547 // We do not introduce additional delay here.
2548 }
2549
2550 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2551 mEngine->getForceUse(
2552 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
2553 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
2554 }
2555
2556 // Automatically enable the remote submix input when output is started on a re routing mix
2557 // of type MIX_TYPE_RECORDERS
2558 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2559 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
2560 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2561 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2562 address,
2563 "remote-submix",
2564 AUDIO_FORMAT_DEFAULT);
2565 }
2566
2567 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2568
2569 return NO_ERROR;
2570 }
2571
checkLeBroadcastRoutes(bool wasUnicastActive,sp<SwAudioOutputDescriptor> ignoredOutput,uint32_t delayMs)2572 void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2573 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2574 bool isUnicastActive = isLeUnicastActive();
2575
2576 if (wasUnicastActive != isUnicastActive) {
2577 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
2578 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2579 for (size_t i = 0; i < mOutputs.size(); i++) {
2580 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2581 if (desc != ignoredOutput && desc->isActive()
2582 && ((isUnicastActive &&
2583 !desc->devices().
2584 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2585 || (wasUnicastActive &&
2586 !desc->devices().getDevicesFromTypes(
2587 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2588 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2589 bool force = desc->devices() != newDevices;
2590 if (desc->mPreferredAttrInfo != nullptr && force) {
2591 // If the device is using preferred mixer attributes, the output need to reopen
2592 // with default configuration when the new selected devices are different from
2593 // current routing devices.
2594 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2595 continue;
2596 }
2597 setOutputDevices(__func__, desc, newDevices, force, delayMs);
2598 // re-apply device specific volume if not done by setOutputDevice()
2599 if (!force) {
2600 applyStreamVolumes(desc, newDevices.types(), delayMs);
2601 }
2602 }
2603 }
2604 reopenOutputsWithDevices(outputsToReopen);
2605 }
2606 }
2607
stopOutput(audio_port_handle_t portId)2608 status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
2609 {
2610 ALOGV("%s portId %d", __FUNCTION__, portId);
2611
2612 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2613 if (outputDesc == 0) {
2614 ALOGW("stopOutput() no output for client %d", portId);
2615 return BAD_VALUE;
2616 }
2617 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2618
2619 if (client->hasPreferredDevice(true)) {
2620 // playback activity with preferred device impacts routing occurred, inform upper layers
2621 mpClientInterface->onRoutingUpdated();
2622 }
2623
2624 ALOGV("stopOutput() output %d, stream %d, session %d",
2625 outputDesc->mIoHandle, client->stream(), client->session());
2626
2627 status_t status = stopSource(outputDesc, client);
2628
2629 if (status == NO_ERROR ) {
2630 outputDesc->stop();
2631 } else {
2632 return status;
2633 }
2634
2635 if (outputDesc->devices().size() == 1) {
2636 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2637 outputDesc->devices()[0]->getId(), client->strategy());
2638 bool outputReopened = false;
2639 if (info != nullptr && info->getUid() == client->uid()) {
2640 info->decreaseActiveClient();
2641 if (info->getActiveClientCount() == 0) {
2642 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2643 outputReopened = true;
2644 }
2645 }
2646 if (com::android::media::audioserver::
2647 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2648 !outputReopened && outputDesc->isBitPerfect()) {
2649 // Only need to update the clients' internal mute when the output is bit-perfect and it
2650 // is not reopened.
2651 updateClientsInternalMute(outputDesc);
2652 }
2653 }
2654 return status;
2655 }
2656
stopSource(const sp<SwAudioOutputDescriptor> & outputDesc,const sp<TrackClientDescriptor> & client)2657 status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2658 const sp<TrackClientDescriptor>& client)
2659 {
2660 // always handle stream stop, check which stream type is stopping
2661 audio_stream_type_t stream = client->stream();
2662 auto clientVolSrc = client->volumeSource();
2663 bool wasLeUnicastActive = isLeUnicastActive();
2664
2665 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2666
2667 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2668 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
2669 // Automatically disable the remote submix input when output is stopped on a
2670 // re routing mix of type MIX_TYPE_RECORDERS
2671 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
2672 if (isSingleDeviceType(
2673 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
2674 policyMix != nullptr &&
2675 policyMix->mMixType == MIX_TYPE_RECORDERS) {
2676 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2677 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2678 policyMix->mDeviceAddress,
2679 "remote-submix", AUDIO_FORMAT_DEFAULT);
2680 }
2681 }
2682 bool forceDeviceUpdate = false;
2683 if (client->hasPreferredDevice(true) &&
2684 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
2685 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
2686 forceDeviceUpdate = true;
2687 }
2688
2689 // decrement usage count of this stream on the output
2690 outputDesc->setClientActive(client, false);
2691
2692 // store time at which the stream was stopped - see isStreamActive()
2693 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
2694 outputDesc->setStopTime(client, systemTime());
2695 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2696
2697 // If the routing does not change, if an output is routed on a device using HwGain
2698 // (aka setAudioPortConfig) and there are still active clients following different
2699 // volume group(s), force reapply volume
2700 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2701 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2702
2703 // delay the device switch by twice the latency because stopOutput() is executed when
2704 // the track stop() command is received and at that time the audio track buffer can
2705 // still contain data that needs to be drained. The latency only covers the audio HAL
2706 // and kernel buffers. Also the latency does not always include additional delay in the
2707 // audio path (audio DSP, CODEC ...)
2708 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
2709 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
2710
2711 // force restoring the device selection on other active outputs if it differs from the
2712 // one being selected for this output
2713 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
2714 uint32_t delayMs = outputDesc->latency()*2;
2715 for (size_t i = 0; i < mOutputs.size(); i++) {
2716 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2717 if (desc != outputDesc &&
2718 desc->isActive() &&
2719 outputDesc->sharesHwModuleWith(desc) &&
2720 (newDevices != desc->devices())) {
2721 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2722 bool force = desc->devices() != newDevices2;
2723
2724 if (desc->mPreferredAttrInfo != nullptr && force) {
2725 // If the device is using preferred mixer attributes, the output need to
2726 // reopen with default configuration when the new selected devices are
2727 // different from current routing devices.
2728 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2729 continue;
2730 }
2731 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
2732
2733 // re-apply device specific volume if not done by setOutputDevice()
2734 if (!force) {
2735 applyStreamVolumes(desc, newDevices2.types(), delayMs);
2736 }
2737 }
2738 }
2739 reopenOutputsWithDevices(outputsToReopen);
2740 // update the outputs if stopping one with a stream that can affect notification routing
2741 handleNotificationRoutingForStream(stream);
2742 }
2743
2744 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2745 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
2746 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
2747 }
2748
2749 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
2750 selectOutputForMusicEffects();
2751 }
2752
2753 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2754
2755 return NO_ERROR;
2756 } else {
2757 ALOGW("stopOutput() refcount is already 0");
2758 return INVALID_OPERATION;
2759 }
2760 }
2761
releaseOutput(audio_port_handle_t portId)2762 bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
2763 {
2764 ALOGV("%s portId %d", __FUNCTION__, portId);
2765
2766 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2767 if (outputDesc == 0) {
2768 // If an output descriptor is closed due to a device routing change,
2769 // then there are race conditions with releaseOutput from tracks
2770 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2771 // destroyed shortly thereafter.
2772 //
2773 // Here we just log a warning, instead of a fatal error.
2774 ALOGW("releaseOutput() no output for client %d", portId);
2775 return false;
2776 }
2777
2778 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
2779
2780 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2781 if (outputDesc->isClientActive(client)) {
2782 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2783 stopOutput(portId);
2784 }
2785
2786 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2787 if (outputDesc->mDirectOpenCount <= 0) {
2788 ALOGW("releaseOutput() invalid open count %d for output %d",
2789 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
2790 return false;
2791 }
2792 if (--outputDesc->mDirectOpenCount == 0) {
2793 closeOutput(outputDesc->mIoHandle);
2794 mpClientInterface->onAudioPortListUpdate();
2795 }
2796 }
2797
2798 outputDesc->removeClient(portId);
2799 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2800 // The output is pending reopened to query dynamic profiles and
2801 // there is no active clients
2802 closeOutput(outputDesc->mIoHandle);
2803 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2804 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2805 if (newOutputDesc == nullptr) {
2806 ALOGE("%s failed to open output", __func__);
2807 }
2808 return true;
2809 }
2810 return false;
2811 }
2812
getInputForAttr(const audio_attributes_t * attr,audio_io_handle_t * input,audio_unique_id_t riid,audio_session_t session,const AttributionSourceState & attributionSource,audio_config_base_t * config,audio_input_flags_t flags,audio_port_handle_t * selectedDeviceId,input_type_t * inputType,audio_port_handle_t * portId,uint32_t * virtualDeviceId)2813 status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2814 audio_io_handle_t *input,
2815 audio_unique_id_t riid,
2816 audio_session_t session,
2817 const AttributionSourceState& attributionSource,
2818 audio_config_base_t *config,
2819 audio_input_flags_t flags,
2820 audio_port_handle_t *selectedDeviceId,
2821 input_type_t *inputType,
2822 audio_port_handle_t *portId,
2823 uint32_t *virtualDeviceId)
2824 {
2825 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
2826 "flags %#x attributes=%s requested device ID %d",
2827 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2828 session, flags, toString(*attr).c_str(), *selectedDeviceId);
2829
2830 status_t status = NO_ERROR;
2831 audio_attributes_t attributes = *attr;
2832 sp<AudioPolicyMix> policyMix;
2833 sp<DeviceDescriptor> device;
2834 sp<AudioInputDescriptor> inputDesc;
2835 sp<AudioInputDescriptor> previousInputDesc;
2836 sp<RecordClientDescriptor> clientDesc;
2837 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
2838 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
2839 bool isSoundTrigger;
2840
2841 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2842 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2843 return INVALID_OPERATION;
2844 }
2845
2846 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2847 attributes.source = AUDIO_SOURCE_MIC;
2848 }
2849
2850 // Explicit routing?
2851 sp<DeviceDescriptor> explicitRoutingDevice =
2852 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
2853
2854 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2855 // possible
2856 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2857 *input != AUDIO_IO_HANDLE_NONE) {
2858 ssize_t index = mInputs.indexOfKey(*input);
2859 if (index < 0) {
2860 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2861 status = BAD_VALUE;
2862 goto error;
2863 }
2864 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
2865 RecordClientVector clients = inputDesc->getClientsForSession(session);
2866 if (clients.size() == 0) {
2867 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2868 status = BAD_VALUE;
2869 goto error;
2870 }
2871 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2872 // The second call is for the first active client and sets the UID. Any further call
2873 // corresponds to a new client and is only permitted from the same UID.
2874 // If the first UID is silenced, allow a new UID connection and replace with new UID
2875 if (clients.size() > 1) {
2876 for (const auto& client : clients) {
2877 // The client map is ordered by key values (portId) and portIds are allocated
2878 // incrementaly. So the first client in this list is the one opened by audio flinger
2879 // when the mmap stream is created and should be ignored as it does not correspond
2880 // to an actual client
2881 if (client == *clients.cbegin()) {
2882 continue;
2883 }
2884 if (uid != client->uid() && !client->isSilenced()) {
2885 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2886 uid, client->portId(), client->uid());
2887 status = INVALID_OPERATION;
2888 goto error;
2889 }
2890 }
2891 }
2892 *inputType = API_INPUT_LEGACY;
2893 device = inputDesc->getDevice();
2894
2895 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
2896 goto exit;
2897 }
2898
2899 *input = AUDIO_IO_HANDLE_NONE;
2900 *inputType = API_INPUT_INVALID;
2901
2902 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2903 extractAddressFromAudioAttributes(attributes).has_value()) {
2904 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
2905 if (status != NO_ERROR) {
2906 ALOGW("%s could not find input mix for attr %s",
2907 __func__, toString(attributes).c_str());
2908 goto error;
2909 }
2910 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2911 String8(attr->tags + strlen("addr=")),
2912 AUDIO_FORMAT_DEFAULT);
2913 if (device == nullptr) {
2914 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
2915 __func__, attributes.source, attributes.tags);
2916 status = BAD_VALUE;
2917 goto error;
2918 }
2919
2920 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2921 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2922 } else {
2923 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2924 }
2925 if (virtualDeviceId) {
2926 *virtualDeviceId = policyMix->mVirtualDeviceId;
2927 }
2928 } else {
2929 if (explicitRoutingDevice != nullptr) {
2930 device = explicitRoutingDevice;
2931 } else {
2932 // Prevent from storing invalid requested device id in clients
2933 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
2934 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
2935 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2936 __FUNCTION__, device->type());
2937 }
2938 if (device == nullptr) {
2939 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
2940 status = BAD_VALUE;
2941 goto error;
2942 }
2943 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2944 *inputType = API_INPUT_MIX_CAPTURE;
2945 } else if (policyMix) {
2946 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2947 // there is an external policy, but this input is attached to a mix of recorders,
2948 // meaning it receives audio injected into the framework, so the recorder doesn't
2949 // know about it and is therefore considered "legacy"
2950 *inputType = API_INPUT_LEGACY;
2951
2952 if (virtualDeviceId) {
2953 *virtualDeviceId = policyMix->mVirtualDeviceId;
2954 }
2955 } else if (audio_is_remote_submix_device(device->type())) {
2956 *inputType = API_INPUT_MIX_CAPTURE;
2957 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
2958 *inputType = API_INPUT_TELEPHONY_RX;
2959 } else {
2960 *inputType = API_INPUT_LEGACY;
2961 }
2962
2963 }
2964
2965 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
2966 if (*input == AUDIO_IO_HANDLE_NONE) {
2967 status = INVALID_OPERATION;
2968 AudioProfileVector profiles;
2969 status_t ret = getProfilesForDevices(
2970 DeviceVector(device), profiles, flags, true /*isInput*/);
2971 if (ret == NO_ERROR && !profiles.empty()) {
2972 const auto channels = profiles[0]->getChannels();
2973 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2974 config->channel_mask = *channels.begin();
2975 }
2976 const auto sampleRates = profiles[0]->getSampleRates();
2977 if (!sampleRates.empty() &&
2978 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2979 config->sample_rate = *sampleRates.begin();
2980 }
2981 config->format = profiles[0]->getFormat();
2982 }
2983 goto error;
2984 }
2985
2986
2987 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2988 *virtualDeviceId = policyMix->mVirtualDeviceId;
2989 }
2990
2991 exit:
2992
2993 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2994 device->getId() : AUDIO_PORT_HANDLE_NONE;
2995
2996 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
2997 mSoundTriggerSessions.indexOfKey(session) >= 0;
2998 *portId = PolicyAudioPort::getNextUniqueId();
2999
3000 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
3001 requestedDeviceId, attributes.source, flags,
3002 isSoundTrigger);
3003 inputDesc = mInputs.valueFor(*input);
3004 // Move (if found) effect for the client session to its input
3005 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
3006 inputDesc->addClient(clientDesc);
3007
3008 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3009 *input, *inputType, *selectedDeviceId, *portId);
3010
3011 return NO_ERROR;
3012
3013 error:
3014 return status;
3015 }
3016
3017
getInputForDevice(const sp<DeviceDescriptor> & device,audio_session_t session,const audio_attributes_t & attributes,audio_config_base_t * config,audio_input_flags_t flags,const sp<AudioPolicyMix> & policyMix)3018 audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
3019 audio_session_t session,
3020 const audio_attributes_t &attributes,
3021 audio_config_base_t *config,
3022 audio_input_flags_t flags,
3023 const sp<AudioPolicyMix> &policyMix)
3024 {
3025 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3026 audio_source_t halInputSource = attributes.source;
3027 bool isSoundTrigger = false;
3028
3029 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
3030 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3031 if (index >= 0) {
3032 input = mSoundTriggerSessions.valueFor(session);
3033 isSoundTrigger = true;
3034 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3035 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3036 } else {
3037 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
3038 }
3039 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
3040 audio_is_linear_pcm(config->format)) {
3041 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
3042 }
3043
3044 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3045 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3046 }
3047
3048 // sampling rate and flags may be updated by getInputProfile
3049 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3050 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
3051 audio_format_t profileFormat = config->format;
3052 audio_channel_mask_t profileChannelMask = config->channel_mask;
3053 audio_input_flags_t profileFlags = flags;
3054 // find a compatible input profile (not necessarily identical in parameters)
3055 sp<IOProfile> profile = getInputProfile(
3056 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3057 if (profile == nullptr) {
3058 return input;
3059 }
3060
3061 // Pick input sampling rate if not specified by client
3062 uint32_t samplingRate = config->sample_rate;
3063 if (samplingRate == 0) {
3064 samplingRate = profileSamplingRate;
3065 }
3066
3067 if (profile->getModuleHandle() == 0) {
3068 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
3069 return input;
3070 }
3071
3072 // Reuse an already opened input if a client with the same session ID already exists
3073 // on that input
3074 for (size_t i = 0; i < mInputs.size(); i++) {
3075 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3076 if (desc->mProfile != profile) {
3077 continue;
3078 }
3079 RecordClientVector clients = desc->clientsList();
3080 for (const auto &client : clients) {
3081 if (session == client->session()) {
3082 return desc->mIoHandle;
3083 }
3084 }
3085 }
3086
3087 if (!profile->canOpenNewIo()) {
3088 for (size_t i = 0; i < mInputs.size(); ) {
3089 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3090 if (desc->mProfile != profile) {
3091 i++;
3092 continue;
3093 }
3094 // if sound trigger, reuse input if used by other sound trigger on same session
3095 // else
3096 // reuse input if active client app is not in IDLE state
3097 //
3098 RecordClientVector clients = desc->clientsList();
3099 bool doClose = false;
3100 for (const auto& client : clients) {
3101 if (isSoundTrigger != client->isSoundTrigger()) {
3102 continue;
3103 }
3104 if (client->isSoundTrigger()) {
3105 if (session == client->session()) {
3106 return desc->mIoHandle;
3107 }
3108 continue;
3109 }
3110 if (client->active() && client->appState() != APP_STATE_IDLE) {
3111 return desc->mIoHandle;
3112 }
3113 doClose = true;
3114 }
3115 if (doClose) {
3116 closeInput(desc->mIoHandle);
3117 } else {
3118 i++;
3119 }
3120 }
3121 }
3122
3123 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
3124
3125 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3126 lConfig.sample_rate = profileSamplingRate;
3127 lConfig.channel_mask = profileChannelMask;
3128 lConfig.format = profileFormat;
3129
3130 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
3131
3132 // only accept input with the exact requested set of parameters
3133 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
3134 (profileSamplingRate != lConfig.sample_rate) ||
3135 !audio_formats_match(profileFormat, lConfig.format) ||
3136 (profileChannelMask != lConfig.channel_mask)) {
3137 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
3138 ", format %#x, channel mask %#x",
3139 profileSamplingRate, profileFormat, profileChannelMask);
3140 if (input != AUDIO_IO_HANDLE_NONE) {
3141 inputDesc->close();
3142 }
3143 return AUDIO_IO_HANDLE_NONE;
3144 }
3145
3146 inputDesc->mPolicyMix = policyMix;
3147
3148 addInput(input, inputDesc);
3149 mpClientInterface->onAudioPortListUpdate();
3150
3151 return input;
3152 }
3153
startInput(audio_port_handle_t portId)3154 status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
3155 {
3156 ALOGV("%s portId %d", __FUNCTION__, portId);
3157
3158 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3159 if (inputDesc == 0) {
3160 ALOGW("%s no input for client %d", __FUNCTION__, portId);
3161 return DEAD_OBJECT;
3162 }
3163 audio_io_handle_t input = inputDesc->mIoHandle;
3164 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
3165 if (client->active()) {
3166 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3167 return INVALID_OPERATION;
3168 }
3169
3170 audio_session_t session = client->session();
3171
3172 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
3173
3174 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
3175
3176 status_t status = inputDesc->start();
3177 if (status != NO_ERROR) {
3178 return status;
3179 }
3180
3181 // increment activity count before calling getNewInputDevice() below as only active sessions
3182 // are considered for device selection
3183 inputDesc->setClientActive(client, true);
3184
3185 // indicate active capture to sound trigger service if starting capture from a mic on
3186 // primary HW module
3187 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
3188 if (device != nullptr) {
3189 status = setInputDevice(input, device, true /* force */);
3190 } else {
3191 ALOGW("%s no new input device can be found for descriptor %d",
3192 __FUNCTION__, inputDesc->getId());
3193 status = BAD_VALUE;
3194 }
3195
3196 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
3197 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
3198 // if input maps to a dynamic policy with an activity listener, notify of state change
3199 if ((policyMix != nullptr)
3200 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3201 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
3202 MIX_STATE_MIXING);
3203 }
3204
3205 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3206 if (primaryInputDevices.contains(device) &&
3207 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
3208 mpClientInterface->setSoundTriggerCaptureState(true);
3209 }
3210
3211 // automatically enable the remote submix output when input is started if not
3212 // used by a policy mix of type MIX_TYPE_RECORDERS
3213 // For remote submix (a virtual device), we open only one input per capture request.
3214 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
3215 String8 address = String8("");
3216 if (policyMix == nullptr) {
3217 address = String8("0");
3218 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3219 address = policyMix->mDeviceAddress;
3220 }
3221 if (address != "") {
3222 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3224 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
3225 }
3226 }
3227 } else if (status != NO_ERROR) {
3228 // Restore client activity state.
3229 inputDesc->setClientActive(client, false);
3230 inputDesc->stop();
3231 }
3232
3233 ALOGV("%s input %d source = %d status = %d exit",
3234 __FUNCTION__, input, client->source(), status);
3235
3236 return status;
3237 }
3238
stopInput(audio_port_handle_t portId)3239 status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
3240 {
3241 ALOGV("%s portId %d", __FUNCTION__, portId);
3242
3243 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3244 if (inputDesc == 0) {
3245 ALOGW("%s no input for client %d", __FUNCTION__, portId);
3246 return BAD_VALUE;
3247 }
3248 audio_io_handle_t input = inputDesc->mIoHandle;
3249 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
3250 if (!client->active()) {
3251 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
3252 return INVALID_OPERATION;
3253 }
3254 auto old_source = inputDesc->source();
3255 inputDesc->setClientActive(client, false);
3256
3257 inputDesc->stop();
3258 if (inputDesc->isActive()) {
3259 auto current_source = inputDesc->source();
3260 setInputDevice(input, getNewInputDevice(inputDesc),
3261 old_source != current_source /* force */);
3262 } else {
3263 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
3264 // if input maps to a dynamic policy with an activity listener, notify of state change
3265 if ((policyMix != nullptr)
3266 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3267 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
3268 MIX_STATE_IDLE);
3269 }
3270
3271 // automatically disable the remote submix output when input is stopped if not
3272 // used by a policy mix of type MIX_TYPE_RECORDERS
3273 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
3274 String8 address = String8("");
3275 if (policyMix == nullptr) {
3276 address = String8("0");
3277 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3278 address = policyMix->mDeviceAddress;
3279 }
3280 if (address != "") {
3281 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3282 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3283 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
3284 }
3285 }
3286 resetInputDevice(input);
3287
3288 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3289 // primary HW module
3290 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3291 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
3292 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
3293 mpClientInterface->setSoundTriggerCaptureState(false);
3294 }
3295 inputDesc->clearPreemptedSessions();
3296 }
3297 return NO_ERROR;
3298 }
3299
releaseInput(audio_port_handle_t portId)3300 void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
3301 {
3302 ALOGV("%s portId %d", __FUNCTION__, portId);
3303
3304 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3305 if (inputDesc == 0) {
3306 ALOGW("%s no input for client %d", __FUNCTION__, portId);
3307 return;
3308 }
3309 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
3310 audio_io_handle_t input = inputDesc->mIoHandle;
3311
3312 ALOGV("%s %d", __FUNCTION__, input);
3313
3314 inputDesc->removeClient(portId);
3315
3316 // If no more clients are present in this session, park effects to an orphan chain
3317 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3318 if (clientsOnSession.size() == 0) {
3319 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3320 }
3321 if (inputDesc->getClientCount() > 0) {
3322 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
3323 return;
3324 }
3325
3326 closeInput(input);
3327 mpClientInterface->onAudioPortListUpdate();
3328 ALOGV("%s exit", __FUNCTION__);
3329 }
3330
closeActiveClients(const sp<AudioInputDescriptor> & input)3331 void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
3332 {
3333 RecordClientVector clients = input->clientsList(true);
3334
3335 for (const auto& client : clients) {
3336 closeClient(client->portId());
3337 }
3338 }
3339
closeClient(audio_port_handle_t portId)3340 void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3341 {
3342 stopInput(portId);
3343 releaseInput(portId);
3344 }
3345
checkCloseInput(const sp<AudioInputDescriptor> & input)3346 bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3347 if (input->clientsList().size() == 0
3348 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3349 return true;
3350 }
3351 for (const auto& client : input->clientsList()) {
3352 sp<DeviceDescriptor> device =
3353 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3354 client->session());
3355 if (!input->supportedDevices().contains(device)) {
3356 return true;
3357 }
3358 }
3359 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3360 return false;
3361 }
3362
checkCloseInputs()3363 void AudioPolicyManager::checkCloseInputs() {
3364 // After connecting or disconnecting an input device, close input if:
3365 // - it has no client (was just opened to check profile) OR
3366 // - none of its supported devices are connected anymore OR
3367 // - one of its clients cannot be routed to one of its supported
3368 // devices anymore. Otherwise update device selection
3369 std::vector<audio_io_handle_t> inputsToClose;
3370 for (size_t i = 0; i < mInputs.size(); i++) {
3371 if (checkCloseInput(mInputs.valueAt(i))) {
3372 inputsToClose.push_back(mInputs.keyAt(i));
3373 }
3374 }
3375 for (const audio_io_handle_t handle : inputsToClose) {
3376 ALOGV("%s closing input %d", __func__, handle);
3377 closeInput(handle);
3378 }
3379 }
3380
setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,const char * address __unused,bool enabled,audio_stream_type_t streamToDriveAbs)3381 status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3382 const char *address __unused,
3383 bool enabled,
3384 audio_stream_type_t streamToDriveAbs)
3385 {
3386 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3387 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3388 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3389 toString(streamToDriveAbs).c_str());
3390 return BAD_VALUE;
3391 }
3392
3393 if (enabled) {
3394 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3395 } else {
3396 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3397 }
3398
3399 return NO_ERROR;
3400 }
3401
initStreamVolume(audio_stream_type_t stream,int indexMin,int indexMax)3402 void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
3403 {
3404 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
3405 if (indexMin < 0 || indexMax < 0) {
3406 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3407 return;
3408 }
3409 getVolumeCurves(stream).initVolume(indexMin, indexMax);
3410
3411 // initialize other private stream volumes which follow this one
3412 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3413 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
3414 continue;
3415 }
3416 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
3417 }
3418 }
3419
setStreamVolumeIndex(audio_stream_type_t stream,int index,audio_devices_t device)3420 status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
3421 int index,
3422 audio_devices_t device)
3423 {
3424 auto attributes = mEngine->getAttributesForStreamType(stream);
3425 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3426 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3427 return NO_ERROR;
3428 }
3429 ALOGV("%s: stream %s attributes=%s", __func__,
3430 toString(stream).c_str(), toString(attributes).c_str());
3431 return setVolumeIndexForAttributes(attributes, index, device);
3432 }
3433
getStreamVolumeIndex(audio_stream_type_t stream,int * index,audio_devices_t device)3434 status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
3435 int *index,
3436 audio_devices_t device)
3437 {
3438 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3439 // stream by the engine.
3440 DeviceTypeSet deviceTypes = {device};
3441 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3442 deviceTypes = mEngine->getOutputDevicesForStream(
3443 stream, true /*fromCache*/).types();
3444 }
3445 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
3446 }
3447
setVolumeIndexForAttributes(const audio_attributes_t & attributes,int index,audio_devices_t device)3448 status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
3449 int index,
3450 audio_devices_t device)
3451 {
3452 // Get Volume group matching the Audio Attributes
3453 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3454 if (group == VOLUME_GROUP_NONE) {
3455 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
3456 return BAD_VALUE;
3457 }
3458 ALOGV("%s: group %d matching with %s index %d",
3459 __FUNCTION__, group, toString(attributes).c_str(), index);
3460 status_t status = NO_ERROR;
3461 IVolumeCurves &curves = getVolumeCurves(attributes);
3462 VolumeSource vs = toVolumeSource(group);
3463 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3464 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3465 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3466 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
3467 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3468
3469 status = setVolumeCurveIndex(index, device, curves);
3470 if (status != NO_ERROR) {
3471 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3472 return status;
3473 }
3474
3475 DeviceTypeSet curSrcDevices;
3476 auto curCurvAttrs = curves.getAttributes();
3477 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3478 auto attr = curCurvAttrs.front();
3479 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
3480 } else if (!curves.getStreamTypes().empty()) {
3481 auto stream = curves.getStreamTypes().front();
3482 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
3483 } else {
3484 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3485 return BAD_VALUE;
3486 }
3487 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3488 resetDeviceTypes(curSrcDevices, curSrcDevice);
3489
3490 // update volume on all outputs and streams matching the following:
3491 // - The requested stream (or a stream matching for volume control) is active on the output
3492 // - The device (or devices) selected by the engine for this stream includes
3493 // the requested device
3494 // - For non default requested device, currently selected device on the output is either the
3495 // requested device or one of the devices selected by the engine for this stream
3496 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3497 // no specific device volume value exists for currently selected device.
3498 // - Only apply the volume if the requested device is the desired device for volume control.
3499 for (size_t i = 0; i < mOutputs.size(); i++) {
3500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3501 DeviceTypeSet curDevices = desc->devices().types();
3502
3503 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3504 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
3505 }
3506
3507 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
3508 continue;
3509 }
3510 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3511 curDevices.find(device) == curDevices.end()) {
3512 continue;
3513 }
3514 bool applyVolume = false;
3515 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3516 curSrcDevices.insert(device);
3517 applyVolume = (curSrcDevices.find(
3518 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3519 && Volume::getDeviceForVolume(curSrcDevices) == device;
3520 } else {
3521 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3522 }
3523 if (!applyVolume) {
3524 continue; // next output
3525 }
3526 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3527 // If a higher priority strategy is active, and the output is routed to a device with a
3528 // HW Gain management, do not change the volume
3529 if (desc->useHwGain()) {
3530 applyVolume = false;
3531 // If the volume source is active with higher priority source, ensure at least Sw Muted
3532 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
3533 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3534 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3535 false /*preferredDevice*/);
3536 if (activeClients.empty()) {
3537 continue;
3538 }
3539 bool isPreempted = false;
3540 bool isHigherPriority = productStrategy < strategy;
3541 for (const auto &client : activeClients) {
3542 if (isHigherPriority && (client->volumeSource() != activityVs)) {
3543 ALOGV("%s: Strategy=%d (\nrequester:\n"
3544 " group %d, volumeGroup=%d attributes=%s)\n"
3545 " higher priority source active:\n"
3546 " volumeGroup=%d attributes=%s) \n"
3547 " on output %zu, bailing out", __func__, productStrategy,
3548 group, group, toString(attributes).c_str(),
3549 client->volumeSource(), toString(client->attributes()).c_str(), i);
3550 applyVolume = false;
3551 isPreempted = true;
3552 break;
3553 }
3554 // However, continue for loop to ensure no higher prio clients running on output
3555 if (client->volumeSource() == activityVs) {
3556 applyVolume = true;
3557 }
3558 }
3559 if (isPreempted || applyVolume) {
3560 break;
3561 }
3562 }
3563 if (!applyVolume) {
3564 continue; // next output
3565 }
3566 }
3567 //FIXME: workaround for truncated touch sounds
3568 // delayed volume change for system stream to be removed when the problem is
3569 // handled by system UI
3570 status_t volStatus = checkAndSetVolume(
3571 curves, vs, index, desc, curDevices,
3572 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
3573 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3574 if (volStatus != NO_ERROR) {
3575 status = volStatus;
3576 }
3577 }
3578
3579 // update voice volume if the an active call route exists
3580 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3581 && (curSrcDevices.find(
3582 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3583 != curSrcDevices.end())) {
3584 bool isVoiceVolSrc;
3585 bool isBtScoVolSrc;
3586 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3587 isVoiceVolSrc, isBtScoVolSrc, __func__)
3588 && (isVoiceVolSrc || isBtScoVolSrc)) {
3589 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3590 }
3591 }
3592
3593 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3594 return status;
3595 }
3596
setVolumeCurveIndex(int index,audio_devices_t device,IVolumeCurves & volumeCurves)3597 status_t AudioPolicyManager::setVolumeCurveIndex(int index,
3598 audio_devices_t device,
3599 IVolumeCurves &volumeCurves)
3600 {
3601 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3602 // app that has MODIFY_PHONE_STATE permission.
3603 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3604 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
3605 (index > volumeCurves.getVolumeIndexMax())) {
3606 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3607 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3608 return BAD_VALUE;
3609 }
3610 if (!audio_is_output_device(device)) {
3611 return BAD_VALUE;
3612 }
3613
3614 // Force max volume if stream cannot be muted
3615 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3616
3617 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
3618 volumeCurves.addCurrentVolumeIndex(device, index);
3619 return NO_ERROR;
3620 }
3621
getVolumeIndexForAttributes(const audio_attributes_t & attr,int & index,audio_devices_t device)3622 status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3623 int &index,
3624 audio_devices_t device)
3625 {
3626 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3627 // stream by the engine.
3628 DeviceTypeSet deviceTypes = {device};
3629 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3630 deviceTypes = mEngine->getOutputDevicesForAttributes(
3631 attr, nullptr, true /*fromCache*/).types();
3632 }
3633 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
3634 }
3635
getVolumeIndex(const IVolumeCurves & curves,int & index,const DeviceTypeSet & deviceTypes) const3636 status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3637 int &index,
3638 const DeviceTypeSet& deviceTypes) const
3639 {
3640 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
3641 return BAD_VALUE;
3642 }
3643 index = curves.getVolumeIndex(deviceTypes);
3644 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
3645 return NO_ERROR;
3646 }
3647
getMinVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)3648 status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3649 int &index)
3650 {
3651 index = getVolumeCurves(attr).getVolumeIndexMin();
3652 return NO_ERROR;
3653 }
3654
getMaxVolumeIndexForAttributes(const audio_attributes_t & attr,int & index)3655 status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3656 int &index)
3657 {
3658 index = getVolumeCurves(attr).getVolumeIndexMax();
3659 return NO_ERROR;
3660 }
3661
selectOutputForMusicEffects()3662 audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
3663 {
3664 // select one output among several suitable for global effects.
3665 // The priority is as follows:
3666 // 1: An offloaded output. If the effect ends up not being offloadable,
3667 // AudioFlinger will invalidate the track and the offloaded output
3668 // will be closed causing the effect to be moved to a PCM output.
3669 // 2: A deep buffer output
3670 // 3: The primary output
3671 // 4: the first output in the list
3672
3673 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3674 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
3675 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
3676
3677 if (outputs.size() == 0) {
3678 return AUDIO_IO_HANDLE_NONE;
3679 }
3680
3681 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3682 bool activeOnly = true;
3683
3684 while (output == AUDIO_IO_HANDLE_NONE) {
3685 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3686 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3687 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3688
3689 for (audio_io_handle_t output : outputs) {
3690 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
3691 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
3692 continue;
3693 }
3694 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3695 activeOnly, output, desc->mFlags);
3696 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3697 outputOffloaded = output;
3698 }
3699 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
3700 outputDeepBuffer = output;
3701 }
3702 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
3703 outputPrimary = output;
3704 }
3705 }
3706 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3707 output = outputOffloaded;
3708 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3709 output = outputDeepBuffer;
3710 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3711 output = outputPrimary;
3712 } else {
3713 output = outputs[0];
3714 }
3715 activeOnly = false;
3716 }
3717
3718 if (output != mMusicEffectOutput) {
3719 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3720 mpClientInterface);
3721 mMusicEffectOutput = output;
3722 }
3723
3724 ALOGV("selectOutputForMusicEffects selected output %d", output);
3725 return output;
3726 }
3727
getOutputForEffect(const effect_descriptor_t * desc __unused)3728 audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3729 {
3730 return selectOutputForMusicEffects();
3731 }
3732
registerEffect(const effect_descriptor_t * desc,audio_io_handle_t io,product_strategy_t strategy,int session,int id)3733 status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
3734 audio_io_handle_t io,
3735 product_strategy_t strategy,
3736 int session,
3737 int id)
3738 {
3739 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
3740 ssize_t index = mOutputs.indexOfKey(io);
3741 if (index < 0) {
3742 index = mInputs.indexOfKey(io);
3743 if (index < 0) {
3744 ALOGW("registerEffect() unknown io %d", io);
3745 return INVALID_OPERATION;
3746 }
3747 }
3748 }
3749 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3750 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3751 || strategy == PRODUCT_STRATEGY_NONE));
3752 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
3753 }
3754
unregisterEffect(int id)3755 status_t AudioPolicyManager::unregisterEffect(int id)
3756 {
3757 if (mEffects.getEffect(id) == nullptr) {
3758 return INVALID_OPERATION;
3759 }
3760 if (mEffects.isEffectEnabled(id)) {
3761 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3762 setEffectEnabled(id, false);
3763 }
3764 return mEffects.unregisterEffect(id);
3765 }
3766
setEffectEnabled(int id,bool enabled)3767 status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3768 {
3769 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3770 if (effect == nullptr) {
3771 return INVALID_OPERATION;
3772 }
3773
3774 status_t status = mEffects.setEffectEnabled(id, enabled);
3775 if (status == NO_ERROR) {
3776 mInputs.trackEffectEnabled(effect, enabled);
3777 }
3778 return status;
3779 }
3780
3781
moveEffectsToIo(const std::vector<int> & ids,audio_io_handle_t io)3782 status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3783 {
3784 mEffects.moveEffects(ids, io);
3785 return NO_ERROR;
3786 }
3787
isStreamActive(audio_stream_type_t stream,uint32_t inPastMs) const3788 bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3789 {
3790 auto vs = toVolumeSource(stream, false);
3791 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
3792 }
3793
isStreamActiveRemotely(audio_stream_type_t stream,uint32_t inPastMs) const3794 bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3795 {
3796 auto vs = toVolumeSource(stream, false);
3797 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
3798 }
3799
isSourceActive(audio_source_t source) const3800 bool AudioPolicyManager::isSourceActive(audio_source_t source) const
3801 {
3802 for (size_t i = 0; i < mInputs.size(); i++) {
3803 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
3804 if (inputDescriptor->isSourceActive(source)) {
3805 return true;
3806 }
3807 }
3808 return false;
3809 }
3810
3811 // Register a list of custom mixes with their attributes and format.
3812 // When a mix is registered, corresponding input and output profiles are
3813 // added to the remote submix hw module. The profile contains only the
3814 // parameters (sampling rate, format...) specified by the mix.
3815 // The corresponding input remote submix device is also connected.
3816 //
3817 // When a remote submix device is connected, the address is checked to select the
3818 // appropriate profile and the corresponding input or output stream is opened.
3819 //
3820 // When capture starts, getInputForAttr() will:
3821 // - 1 look for a mix matching the address passed in attribtutes tags if any
3822 // - 2 if none found, getDeviceForInputSource() will:
3823 // - 2.1 look for a mix matching the attributes source
3824 // - 2.2 if none found, default to device selection by policy rules
3825 // At this time, the corresponding output remote submix device is also connected
3826 // and active playback use cases can be transferred to this mix if needed when reconnecting
3827 // after AudioTracks are invalidated
3828 //
3829 // When playback starts, getOutputForAttr() will:
3830 // - 1 look for a mix matching the address passed in attribtutes tags if any
3831 // - 2 if none found, look for a mix matching the attributes usage
3832 // - 3 if none found, default to device and output selection by policy rules.
3833
registerPolicyMixes(const Vector<AudioMix> & mixes)3834 status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
3835 {
3836 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3837 status_t res = NO_ERROR;
3838 bool checkOutputs = false;
3839 sp<HwModule> rSubmixModule;
3840 Vector<AudioMix> registeredMixes;
3841 // examine each mix's route type
3842 for (size_t i = 0; i < mixes.size(); i++) {
3843 AudioMix mix = mixes[i];
3844 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3845 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3846 ALOGE("Unsupported Policy Mix %zu of %zu: "
3847 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3848 i, mixes.size());
3849 res = INVALID_OPERATION;
3850 break;
3851 }
3852 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3853 // in the same way.
3854 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
3855 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3856 mix.mRouteFlags);
3857 if (rSubmixModule == 0) {
3858 rSubmixModule = mHwModules.getModuleFromName(
3859 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3860 if (rSubmixModule == 0) {
3861 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
3862 i);
3863 res = INVALID_OPERATION;
3864 break;
3865 }
3866 }
3867
3868 String8 address = mix.mDeviceAddress;
3869 audio_devices_t deviceTypeToMakeAvailable;
3870 if (mix.mMixType == MIX_TYPE_PLAYERS) {
3871 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
3872 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3873 } else {
3874 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3875 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
3876 }
3877
3878 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
3879 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
3880 res = INVALID_OPERATION;
3881 break;
3882 }
3883 audio_config_t outputConfig = mix.mFormat;
3884 audio_config_t inputConfig = mix.mFormat;
3885 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3886 // in stereo and let audio flinger do the channel conversion if needed.
3887 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3888 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
3889 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
3890 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3891 audio_is_linear_pcm(outputConfig.format)
3892 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
3893 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
3894 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3895 audio_is_linear_pcm(inputConfig.format)
3896 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
3897
3898 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
3899 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3900 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3901 ALOGE("Failed to set remote submix device available, type %u, address %s",
3902 mix.mDeviceType, address.c_str());
3903 break;
3904 }
3905 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3906 String8 address = mix.mDeviceAddress;
3907 audio_devices_t type = mix.mDeviceType;
3908 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
3909 i, mixes.size(), type, address.c_str());
3910
3911 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3912 mix.mDeviceType, mix.mDeviceAddress,
3913 String8(), AUDIO_FORMAT_DEFAULT);
3914 if (device == nullptr) {
3915 res = INVALID_OPERATION;
3916 break;
3917 }
3918
3919 bool foundOutput = false;
3920 // First try to find an already opened output supporting the device
3921 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
3922 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
3923
3924 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
3925 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
3926 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3927 address.c_str());
3928 res = INVALID_OPERATION;
3929 } else {
3930 foundOutput = true;
3931 }
3932 }
3933 }
3934 // If no output found, try to find a direct output profile supporting the device
3935 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3936 sp<HwModule> module = mHwModules[i];
3937 for (size_t j = 0;
3938 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3939 j++) {
3940 sp<IOProfile> profile = module->getOutputProfiles()[j];
3941 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3942 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3943 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3944 address.c_str());
3945 res = INVALID_OPERATION;
3946 } else {
3947 foundOutput = true;
3948 }
3949 }
3950 }
3951 }
3952 if (res != NO_ERROR) {
3953 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
3954 i, type, address.c_str());
3955 res = INVALID_OPERATION;
3956 break;
3957 } else if (!foundOutput) {
3958 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
3959 i, type, address.c_str());
3960 res = INVALID_OPERATION;
3961 break;
3962 } else {
3963 checkOutputs = true;
3964 registeredMixes.add(mix);
3965 }
3966 }
3967 }
3968 if (res != NO_ERROR) {
3969 if (audio_flags::audio_mix_ownership()) {
3970 // Only unregister mixes that were actually registered to not accidentally unregister
3971 // mixes that already existed previously.
3972 unregisterPolicyMixes(registeredMixes);
3973 registeredMixes.clear();
3974 } else {
3975 unregisterPolicyMixes(mixes);
3976 }
3977 } else if (checkOutputs) {
3978 checkForDeviceAndOutputChanges();
3979 updateCallAndOutputRouting();
3980 }
3981 return res;
3982 }
3983
unregisterPolicyMixes(Vector<AudioMix> mixes)3984 status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3985 {
3986 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
3987 status_t res = NO_ERROR;
3988 bool checkOutputs = false;
3989 sp<HwModule> rSubmixModule;
3990 // examine each mix's route type
3991 for (const auto& mix : mixes) {
3992 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
3993
3994 if (rSubmixModule == 0) {
3995 rSubmixModule = mHwModules.getModuleFromName(
3996 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3997 if (rSubmixModule == 0) {
3998 res = INVALID_OPERATION;
3999 continue;
4000 }
4001 }
4002
4003 String8 address = mix.mDeviceAddress;
4004
4005 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
4006 res = INVALID_OPERATION;
4007 continue;
4008 }
4009
4010 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
4011 if (getDeviceConnectionState(device, address.c_str()) ==
4012 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4013 status_t currentRes =
4014 setDeviceConnectionStateInt(device,
4015 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4016 address.c_str(),
4017 "remote-submix",
4018 AUDIO_FORMAT_DEFAULT);
4019 if (!audio_flags::audio_mix_ownership()) {
4020 res = currentRes;
4021 }
4022 if (currentRes != OK) {
4023 ALOGE("Error making RemoteSubmix device unavailable for mix "
4024 "with type %d, address %s", device, address.c_str());
4025 res = INVALID_OPERATION;
4026 }
4027 }
4028 }
4029 rSubmixModule->removeOutputProfile(address.c_str());
4030 rSubmixModule->removeInputProfile(address.c_str());
4031
4032 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4033 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
4034 res = INVALID_OPERATION;
4035 continue;
4036 } else {
4037 checkOutputs = true;
4038 }
4039 }
4040 }
4041
4042 if (res == NO_ERROR && checkOutputs) {
4043 checkForDeviceAndOutputChanges();
4044 updateCallAndOutputRouting();
4045 }
4046 return res;
4047 }
4048
getRegisteredPolicyMixes(std::vector<AudioMix> & _aidl_return)4049 status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4050 if (!audio_flags::audio_mix_test_api()) {
4051 return INVALID_OPERATION;
4052 }
4053
4054 _aidl_return.clear();
4055 _aidl_return.reserve(mPolicyMixes.size());
4056 for (const auto &policyMix: mPolicyMixes) {
4057 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4058 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4059 policyMix->mCbFlags);
4060 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
4061 _aidl_return.back().mToken = policyMix->mToken;
4062 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
4063 }
4064
4065 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
4066 return OK;
4067 }
4068
updatePolicyMix(const AudioMix & mix,const std::vector<AudioMixMatchCriterion> & updatedCriteria)4069 status_t AudioPolicyManager::updatePolicyMix(
4070 const AudioMix& mix,
4071 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4072 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4073 if (res == NO_ERROR) {
4074 checkForDeviceAndOutputChanges();
4075 updateCallAndOutputRouting();
4076 }
4077 return res;
4078 }
4079
dumpManualSurroundFormats(String8 * dst) const4080 void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4081 {
4082 size_t i = 0;
4083 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4084 for (const auto& fmt : mManualSurroundFormats) {
4085 if (i++ != 0) dst->append(", ");
4086 std::string sfmt;
4087 FormatConverter::toString(fmt, sfmt);
4088 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4089 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4090 }
4091 }
4092
4093 // Returns true if all devices types match the predicate and are supported by one HW module
areAllDevicesSupported(const AudioDeviceTypeAddrVector & devices,std::function<bool (audio_devices_t)> predicate,const char * context,bool matchAddress)4094 bool AudioPolicyManager::areAllDevicesSupported(
4095 const AudioDeviceTypeAddrVector& devices,
4096 std::function<bool(audio_devices_t)> predicate,
4097 const char *context,
4098 bool matchAddress) {
4099 for (size_t i = 0; i < devices.size(); i++) {
4100 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
4101 devices[i].mType, devices[i].getAddress(), String8(),
4102 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
4103 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
4104 ALOGE("%s: device type %#x address %s not supported or not match predicate",
4105 context, devices[i].mType, devices[i].getAddress());
4106 return false;
4107 }
4108 }
4109 return true;
4110 }
4111
changeOutputDevicesMuteState(const AudioDeviceTypeAddrVector & devices)4112 void AudioPolicyManager::changeOutputDevicesMuteState(
4113 const AudioDeviceTypeAddrVector& devices) {
4114 ALOGVV("%s() num devices %zu", __func__, devices.size());
4115
4116 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4117 getSoftwareOutputsForDevices(devices);
4118
4119 for (size_t i = 0; i < outputs.size(); i++) {
4120 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4121 DeviceVector prevDevices = outputDesc->devices();
4122 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4123 }
4124 }
4125
getSoftwareOutputsForDevices(const AudioDeviceTypeAddrVector & devices) const4126 std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4127 const AudioDeviceTypeAddrVector& devices) const
4128 {
4129 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4130 DeviceVector deviceDescriptors;
4131 for (size_t j = 0; j < devices.size(); j++) {
4132 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4133 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4134 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4135 ALOGE("%s: device type %#x address %s not supported or not an output device",
4136 __func__, devices[j].mType, devices[j].getAddress());
4137 continue;
4138 }
4139 deviceDescriptors.add(desc);
4140 }
4141 for (size_t i = 0; i < mOutputs.size(); i++) {
4142 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4143 continue;
4144 }
4145 outputs.push_back(mOutputs.valueAt(i));
4146 }
4147 return outputs;
4148 }
4149
setUidDeviceAffinities(uid_t uid,const AudioDeviceTypeAddrVector & devices)4150 status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
4151 const AudioDeviceTypeAddrVector& devices) {
4152 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
4153 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4154 return BAD_VALUE;
4155 }
4156 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
4157 if (res != NO_ERROR) {
4158 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4159 return res;
4160 }
4161
4162 checkForDeviceAndOutputChanges();
4163 updateCallAndOutputRouting();
4164
4165 return NO_ERROR;
4166 }
4167
removeUidDeviceAffinities(uid_t uid)4168 status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4169 ALOGV("%s() uid=%d", __FUNCTION__, uid);
4170 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4171 if (res != NO_ERROR) {
4172 ALOGE("%s() Could not remove all device affinities for uid = %d",
4173 __FUNCTION__, uid);
4174 return INVALID_OPERATION;
4175 }
4176
4177 checkForDeviceAndOutputChanges();
4178 updateCallAndOutputRouting();
4179
4180 return res;
4181 }
4182
4183
setDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role,const AudioDeviceTypeAddrVector & devices)4184 status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4185 device_role_t role,
4186 const AudioDeviceTypeAddrVector &devices) {
4187 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4188 dumpAudioDeviceTypeAddrVector(devices).c_str());
4189
4190 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4191 return BAD_VALUE;
4192 }
4193 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
4194 if (status != NO_ERROR) {
4195 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4196 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4197 return status;
4198 }
4199
4200 checkForDeviceAndOutputChanges();
4201
4202 bool forceVolumeReeval = false;
4203 // FIXME: workaround for truncated touch sounds
4204 // to be removed when the problem is handled by system UI
4205 uint32_t delayMs = 0;
4206 if (strategy == mCommunnicationStrategy) {
4207 forceVolumeReeval = true;
4208 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4209 updateInputRouting();
4210 }
4211 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4212
4213 return NO_ERROR;
4214 }
4215
updateCallAndOutputRouting(bool forceVolumeReeval,uint32_t delayMs,bool skipDelays)4216 void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4217 bool skipDelays)
4218 {
4219 uint32_t waitMs = 0;
4220 bool wasLeUnicastActive = isLeUnicastActive();
4221 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
4222 // Only apply special touch sound delay once
4223 delayMs = 0;
4224 }
4225 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
4226 for (size_t i = 0; i < mOutputs.size(); i++) {
4227 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4228 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
4229 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4230 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
4231 // As done in setDeviceConnectionState, we could also fix default device issue by
4232 // preventing the force re-routing in case of default dev that distinguishes on address.
4233 // Let's give back to engine full device choice decision however.
4234 bool forceRouting = !newDevices.isEmpty();
4235 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
4236 // If the device is using preferred mixer attributes, the output need to reopen
4237 // with default configuration when the new selected devices are different from
4238 // current routing devices.
4239 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4240 continue;
4241 }
4242
4243 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4244 nullptr, !skipDelays /*requiresMuteCheck*/,
4245 !forceRouting /*requiresVolumeCheck*/, skipDelays);
4246 // Only apply special touch sound delay once
4247 delayMs = 0;
4248 }
4249 if (forceVolumeReeval && !newDevices.isEmpty()) {
4250 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4251 }
4252 }
4253 reopenOutputsWithDevices(outputsToReopen);
4254 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
4255 }
4256
updateInputRouting()4257 void AudioPolicyManager::updateInputRouting() {
4258 for (const auto& activeDesc : mInputs.getActiveInputs()) {
4259 // Skip for hotword recording as the input device switch
4260 // is handled within sound trigger HAL
4261 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4262 continue;
4263 }
4264 auto newDevice = getNewInputDevice(activeDesc);
4265 // Force new input selection if the new device can not be reached via current input
4266 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4267 setInputDevice(activeDesc->mIoHandle, newDevice);
4268 } else {
4269 closeInput(activeDesc->mIoHandle);
4270 }
4271 }
4272 }
4273
4274 status_t
removeDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role,const AudioDeviceTypeAddrVector & devices)4275 AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4276 device_role_t role,
4277 const AudioDeviceTypeAddrVector &devices) {
4278 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4279 dumpAudioDeviceTypeAddrVector(devices).c_str());
4280
4281 if (!areAllDevicesSupported(
4282 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
4283 return BAD_VALUE;
4284 }
4285 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4286 if (status != NO_ERROR) {
4287 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4288 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4289 return status;
4290 }
4291
4292 checkForDeviceAndOutputChanges();
4293
4294 bool forceVolumeReeval = false;
4295 // TODO(b/263479999): workaround for truncated touch sounds
4296 // to be removed when the problem is handled by system UI
4297 uint32_t delayMs = 0;
4298 if (strategy == mCommunnicationStrategy) {
4299 forceVolumeReeval = true;
4300 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4301 updateInputRouting();
4302 }
4303 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4304
4305 return NO_ERROR;
4306 }
4307
clearDevicesRoleForStrategy(product_strategy_t strategy,device_role_t role)4308 status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4309 device_role_t role)
4310 {
4311 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
4312
4313 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
4314 if (status != NO_ERROR) {
4315 ALOGW_IF(status != NAME_NOT_FOUND,
4316 "Engine could not remove device role for strategy %d status %d",
4317 strategy, status);
4318 return status;
4319 }
4320
4321 checkForDeviceAndOutputChanges();
4322
4323 bool forceVolumeReeval = false;
4324 // FIXME: workaround for truncated touch sounds
4325 // to be removed when the problem is handled by system UI
4326 uint32_t delayMs = 0;
4327 if (strategy == mCommunnicationStrategy) {
4328 forceVolumeReeval = true;
4329 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4330 updateInputRouting();
4331 }
4332 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4333
4334 return NO_ERROR;
4335 }
4336
getDevicesForRoleAndStrategy(product_strategy_t strategy,device_role_t role,AudioDeviceTypeAddrVector & devices)4337 status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4338 device_role_t role,
4339 AudioDeviceTypeAddrVector &devices) {
4340 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
4341 }
4342
setDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)4343 status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4344 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4345 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4346 dumpAudioDeviceTypeAddrVector(devices).c_str());
4347
4348 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
4349 return BAD_VALUE;
4350 }
4351 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4352 ALOGW_IF(status != NO_ERROR,
4353 "Engine could not set preferred devices %s for audio source %d role %d",
4354 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4355
4356 return status;
4357 }
4358
addDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)4359 status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4360 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4361 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4362 dumpAudioDeviceTypeAddrVector(devices).c_str());
4363
4364 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
4365 return BAD_VALUE;
4366 }
4367 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4368 ALOGW_IF(status != NO_ERROR,
4369 "Engine could not add preferred devices %s for audio source %d role %d",
4370 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4371
4372 updateInputRouting();
4373 return status;
4374 }
4375
removeDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role,const AudioDeviceTypeAddrVector & devices)4376 status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4377 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4378 {
4379 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4380 dumpAudioDeviceTypeAddrVector(devices).c_str());
4381
4382 if (!areAllDevicesSupported(
4383 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
4384 return BAD_VALUE;
4385 }
4386
4387 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4388 audioSource, role, devices);
4389 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
4390 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
4391 if (status == NO_ERROR) {
4392 updateInputRouting();
4393 }
4394 return status;
4395 }
4396
clearDevicesRoleForCapturePreset(audio_source_t audioSource,device_role_t role)4397 status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4398 device_role_t role) {
4399 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4400
4401 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
4402 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
4403 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
4404 if (status == NO_ERROR) {
4405 updateInputRouting();
4406 }
4407 return status;
4408 }
4409
getDevicesForRoleAndCapturePreset(audio_source_t audioSource,device_role_t role,AudioDeviceTypeAddrVector & devices)4410 status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4411 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4412 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4413 }
4414
setUserIdDeviceAffinities(int userId,const AudioDeviceTypeAddrVector & devices)4415 status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
4416 const AudioDeviceTypeAddrVector& devices) {
4417 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
4418 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4419 return BAD_VALUE;
4420 }
4421 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4422 if (status != NO_ERROR) {
4423 ALOGE("%s() could not set device affinity for userId %d",
4424 __FUNCTION__, userId);
4425 return status;
4426 }
4427
4428 // reevaluate outputs for all devices
4429 checkForDeviceAndOutputChanges();
4430 changeOutputDevicesMuteState(devices);
4431 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4432 true /* skipDelays */);
4433 changeOutputDevicesMuteState(devices);
4434
4435 return NO_ERROR;
4436 }
4437
removeUserIdDeviceAffinities(int userId)4438 status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
4439 ALOGV("%s() userId=%d", __FUNCTION__, userId);
4440 AudioDeviceTypeAddrVector devices;
4441 mPolicyMixes.getDevicesForUserId(userId, devices);
4442 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4443 if (status != NO_ERROR) {
4444 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4445 __FUNCTION__, userId);
4446 return status;
4447 }
4448
4449 // reevaluate outputs for all devices
4450 checkForDeviceAndOutputChanges();
4451 changeOutputDevicesMuteState(devices);
4452 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4453 true /* skipDelays */);
4454 changeOutputDevicesMuteState(devices);
4455
4456 return NO_ERROR;
4457 }
4458
dump(String8 * dst) const4459 void AudioPolicyManager::dump(String8 *dst) const
4460 {
4461 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
4462 dst->appendFormat(" Primary Output I/O handle: %d\n",
4463 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
4464 std::string stateLiteral;
4465 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
4466 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
4467 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4468 "communications", "media", "record", "dock", "system",
4469 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4470 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4471 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
4472 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4473 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4474 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4475 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4476 dst->append(" (MANUAL: ");
4477 dumpManualSurroundFormats(dst);
4478 dst->append(")");
4479 }
4480 dst->append("\n");
4481 }
4482 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4483 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
4484 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
4485 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
4486
4487 dst->append("\n");
4488 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4489 dst->append("\n");
4490 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
4491 mHwModules.dump(dst);
4492 mOutputs.dump(dst);
4493 mInputs.dump(dst);
4494 mEffects.dump(dst, 1);
4495 mAudioPatches.dump(dst);
4496 mPolicyMixes.dump(dst);
4497 mAudioSources.dump(dst);
4498
4499 dst->appendFormat(" AllowedCapturePolicies:\n");
4500 for (auto& policy : mAllowedCapturePolicies) {
4501 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4502 }
4503
4504 dst->appendFormat(" Preferred mixer audio configuration:\n");
4505 for (const auto it : mPreferredMixerAttrInfos) {
4506 dst->appendFormat(" - device port id: %d\n", it.first);
4507 for (const auto preferredMixerInfoIt : it.second) {
4508 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4509 preferredMixerInfoIt.second->dump(dst);
4510 }
4511 }
4512
4513 dst->appendFormat("\nPolicy Engine dump:\n");
4514 mEngine->dump(dst);
4515
4516 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4517 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4518 dst->appendFormat(" - device type: %s, driving stream %d\n",
4519 dumpDeviceTypes({it.first}).c_str(),
4520 mEngine->getVolumeGroupForAttributes(it.second));
4521 }
4522 }
4523
dump(int fd)4524 status_t AudioPolicyManager::dump(int fd)
4525 {
4526 String8 result;
4527 dump(&result);
4528 write(fd, result.c_str(), result.size());
4529 return NO_ERROR;
4530 }
4531
setAllowedCapturePolicy(uid_t uid,audio_flags_mask_t capturePolicy)4532 status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4533 {
4534 mAllowedCapturePolicies[uid] = capturePolicy;
4535 return NO_ERROR;
4536 }
4537
4538 // This function checks for the parameters which can be offloaded.
4539 // This can be enhanced depending on the capability of the DSP and policy
4540 // of the system.
getOffloadSupport(const audio_offload_info_t & offloadInfo)4541 audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
4542 {
4543 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
4544 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
4545 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
4546 offloadInfo.format,
4547 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4548 offloadInfo.has_video);
4549
4550 if (!isOffloadPossible(offloadInfo)) {
4551 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4552 }
4553
4554 // See if there is a profile to support this.
4555 // AUDIO_DEVICE_NONE
4556 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
4557 offloadInfo.sample_rate,
4558 offloadInfo.format,
4559 offloadInfo.channel_mask,
4560 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4561 true /* directOnly */);
4562 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4563 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4564 ? ", supports gapless" : "");
4565 if (profile == nullptr) {
4566 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4567 }
4568 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4569 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4570 }
4571 return AUDIO_OFFLOAD_SUPPORTED;
4572 }
4573
isDirectOutputSupported(const audio_config_base_t & config,const audio_attributes_t & attributes)4574 bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4575 const audio_attributes_t& attributes) {
4576 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
4577 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
4578 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4579 sp<IOProfile> profile = getProfileForOutput(outputDevices,
4580 config.sample_rate,
4581 config.format,
4582 config.channel_mask,
4583 output_flags,
4584 true /* directOnly */);
4585 ALOGV("%s() profile %sfound with name: %s, "
4586 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4587 __FUNCTION__, profile != 0 ? "" : "NOT ",
4588 (profile != 0 ? profile->getTagName().c_str() : "null"),
4589 config.sample_rate, config.format, config.channel_mask, output_flags);
4590
4591 // also try the MSD module if compatible profile not found
4592 if (profile == nullptr) {
4593 profile = getMsdProfileForOutput(outputDevices,
4594 config.sample_rate,
4595 config.format,
4596 config.channel_mask,
4597 output_flags,
4598 true /* directOnly */);
4599 ALOGV("%s() MSD profile %sfound with name: %s, "
4600 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4601 __FUNCTION__, profile != 0 ? "" : "NOT ",
4602 (profile != 0 ? profile->getTagName().c_str() : "null"),
4603 config.sample_rate, config.format, config.channel_mask, output_flags);
4604 }
4605 return (profile != nullptr);
4606 }
4607
isOffloadPossible(const audio_offload_info_t & offloadInfo,bool durationIgnored)4608 bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4609 bool durationIgnored) {
4610 if (mMasterMono) {
4611 return false; // no offloading if mono is set.
4612 }
4613
4614 // Check if offload has been disabled
4615 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4616 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4617 return false;
4618 }
4619
4620 // Check if stream type is music, then only allow offload as of now.
4621 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4622 {
4623 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4624 return false;
4625 }
4626
4627 //TODO: enable audio offloading with video when ready
4628 const bool allowOffloadWithVideo =
4629 property_get_bool("audio.offload.video", false /* default_value */);
4630 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4631 ALOGV("%s: has_video == true, returning false", __func__);
4632 return false;
4633 }
4634
4635 //If duration is less than minimum value defined in property, return false
4636 const int min_duration_secs = property_get_int32(
4637 "audio.offload.min.duration.secs", -1 /* default_value */);
4638 if (!durationIgnored) {
4639 if (min_duration_secs >= 0) {
4640 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4641 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4642 __func__, min_duration_secs);
4643 return false;
4644 }
4645 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4646 ALOGV("%s: Offload denied by duration < default min(=%u)",
4647 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4648 return false;
4649 }
4650 }
4651
4652 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4653 // creating an offloaded track and tearing it down immediately after start when audioflinger
4654 // detects there is an active non offloadable effect.
4655 // FIXME: We should check the audio session here but we do not have it in this context.
4656 // This may prevent offloading in rare situations where effects are left active by apps
4657 // in the background.
4658 if (mEffects.isNonOffloadableEffectEnabled()) {
4659 return false;
4660 }
4661
4662 return true;
4663 }
4664
getDirectPlaybackSupport(const audio_attributes_t * attr,const audio_config_t * config)4665 audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4666 const audio_config_t *config) {
4667 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4668 offloadInfo.format = config->format;
4669 offloadInfo.sample_rate = config->sample_rate;
4670 offloadInfo.channel_mask = config->channel_mask;
4671 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4672 offloadInfo.has_video = false;
4673 offloadInfo.is_streaming = false;
4674 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4675
4676 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4677 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4678 audio_flags_to_audio_output_flags(attr->flags, &flags);
4679 // only retain flags that will drive compressed offload or passthrough
4680 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4681 if (offloadPossible) {
4682 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4683 }
4684 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4685
4686 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
4687 for (const auto& hwModule : mHwModules) {
4688 DeviceVector outputDevices = engineOutputDevices;
4689 // the MSD module checks for different conditions and output devices
4690 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4691 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4692 continue;
4693 }
4694 outputDevices = getMsdAudioOutDevices();
4695 }
4696 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4697 if (curProfile->getCompatibilityScore(outputDevices,
4698 config->sample_rate, nullptr /*updatedSamplingRate*/,
4699 config->format, nullptr /*updatedFormat*/,
4700 config->channel_mask, nullptr /*updatedChannelMask*/,
4701 flags) == IOProfile::NO_MATCH) {
4702 continue;
4703 }
4704 // reject profiles not corresponding to a device currently available
4705 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4706 continue;
4707 }
4708 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4709 != AUDIO_OUTPUT_FLAG_NONE)) {
4710 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
4711 != AUDIO_DIRECT_NOT_SUPPORTED) {
4712 // Already reports offload gapless supported. No need to report offload support.
4713 continue;
4714 }
4715 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4716 != AUDIO_OUTPUT_FLAG_NONE) {
4717 // If offload gapless is reported, no need to report offload support.
4718 directMode = (audio_direct_mode_t) ((directMode &
4719 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4720 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4721 } else {
4722 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
4723 }
4724 } else {
4725 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
4726 }
4727 }
4728 }
4729 return directMode;
4730 }
4731
getDirectProfilesForAttributes(const audio_attributes_t * attr,AudioProfileVector & audioProfilesVector)4732 status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4733 AudioProfileVector& audioProfilesVector) {
4734 if (mEffects.isNonOffloadableEffectEnabled()) {
4735 return OK;
4736 }
4737 DeviceVector devices;
4738 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
4739 if (status != OK) {
4740 return status;
4741 }
4742 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4743 if (devices.empty()) {
4744 return OK; // no output devices for the attributes
4745 }
4746 return getProfilesForDevices(devices, audioProfilesVector,
4747 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
4748 }
4749
getSupportedMixerAttributes(audio_port_handle_t portId,std::vector<audio_mixer_attributes_t> & mixerAttrs)4750 status_t AudioPolicyManager::getSupportedMixerAttributes(
4751 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4752 ALOGV("%s, portId=%d", __func__, portId);
4753 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4754 if (deviceDescriptor == nullptr) {
4755 ALOGE("%s the requested device is currently unavailable", __func__);
4756 return BAD_VALUE;
4757 }
4758 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4759 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4760 deviceDescriptor->type());
4761 return BAD_VALUE;
4762 }
4763 for (const auto& hwModule : mHwModules) {
4764 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4765 if (curProfile->supportsDevice(deviceDescriptor)) {
4766 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4767 }
4768 }
4769 }
4770 return NO_ERROR;
4771 }
4772
setPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,uid_t uid,const audio_mixer_attributes_t * mixerAttributes)4773 status_t AudioPolicyManager::setPreferredMixerAttributes(
4774 const audio_attributes_t *attr,
4775 audio_port_handle_t portId,
4776 uid_t uid,
4777 const audio_mixer_attributes_t *mixerAttributes) {
4778 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4779 "mixerBehavior=%d}, uid=%d, portId=%u",
4780 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4781 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4782 mixerAttributes->mixer_behavior, uid, portId);
4783 if (attr->usage != AUDIO_USAGE_MEDIA) {
4784 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4785 return BAD_VALUE;
4786 }
4787 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4788 if (deviceDescriptor == nullptr) {
4789 ALOGE("%s the requested device is currently unavailable", __func__);
4790 return BAD_VALUE;
4791 }
4792 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4793 ALOGE("%s(%d), type=%d, is not a usb output device",
4794 __func__, portId, deviceDescriptor->type());
4795 return BAD_VALUE;
4796 }
4797
4798 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4799 audio_flags_to_audio_output_flags(attr->flags, &flags);
4800 flags = (audio_output_flags_t) (flags |
4801 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4802 sp<IOProfile> profile = nullptr;
4803 DeviceVector devices(deviceDescriptor);
4804 for (const auto& hwModule : mHwModules) {
4805 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4806 if (curProfile->hasDynamicAudioProfile()
4807 && curProfile->getCompatibilityScore(
4808 devices,
4809 mixerAttributes->config.sample_rate,
4810 nullptr /*updatedSamplingRate*/,
4811 mixerAttributes->config.format,
4812 nullptr /*updatedFormat*/,
4813 mixerAttributes->config.channel_mask,
4814 nullptr /*updatedChannelMask*/,
4815 flags,
4816 false /*exactMatchRequiredForInputFlags*/)
4817 != IOProfile::NO_MATCH) {
4818 profile = curProfile;
4819 break;
4820 }
4821 }
4822 }
4823 if (profile == nullptr) {
4824 ALOGE("%s, there is no compatible profile found", __func__);
4825 return BAD_VALUE;
4826 }
4827
4828 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4829 sp<PreferredMixerAttributesInfo>::make(
4830 uid, portId, profile, flags, *mixerAttributes);
4831 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4832 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4833
4834 // If 1) there is any client from the preferred mixer configuration owner that is currently
4835 // active and matches the strategy and 2) current output is on the preferred device and the
4836 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4837 // configuration.
4838 std::vector<audio_io_handle_t> outputsToReopen;
4839 for (size_t i = 0; i < mOutputs.size(); i++) {
4840 const auto output = mOutputs.valueAt(i);
4841 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4842 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4843 output->mPreferredAttrInfo = mixerAttrInfo;
4844 } else {
4845 for (const auto &client: output->getActiveClients()) {
4846 if (client->uid() == uid && client->strategy() == strategy) {
4847 client->setIsInvalid();
4848 outputsToReopen.push_back(output->mIoHandle);
4849 }
4850 }
4851 }
4852 }
4853 }
4854 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4855 config.sample_rate = mixerAttributes->config.sample_rate;
4856 config.channel_mask = mixerAttributes->config.channel_mask;
4857 config.format = mixerAttributes->config.format;
4858 for (const auto output : outputsToReopen) {
4859 sp<SwAudioOutputDescriptor> desc =
4860 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4861 if (desc == nullptr) {
4862 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4863 continue;
4864 }
4865 desc->mPreferredAttrInfo = mixerAttrInfo;
4866 }
4867
4868 return NO_ERROR;
4869 }
4870
getPreferredMixerAttributesInfo(audio_port_handle_t devicePortId,product_strategy_t strategy,bool activeBitPerfectPreferred)4871 sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4872 audio_port_handle_t devicePortId,
4873 product_strategy_t strategy,
4874 bool activeBitPerfectPreferred) {
4875 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4876 if (it == mPreferredMixerAttrInfos.end()) {
4877 return nullptr;
4878 }
4879 if (activeBitPerfectPreferred) {
4880 for (auto [strategy, info] : it->second) {
4881 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
4882 return info;
4883 }
4884 }
4885 }
4886 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4887 return strategyMatchedMixerAttrInfoIt == it->second.end()
4888 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
4889 }
4890
getPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,audio_mixer_attributes_t * mixerAttributes)4891 status_t AudioPolicyManager::getPreferredMixerAttributes(
4892 const audio_attributes_t *attr,
4893 audio_port_handle_t portId,
4894 audio_mixer_attributes_t* mixerAttributes) {
4895 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4896 portId, mEngine->getProductStrategyForAttributes(*attr));
4897 if (info == nullptr) {
4898 return NAME_NOT_FOUND;
4899 }
4900 *mixerAttributes = info->getMixerAttributes();
4901 return NO_ERROR;
4902 }
4903
clearPreferredMixerAttributes(const audio_attributes_t * attr,audio_port_handle_t portId,uid_t uid)4904 status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4905 audio_port_handle_t portId,
4906 uid_t uid) {
4907 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4908 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4909 if (preferredMixerAttrInfo == nullptr) {
4910 return NAME_NOT_FOUND;
4911 }
4912 if (preferredMixerAttrInfo->getUid() != uid) {
4913 ALOGE("%s, requested uid=%d, owned uid=%d",
4914 __func__, uid, preferredMixerAttrInfo->getUid());
4915 return PERMISSION_DENIED;
4916 }
4917 mPreferredMixerAttrInfos[portId].erase(strategy);
4918 if (mPreferredMixerAttrInfos[portId].empty()) {
4919 mPreferredMixerAttrInfos.erase(portId);
4920 }
4921
4922 // Reconfig existing output
4923 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4924 for (size_t i = 0; i < mOutputs.size(); i++) {
4925 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4926 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4927 }
4928 }
4929 for (const auto output : potentialOutputsToReopen) {
4930 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4931 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4932 preferredMixerAttrInfo->getFlags())) {
4933 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4934 }
4935 }
4936 return NO_ERROR;
4937 }
4938
listAudioPorts(audio_port_role_t role,audio_port_type_t type,unsigned int * num_ports,struct audio_port_v7 * ports,unsigned int * generation)4939 status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4940 audio_port_type_t type,
4941 unsigned int *num_ports,
4942 struct audio_port_v7 *ports,
4943 unsigned int *generation)
4944 {
4945 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4946 generation == nullptr) {
4947 return BAD_VALUE;
4948 }
4949 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
4950 if (ports == nullptr) {
4951 *num_ports = 0;
4952 }
4953
4954 size_t portsWritten = 0;
4955 size_t portsMax = *num_ports;
4956 *num_ports = 0;
4957 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
4958 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4959 // as they are used by stub HALs by convention
4960 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4961 for (const auto& dev : mAvailableOutputDevices) {
4962 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
4963 continue;
4964 }
4965 if (portsWritten < portsMax) {
4966 dev->toAudioPort(&ports[portsWritten++]);
4967 }
4968 (*num_ports)++;
4969 }
4970 }
4971 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
4972 for (const auto& dev : mAvailableInputDevices) {
4973 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
4974 continue;
4975 }
4976 if (portsWritten < portsMax) {
4977 dev->toAudioPort(&ports[portsWritten++]);
4978 }
4979 (*num_ports)++;
4980 }
4981 }
4982 }
4983 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4984 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4985 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4986 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4987 }
4988 *num_ports += mInputs.size();
4989 }
4990 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
4991 size_t numOutputs = 0;
4992 for (size_t i = 0; i < mOutputs.size(); i++) {
4993 if (!mOutputs[i]->isDuplicated()) {
4994 numOutputs++;
4995 if (portsWritten < portsMax) {
4996 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4997 }
4998 }
4999 }
5000 *num_ports += numOutputs;
5001 }
5002 }
5003
5004 *generation = curAudioPortGeneration();
5005 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
5006 return NO_ERROR;
5007 }
5008
listDeclaredDevicePorts(media::AudioPortRole role,std::vector<media::AudioPortFw> * _aidl_return)5009 status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5010 std::vector<media::AudioPortFw>* _aidl_return) {
5011 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5012 audio_port_v7 port;
5013 dev->toAudioPort(&port);
5014 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5015 _aidl_return->push_back(std::move(aidlPort));
5016 return OK;
5017 };
5018
5019 for (const auto& module : mHwModules) {
5020 for (const auto& dev : module->getDeclaredDevices()) {
5021 if (role == media::AudioPortRole::NONE ||
5022 ((role == media::AudioPortRole::SOURCE)
5023 == audio_is_input_device(dev->type()))) {
5024 RETURN_STATUS_IF_ERROR(pushPort(dev));
5025 }
5026 }
5027 }
5028 return OK;
5029 }
5030
getAudioPort(struct audio_port_v7 * port)5031 status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
5032 {
5033 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5034 return BAD_VALUE;
5035 }
5036 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5037 if (dev != 0) {
5038 dev->toAudioPort(port);
5039 return NO_ERROR;
5040 }
5041 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5042 if (dev != 0) {
5043 dev->toAudioPort(port);
5044 return NO_ERROR;
5045 }
5046 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5047 if (out != 0) {
5048 out->toAudioPort(port);
5049 return NO_ERROR;
5050 }
5051 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5052 if (in != 0) {
5053 in->toAudioPort(port);
5054 return NO_ERROR;
5055 }
5056 return BAD_VALUE;
5057 }
5058
createAudioPatch(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid)5059 status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5060 audio_patch_handle_t *handle,
5061 uid_t uid)
5062 {
5063 ALOGV("%s", __func__);
5064 if (handle == NULL || patch == NULL) {
5065 return BAD_VALUE;
5066 }
5067 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
5068 if (!audio_patch_is_valid(patch)) {
5069 return BAD_VALUE;
5070 }
5071 // only one source per audio patch supported for now
5072 if (patch->num_sources > 1) {
5073 return INVALID_OPERATION;
5074 }
5075 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
5076 return INVALID_OPERATION;
5077 }
5078 for (size_t i = 0; i < patch->num_sinks; i++) {
5079 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5080 return INVALID_OPERATION;
5081 }
5082 }
5083
5084 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5085 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5086 if (srcDevice == nullptr || sinkDevice == nullptr) {
5087 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5088 return BAD_VALUE;
5089 }
5090 ALOGV("%s between source %s and sink %s", __func__,
5091 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5092 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5093 // Default attributes, default volume priority, not to infer with non raw audio patches.
5094 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5095 const struct audio_port_config *source = &patch->sources[0];
5096 sp<SourceClientDescriptor> sourceDesc =
5097 new SourceClientDescriptor(
5098 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5099 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5100 true, false /*isCallRx*/, false /*isCallTx*/);
5101 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
5102
5103 status_t status =
5104 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5105
5106 if (status != NO_ERROR) {
5107 return INVALID_OPERATION;
5108 }
5109 mAudioSources.add(portId, sourceDesc);
5110 return NO_ERROR;
5111 }
5112
connectAudioSourceToSink(const sp<SourceClientDescriptor> & sourceDesc,const sp<DeviceDescriptor> & sinkDevice,const struct audio_patch * patch,audio_patch_handle_t & handle,uid_t uid,uint32_t delayMs)5113 status_t AudioPolicyManager::connectAudioSourceToSink(
5114 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5115 const struct audio_patch *patch,
5116 audio_patch_handle_t &handle,
5117 uid_t uid, uint32_t delayMs)
5118 {
5119 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5120 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5121 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5122 return INVALID_OPERATION;
5123 }
5124 sourceDesc->connect(handle, sinkDevice);
5125 if (isMsdPatch(handle)) {
5126 return NO_ERROR;
5127 }
5128 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5129 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5130 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5131 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5132 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5133 goto FailurePatchAdded;
5134 }
5135 status = swOutput->start();
5136 if (status != NO_ERROR) {
5137 goto FailureSourceAdded;
5138 }
5139 swOutput->addClient(sourceDesc);
5140 status = startSource(swOutput, sourceDesc, &delayMs);
5141 if (status != NO_ERROR) {
5142 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5143 goto FailureSourceActive;
5144 }
5145 if (delayMs != 0) {
5146 usleep(delayMs * 1000);
5147 }
5148 return NO_ERROR;
5149
5150 FailureSourceActive:
5151 swOutput->stop();
5152 releaseOutput(sourceDesc->portId());
5153 FailureSourceAdded:
5154 sourceDesc->setSwOutput(nullptr);
5155 FailurePatchAdded:
5156 releaseAudioPatchInternal(handle);
5157 return INVALID_OPERATION;
5158 }
5159
createAudioPatchInternal(const struct audio_patch * patch,audio_patch_handle_t * handle,uid_t uid,uint32_t delayMs,const sp<SourceClientDescriptor> & sourceDesc)5160 status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5161 audio_patch_handle_t *handle,
5162 uid_t uid, uint32_t delayMs,
5163 const sp<SourceClientDescriptor>& sourceDesc)
5164 {
5165 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
5166 sp<AudioPatch> patchDesc;
5167 ssize_t index = mAudioPatches.indexOfKey(*handle);
5168
5169 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5170 patch->sources[0].role,
5171 patch->sources[0].type);
5172 #if LOG_NDEBUG == 0
5173 for (size_t i = 0; i < patch->num_sinks; i++) {
5174 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5175 patch->sinks[i].role,
5176 patch->sinks[i].type);
5177 }
5178 #endif
5179
5180 if (index >= 0) {
5181 patchDesc = mAudioPatches.valueAt(index);
5182 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5183 __func__, mUidCached, patchDesc->getUid(), uid);
5184 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
5185 return INVALID_OPERATION;
5186 }
5187 } else {
5188 *handle = AUDIO_PATCH_HANDLE_NONE;
5189 }
5190
5191 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
5192 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
5193 if (outputDesc == NULL) {
5194 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
5195 return BAD_VALUE;
5196 }
5197 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5198 outputDesc->mIoHandle);
5199 if (patchDesc != 0) {
5200 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
5201 ALOGV("%s source id differs for patch current id %d new id %d",
5202 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
5203 return BAD_VALUE;
5204 }
5205 }
5206 DeviceVector devices;
5207 for (size_t i = 0; i < patch->num_sinks; i++) {
5208 // Only support mix to devices connection
5209 // TODO add support for mix to mix connection
5210 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
5211 ALOGV("%s source mix but sink is not a device", __func__);
5212 return INVALID_OPERATION;
5213 }
5214 sp<DeviceDescriptor> devDesc =
5215 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5216 if (devDesc == 0) {
5217 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
5218 return BAD_VALUE;
5219 }
5220
5221 if (outputDesc->mProfile->getCompatibilityScore(
5222 DeviceVector(devDesc),
5223 patch->sources[0].sample_rate,
5224 nullptr, // updatedSamplingRate
5225 patch->sources[0].format,
5226 nullptr, // updatedFormat
5227 patch->sources[0].channel_mask,
5228 nullptr, // updatedChannelMask
5229 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
5230 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
5231 return INVALID_OPERATION;
5232 }
5233 devices.add(devDesc);
5234 }
5235 if (devices.size() == 0) {
5236 return INVALID_OPERATION;
5237 }
5238
5239 // TODO: reconfigure output format and channels here
5240 ALOGV("%s setting device %s on output %d",
5241 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
5242 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
5243 index = mAudioPatches.indexOfKey(*handle);
5244 if (index >= 0) {
5245 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
5246 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
5247 }
5248 patchDesc = mAudioPatches.valueAt(index);
5249 patchDesc->setUid(uid);
5250 ALOGV("%s success", __func__);
5251 } else {
5252 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
5253 return INVALID_OPERATION;
5254 }
5255 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5256 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5257 // input device to input mix connection
5258 // only one sink supported when connecting an input device to a mix
5259 if (patch->num_sinks > 1) {
5260 return INVALID_OPERATION;
5261 }
5262 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
5263 if (inputDesc == NULL) {
5264 return BAD_VALUE;
5265 }
5266 if (patchDesc != 0) {
5267 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5268 return BAD_VALUE;
5269 }
5270 }
5271 sp<DeviceDescriptor> device =
5272 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5273 if (device == 0) {
5274 return BAD_VALUE;
5275 }
5276
5277 if (inputDesc->mProfile->getCompatibilityScore(
5278 DeviceVector(device),
5279 patch->sinks[0].sample_rate,
5280 nullptr, /*updatedSampleRate*/
5281 patch->sinks[0].format,
5282 nullptr, /*updatedFormat*/
5283 patch->sinks[0].channel_mask,
5284 nullptr, /*updatedChannelMask*/
5285 // FIXME for the parameter type,
5286 // and the NONE
5287 (audio_output_flags_t)
5288 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
5289 return INVALID_OPERATION;
5290 }
5291 // TODO: reconfigure output format and channels here
5292 ALOGV("%s setting device %s on output %d", __func__,
5293 device->toString().c_str(), inputDesc->mIoHandle);
5294 setInputDevice(inputDesc->mIoHandle, device, true, handle);
5295 index = mAudioPatches.indexOfKey(*handle);
5296 if (index >= 0) {
5297 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
5298 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
5299 }
5300 patchDesc = mAudioPatches.valueAt(index);
5301 patchDesc->setUid(uid);
5302 ALOGV("%s success", __func__);
5303 } else {
5304 ALOGW("%s setInputDevice() failed to create a patch", __func__);
5305 return INVALID_OPERATION;
5306 }
5307 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5308 // device to device connection
5309 if (patchDesc != 0) {
5310 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
5311 return BAD_VALUE;
5312 }
5313 }
5314 sp<DeviceDescriptor> srcDevice =
5315 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5316 if (srcDevice == 0) {
5317 return BAD_VALUE;
5318 }
5319
5320 //update source and sink with our own data as the data passed in the patch may
5321 // be incomplete.
5322 PatchBuilder patchBuilder;
5323 audio_port_config sourcePortConfig = {};
5324
5325 // if first sink is to MSD, establish single MSD patch
5326 if (getMsdAudioOutDevices().contains(
5327 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5328 ALOGV("%s patching to MSD", __FUNCTION__);
5329 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5330 goto installPatch;
5331 }
5332
5333 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5334 patchBuilder.addSource(sourcePortConfig);
5335
5336 for (size_t i = 0; i < patch->num_sinks; i++) {
5337 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
5338 ALOGV("%s source device but one sink is not a device", __func__);
5339 return INVALID_OPERATION;
5340 }
5341 sp<DeviceDescriptor> sinkDevice =
5342 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5343 if (sinkDevice == 0) {
5344 return BAD_VALUE;
5345 }
5346 audio_port_config sinkPortConfig = {};
5347 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5348 patchBuilder.addSink(sinkPortConfig);
5349
5350 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5351 // volume management purpose (tracking activity)
5352 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5353 // in config XML to reach the sink so that is can be declared as available.
5354 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
5355 sp<SwAudioOutputDescriptor> outputDesc;
5356 if (!sourceDesc->isInternal()) {
5357 // take care of dynamic routing for SwOutput selection,
5358 audio_attributes_t attributes = sourceDesc->attributes();
5359 audio_stream_type_t stream = sourceDesc->stream();
5360 audio_attributes_t resultAttr;
5361 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5362 config.sample_rate = sourceDesc->config().sample_rate;
5363 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5364 config.channel_mask =
5365 (audio_channel_mask_get_representation(sourceMask)
5366 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5367 : audio_channel_mask_in_to_out(sourceMask);
5368 config.format = sourceDesc->config().format;
5369 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5370 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5371 bool isRequestedDeviceForExclusiveUse = false;
5372 output_type_t outputType;
5373 bool isSpatialized;
5374 bool isBitPerfect;
5375 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5376 &stream, sourceDesc->uid(), &config, &flags,
5377 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
5378 nullptr, &outputType, &isSpatialized, &isBitPerfect);
5379 if (output == AUDIO_IO_HANDLE_NONE) {
5380 ALOGV("%s no output for device %s",
5381 __FUNCTION__, sinkDevice->toString().c_str());
5382 return INVALID_OPERATION;
5383 }
5384 outputDesc = mOutputs.valueFor(output);
5385 if (outputDesc->isDuplicated()) {
5386 ALOGE("%s output is duplicated", __func__);
5387 return INVALID_OPERATION;
5388 }
5389 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5390 sourceDesc->setSwOutput(outputDesc, closeOutput);
5391 } else {
5392 // Same for "raw patches" aka created from createAudioPatch API
5393 SortedVector<audio_io_handle_t> outputs =
5394 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5395 // if the sink device is reachable via an opened output stream, request to
5396 // go via this output stream by adding a second source to the patch
5397 // description
5398 output = selectOutput(outputs);
5399 if (output == AUDIO_IO_HANDLE_NONE) {
5400 ALOGE("%s no output available for internal patch sink", __func__);
5401 return INVALID_OPERATION;
5402 }
5403 outputDesc = mOutputs.valueFor(output);
5404 if (outputDesc->isDuplicated()) {
5405 ALOGV("%s output for device %s is duplicated",
5406 __func__, sinkDevice->toString().c_str());
5407 return INVALID_OPERATION;
5408 }
5409 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
5410 }
5411 // create a software bridge in PatchPanel if:
5412 // - source and sink devices are on different HW modules OR
5413 // - audio HAL version is < 3.0
5414 // - audio HAL version is >= 3.0 but no route has been declared between devices
5415 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5416 // does not have a gain controller
5417 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5418 (srcDevice->getModuleVersionMajor() < 3) ||
5419 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
5420 (!sourceDesc->isInternal() &&
5421 srcDevice->getAudioPort()->getGains().size() == 0)) {
5422 // support only one sink device for now to simplify output selection logic
5423 if (patch->num_sinks > 1) {
5424 return INVALID_OPERATION;
5425 }
5426 sourceDesc->setUseSwBridge();
5427 if (outputDesc != nullptr) {
5428 audio_port_config srcMixPortConfig = {};
5429 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
5430 // for volume control, we may need a valid stream
5431 srcMixPortConfig.ext.mix.usecase.stream =
5432 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
5433 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5434 AUDIO_STREAM_PATCH;
5435 patchBuilder.addSource(srcMixPortConfig);
5436 }
5437 }
5438 }
5439 // TODO: check from routing capabilities in config file and other conflicting patches
5440
5441 installPatch:
5442 status_t status = installPatch(
5443 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
5444 if (status != NO_ERROR) {
5445 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5446 return INVALID_OPERATION;
5447 }
5448 } else {
5449 return BAD_VALUE;
5450 }
5451 } else {
5452 return BAD_VALUE;
5453 }
5454 return NO_ERROR;
5455 }
5456
releaseAudioPatch(audio_patch_handle_t handle,uid_t uid)5457 status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
5458 {
5459 ALOGV("%s patch %d", __func__, handle);
5460 ssize_t index = mAudioPatches.indexOfKey(handle);
5461
5462 if (index < 0) {
5463 return BAD_VALUE;
5464 }
5465 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5466 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5467 __func__, mUidCached, patchDesc->getUid(), uid);
5468 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
5469 return INVALID_OPERATION;
5470 }
5471 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5472 for (size_t i = 0; i < mAudioSources.size(); i++) {
5473 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5474 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5475 portId = sourceDesc->portId();
5476 break;
5477 }
5478 }
5479 return portId != AUDIO_PORT_HANDLE_NONE ?
5480 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
5481 }
5482
releaseAudioPatchInternal(audio_patch_handle_t handle,uint32_t delayMs,const sp<SourceClientDescriptor> & sourceDesc)5483 status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
5484 uint32_t delayMs,
5485 const sp<SourceClientDescriptor>& sourceDesc)
5486 {
5487 ALOGV("%s patch %d", __func__, handle);
5488 if (mAudioPatches.indexOfKey(handle) < 0) {
5489 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5490 return BAD_VALUE;
5491 }
5492 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
5493 struct audio_patch *patch = &patchDesc->mPatch;
5494 patchDesc->setUid(mUidCached);
5495 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
5496 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
5497 if (outputDesc == NULL) {
5498 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
5499 return BAD_VALUE;
5500 }
5501
5502 setOutputDevices(__func__, outputDesc,
5503 getNewOutputDevices(outputDesc, true /*fromCache*/),
5504 true,
5505 0,
5506 NULL);
5507 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5508 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5509 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
5510 if (inputDesc == NULL) {
5511 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
5512 return BAD_VALUE;
5513 }
5514 setInputDevice(inputDesc->mIoHandle,
5515 getNewInputDevice(inputDesc),
5516 true,
5517 NULL);
5518 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5519 status_t status =
5520 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5521 ALOGV("%s patch panel returned %d patchHandle %d",
5522 __func__, status, patchDesc->getAfHandle());
5523 removeAudioPatch(patchDesc->getHandle());
5524 nextAudioPortGeneration();
5525 mpClientInterface->onAudioPatchListUpdate();
5526 // SW or HW Bridge
5527 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5528 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
5529 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
5530 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5531 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5532 outputDesc = sourceDesc->swOutput().promote();
5533 }
5534 if (outputDesc == nullptr) {
5535 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5536 // releaseOutput has already called closeOutput in case of direct output
5537 return NO_ERROR;
5538 }
5539 patchHandle = outputDesc->getPatchHandle();
5540 // While using a HwBridge, force reconsidering device only if not reusing an existing
5541 // output and no more activity on output (will force to close).
5542 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
5543 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5544 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5545 // Reconsider device only for cases:
5546 // 1 / Active Output
5547 // 2 / Inactive Output previously hosting HwBridge
5548 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5549 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5550 sourceDesc->canCloseOutput();
5551 setOutputDevices(__func__, outputDesc,
5552 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5553 outputDesc->devices(),
5554 force,
5555 0,
5556 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
5557 } else {
5558 return BAD_VALUE;
5559 }
5560 } else {
5561 return BAD_VALUE;
5562 }
5563 return NO_ERROR;
5564 }
5565
listAudioPatches(unsigned int * num_patches,struct audio_patch * patches,unsigned int * generation)5566 status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5567 struct audio_patch *patches,
5568 unsigned int *generation)
5569 {
5570 if (generation == NULL) {
5571 return BAD_VALUE;
5572 }
5573 *generation = curAudioPortGeneration();
5574 return mAudioPatches.listAudioPatches(num_patches, patches);
5575 }
5576
setAudioPortConfig(const struct audio_port_config * config)5577 status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
5578 {
5579 ALOGV("setAudioPortConfig()");
5580
5581 if (config == NULL) {
5582 return BAD_VALUE;
5583 }
5584 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5585 // Only support gain configuration for now
5586 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5587 return INVALID_OPERATION;
5588 }
5589
5590 sp<AudioPortConfig> audioPortConfig;
5591 if (config->type == AUDIO_PORT_TYPE_MIX) {
5592 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5593 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
5594 if (outputDesc == NULL) {
5595 return BAD_VALUE;
5596 }
5597 ALOG_ASSERT(!outputDesc->isDuplicated(),
5598 "setAudioPortConfig() called on duplicated output %d",
5599 outputDesc->mIoHandle);
5600 audioPortConfig = outputDesc;
5601 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5602 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
5603 if (inputDesc == NULL) {
5604 return BAD_VALUE;
5605 }
5606 audioPortConfig = inputDesc;
5607 } else {
5608 return BAD_VALUE;
5609 }
5610 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5611 sp<DeviceDescriptor> deviceDesc;
5612 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5613 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5614 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5615 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5616 } else {
5617 return BAD_VALUE;
5618 }
5619 if (deviceDesc == NULL) {
5620 return BAD_VALUE;
5621 }
5622 audioPortConfig = deviceDesc;
5623 } else {
5624 return BAD_VALUE;
5625 }
5626
5627 struct audio_port_config backupConfig = {};
5628 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5629 if (status == NO_ERROR) {
5630 struct audio_port_config newConfig = {};
5631 audioPortConfig->toAudioPortConfig(&newConfig, config);
5632 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
5633 }
5634 if (status != NO_ERROR) {
5635 audioPortConfig->applyAudioPortConfig(&backupConfig);
5636 }
5637
5638 return status;
5639 }
5640
releaseResourcesForUid(uid_t uid)5641 void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5642 {
5643 clearAudioSources(uid);
5644 clearAudioPatches(uid);
5645 clearSessionRoutes(uid);
5646 }
5647
clearAudioPatches(uid_t uid)5648 void AudioPolicyManager::clearAudioPatches(uid_t uid)
5649 {
5650 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
5651 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
5652 if (patchDesc->getUid() == uid) {
5653 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
5654 }
5655 }
5656 }
5657
checkStrategyRoute(product_strategy_t ps,audio_io_handle_t ouptutToSkip)5658 void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
5659 {
5660 // Take the first attributes following the product strategy as it is used to retrieve the routed
5661 // device. All attributes wihin a strategy follows the same "routing strategy"
5662 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5663 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
5664 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
5665 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
5666 for (size_t j = 0; j < mOutputs.size(); j++) {
5667 if (mOutputs.keyAt(j) == ouptutToSkip) {
5668 continue;
5669 }
5670 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
5671 if (!outputDesc->isStrategyActive(ps)) {
5672 continue;
5673 }
5674 // If the default device for this strategy is on another output mix,
5675 // invalidate all tracks in this strategy to force re connection.
5676 // Otherwise select new device on the output mix.
5677 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
5678 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
5679 } else {
5680 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5681 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
5682 // If the device is using preferred mixer attributes, the output need to reopen
5683 // with default configuration when the new selected devices are different from
5684 // current routing devices.
5685 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5686 continue;
5687 }
5688 setOutputDevices(__func__, outputDesc, newDevices, false);
5689 }
5690 }
5691 reopenOutputsWithDevices(outputsToReopen);
5692 }
5693
clearSessionRoutes(uid_t uid)5694 void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5695 {
5696 // remove output routes associated with this uid
5697 std::vector<product_strategy_t> affectedStrategies;
5698 for (size_t i = 0; i < mOutputs.size(); i++) {
5699 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
5700 for (const auto& client : outputDesc->getClientIterable()) {
5701 if (client->hasPreferredDevice() && client->uid() == uid) {
5702 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5703 auto clientStrategy = client->strategy();
5704 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5705 end(affectedStrategies)) {
5706 continue;
5707 }
5708 affectedStrategies.push_back(client->strategy());
5709 }
5710 }
5711 }
5712 // reroute outputs if necessary
5713 for (const auto& strategy : affectedStrategies) {
5714 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
5715 }
5716
5717 // remove input routes associated with this uid
5718 SortedVector<audio_source_t> affectedSources;
5719 for (size_t i = 0; i < mInputs.size(); i++) {
5720 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
5721 for (const auto& client : inputDesc->getClientIterable()) {
5722 if (client->hasPreferredDevice() && client->uid() == uid) {
5723 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5724 affectedSources.add(client->source());
5725 }
5726 }
5727 }
5728 // reroute inputs if necessary
5729 SortedVector<audio_io_handle_t> inputsToClose;
5730 for (size_t i = 0; i < mInputs.size(); i++) {
5731 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
5732 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
5733 inputsToClose.add(inputDesc->mIoHandle);
5734 }
5735 }
5736 for (const auto& input : inputsToClose) {
5737 closeInput(input);
5738 }
5739 }
5740
clearAudioSources(uid_t uid)5741 void AudioPolicyManager::clearAudioSources(uid_t uid)
5742 {
5743 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
5744 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5745 if (sourceDesc->uid() == uid) {
5746 stopAudioSource(mAudioSources.keyAt(i));
5747 }
5748 }
5749 }
5750
acquireSoundTriggerSession(audio_session_t * session,audio_io_handle_t * ioHandle,audio_devices_t * device)5751 status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5752 audio_io_handle_t *ioHandle,
5753 audio_devices_t *device)
5754 {
5755 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5756 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
5757 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
5758 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5759 if (deviceDesc == nullptr) {
5760 return INVALID_OPERATION;
5761 }
5762 *device = deviceDesc->type();
5763
5764 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
5765 }
5766
startAudioSource(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId,uid_t uid)5767 status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
5768 const audio_attributes_t *attributes,
5769 audio_port_handle_t *portId,
5770 uid_t uid) {
5771 return startAudioSourceInternal(source, attributes, portId, uid,
5772 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
5773 }
5774
startAudioSourceInternal(const struct audio_port_config * source,const audio_attributes_t * attributes,audio_port_handle_t * portId,uid_t uid,bool internal,bool isCallRx,uint32_t delayMs)5775 status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5776 const audio_attributes_t *attributes,
5777 audio_port_handle_t *portId,
5778 uid_t uid, bool internal, bool isCallRx,
5779 uint32_t delayMs)
5780 {
5781 ALOGV("%s", __FUNCTION__);
5782 *portId = AUDIO_PORT_HANDLE_NONE;
5783
5784 if (source == NULL || attributes == NULL || portId == NULL) {
5785 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5786 __FUNCTION__, source, attributes, portId);
5787 return BAD_VALUE;
5788 }
5789
5790 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5791 source->type != AUDIO_PORT_TYPE_DEVICE) {
5792 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5793 __FUNCTION__, source->role, source->type);
5794 return INVALID_OPERATION;
5795 }
5796
5797 sp<DeviceDescriptor> srcDevice =
5798 mAvailableInputDevices.getDevice(source->ext.device.type,
5799 String8(source->ext.device.address),
5800 AUDIO_FORMAT_DEFAULT);
5801 if (srcDevice == 0) {
5802 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
5803 return BAD_VALUE;
5804 }
5805
5806 *portId = PolicyAudioPort::getNextUniqueId();
5807
5808 sp<SourceClientDescriptor> sourceDesc =
5809 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
5810 mEngine->getStreamTypeForAttributes(*attributes),
5811 mEngine->getProductStrategyForAttributes(*attributes),
5812 toVolumeSource(*attributes), internal, isCallRx, false);
5813
5814 status_t status = connectAudioSource(sourceDesc, delayMs);
5815 if (status == NO_ERROR) {
5816 mAudioSources.add(*portId, sourceDesc);
5817 }
5818 return status;
5819 }
5820
connectAudioSource(const sp<SourceClientDescriptor> & sourceDesc,uint32_t delayMs)5821 status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5822 uint32_t delayMs)
5823 {
5824 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
5825
5826 // make sure we only have one patch per source.
5827 disconnectAudioSource(sourceDesc);
5828
5829 audio_attributes_t attributes = sourceDesc->attributes();
5830 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5831 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5832 sourceDesc->srcDevice()->type(),
5833 String8(sourceDesc->srcDevice()->address().c_str()),
5834 AUDIO_FORMAT_DEFAULT);
5835 DeviceVector sinkDevices =
5836 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
5837 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
5838 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
5839 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5840 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5841 return INVALID_OPERATION;
5842 }
5843 PatchBuilder patchBuilder;
5844 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5845 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
5846
5847 return connectAudioSourceToSink(
5848 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
5849 }
5850
stopAudioSource(audio_port_handle_t portId)5851 status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
5852 {
5853 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5854 ALOGV("%s port ID %d", __FUNCTION__, portId);
5855 if (sourceDesc == 0) {
5856 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
5857 return BAD_VALUE;
5858 }
5859 status_t status = disconnectAudioSource(sourceDesc);
5860
5861 mAudioSources.removeItem(portId);
5862 return status;
5863 }
5864
setMasterMono(bool mono)5865 status_t AudioPolicyManager::setMasterMono(bool mono)
5866 {
5867 if (mMasterMono == mono) {
5868 return NO_ERROR;
5869 }
5870 mMasterMono = mono;
5871 // if enabling mono we close all offloaded devices, which will invalidate the
5872 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5873 // for recreating the new AudioTrack as non-offloaded PCM.
5874 //
5875 // If disabling mono, we leave all tracks as is: we don't know which clients
5876 // and tracks are able to be recreated as offloaded. The next "song" should
5877 // play back offloaded.
5878 if (mMasterMono) {
5879 Vector<audio_io_handle_t> offloaded;
5880 for (size_t i = 0; i < mOutputs.size(); ++i) {
5881 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5882 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5883 offloaded.push(desc->mIoHandle);
5884 }
5885 }
5886 for (const auto& handle : offloaded) {
5887 closeOutput(handle);
5888 }
5889 }
5890 // update master mono for all remaining outputs
5891 for (size_t i = 0; i < mOutputs.size(); ++i) {
5892 updateMono(mOutputs.keyAt(i));
5893 }
5894 return NO_ERROR;
5895 }
5896
getMasterMono(bool * mono)5897 status_t AudioPolicyManager::getMasterMono(bool *mono)
5898 {
5899 *mono = mMasterMono;
5900 return NO_ERROR;
5901 }
5902
getStreamVolumeDB(audio_stream_type_t stream,int index,audio_devices_t device)5903 float AudioPolicyManager::getStreamVolumeDB(
5904 audio_stream_type_t stream, int index, audio_devices_t device)
5905 {
5906 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
5907 }
5908
getSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats,bool * surroundFormatsEnabled)5909 status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5910 audio_format_t *surroundFormats,
5911 bool *surroundFormatsEnabled)
5912 {
5913 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5914 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
5915 return BAD_VALUE;
5916 }
5917 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5918 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
5919
5920 size_t formatsWritten = 0;
5921 size_t formatsMax = *numSurroundFormats;
5922
5923 *numSurroundFormats = mConfig->getSurroundFormats().size();
5924 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5925 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
5926 for (const auto& format: mConfig->getSurroundFormats()) {
5927 if (formatsWritten < formatsMax) {
5928 surroundFormats[formatsWritten] = format.first;
5929 bool formatEnabled = true;
5930 switch (forceUse) {
5931 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
5932 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
5933 break;
5934 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5935 formatEnabled = false;
5936 break;
5937 default: // AUTO or ALWAYS => true
5938 break;
5939 }
5940 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5941 }
5942 }
5943 return NO_ERROR;
5944 }
5945
getReportedSurroundFormats(unsigned int * numSurroundFormats,audio_format_t * surroundFormats)5946 status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5947 audio_format_t *surroundFormats) {
5948 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5949 return BAD_VALUE;
5950 }
5951 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5952 __func__, *numSurroundFormats, surroundFormats);
5953
5954 size_t formatsWritten = 0;
5955 size_t formatsMax = *numSurroundFormats;
5956 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5957
5958 // Return formats from all device profiles that have already been resolved by
5959 // checkOutputsForDevice().
5960 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5961 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5962 audio_devices_t deviceType = device->type();
5963 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5964 // returns formats reported by HDMI devices.
5965 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5966 continue;
5967 }
5968 // Formats reported by sink devices
5969 std::unordered_set<audio_format_t> formatset;
5970 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5971 formatset.insert(it->second.begin(), it->second.end());
5972 }
5973
5974 // Formats hard-coded in the in policy configuration file (if any).
5975 FormatVector encodedFormats = device->encodedFormats();
5976 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5977 // Filter the formats which are supported by the vendor hardware.
5978 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5979 if (mConfig->getSurroundFormats().count(*it) != 0) {
5980 formats.insert(*it);
5981 } else {
5982 for (const auto& pair : mConfig->getSurroundFormats()) {
5983 if (pair.second.count(*it) != 0) {
5984 formats.insert(pair.first);
5985 break;
5986 }
5987 }
5988 }
5989 }
5990 }
5991 *numSurroundFormats = formats.size();
5992 for (const auto& format: formats) {
5993 if (formatsWritten < formatsMax) {
5994 surroundFormats[formatsWritten++] = format;
5995 }
5996 }
5997 return NO_ERROR;
5998 }
5999
setSurroundFormatEnabled(audio_format_t audioFormat,bool enabled)6000 status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6001 {
6002 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
6003 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6004 if (formatIter == mConfig->getSurroundFormats().end()) {
6005 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
6006 return BAD_VALUE;
6007 }
6008
6009 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6010 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
6011 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
6012 return INVALID_OPERATION;
6013 }
6014
6015 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
6016 return NO_ERROR;
6017 }
6018
6019 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
6020 if (enabled) {
6021 mManualSurroundFormats.insert(audioFormat);
6022 for (const auto& subFormat : formatIter->second) {
6023 mManualSurroundFormats.insert(subFormat);
6024 }
6025 } else {
6026 mManualSurroundFormats.erase(audioFormat);
6027 for (const auto& subFormat : formatIter->second) {
6028 mManualSurroundFormats.erase(subFormat);
6029 }
6030 }
6031
6032 sp<SwAudioOutputDescriptor> outputDesc;
6033 bool profileUpdated = false;
6034 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6035 AUDIO_DEVICE_OUT_HDMI);
6036 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6037 // Simulate reconnection to update enabled surround sound formats.
6038 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
6039 std::string name = hdmiOutputDevices[i]->getName();
6040 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6041 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6042 address.c_str(),
6043 name.c_str(),
6044 AUDIO_FORMAT_DEFAULT);
6045 if (status != NO_ERROR) {
6046 continue;
6047 }
6048 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6049 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6050 address.c_str(),
6051 name.c_str(),
6052 AUDIO_FORMAT_DEFAULT);
6053 profileUpdated |= (status == NO_ERROR);
6054 }
6055 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
6056 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
6057 AUDIO_DEVICE_IN_HDMI);
6058 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6059 // Simulate reconnection to update enabled surround sound formats.
6060 String8 address = String8(hdmiInputDevices[i]->address().c_str());
6061 std::string name = hdmiInputDevices[i]->getName();
6062 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6063 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6064 address.c_str(),
6065 name.c_str(),
6066 AUDIO_FORMAT_DEFAULT);
6067 if (status != NO_ERROR) {
6068 continue;
6069 }
6070 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6071 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6072 address.c_str(),
6073 name.c_str(),
6074 AUDIO_FORMAT_DEFAULT);
6075 profileUpdated |= (status == NO_ERROR);
6076 }
6077
6078 if (!profileUpdated) {
6079 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
6080 mManualSurroundFormats = std::move(surroundFormatsBackup);
6081 }
6082
6083 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6084 }
6085
setAppState(audio_port_handle_t portId,app_state_t state)6086 void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
6087 {
6088 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
6089 for (size_t i = 0; i < mInputs.size(); i++) {
6090 mInputs.valueAt(i)->setAppState(portId, state);
6091 }
6092 }
6093
isHapticPlaybackSupported()6094 bool AudioPolicyManager::isHapticPlaybackSupported()
6095 {
6096 for (const auto& hwModule : mHwModules) {
6097 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6098 for (const auto &outProfile : outputProfiles) {
6099 struct audio_port audioPort;
6100 outProfile->toAudioPort(&audioPort);
6101 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6102 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6103 return true;
6104 }
6105 }
6106 }
6107 }
6108 return false;
6109 }
6110
isUltrasoundSupported()6111 bool AudioPolicyManager::isUltrasoundSupported()
6112 {
6113 bool hasUltrasoundOutput = false;
6114 bool hasUltrasoundInput = false;
6115 for (const auto& hwModule : mHwModules) {
6116 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6117 if (!hasUltrasoundOutput) {
6118 for (const auto &outProfile : outputProfiles) {
6119 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6120 hasUltrasoundOutput = true;
6121 break;
6122 }
6123 }
6124 }
6125
6126 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6127 if (!hasUltrasoundInput) {
6128 for (const auto &inputProfile : inputProfiles) {
6129 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6130 hasUltrasoundInput = true;
6131 break;
6132 }
6133 }
6134 }
6135
6136 if (hasUltrasoundOutput && hasUltrasoundInput)
6137 return true;
6138 }
6139 return false;
6140 }
6141
isHotwordStreamSupported(bool lookbackAudio)6142 bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6143 {
6144 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6145 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6146 for (const auto& hwModule : mHwModules) {
6147 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6148 for (const auto &inputProfile : inputProfiles) {
6149 if ((inputProfile->getFlags() & mask) == mask) {
6150 return true;
6151 }
6152 }
6153 }
6154 return false;
6155 }
6156
isCallScreenModeSupported()6157 bool AudioPolicyManager::isCallScreenModeSupported()
6158 {
6159 return mConfig->isCallScreenModeSupported();
6160 }
6161
6162
disconnectAudioSource(const sp<SourceClientDescriptor> & sourceDesc)6163 status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
6164 {
6165 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
6166 if (!sourceDesc->isConnected()) {
6167 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6168 return NO_ERROR;
6169 }
6170 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6171 if (swOutput != 0) {
6172 status_t status = stopSource(swOutput, sourceDesc);
6173 if (status == NO_ERROR) {
6174 swOutput->stop();
6175 }
6176 if (releaseOutput(sourceDesc->portId())) {
6177 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6178 // no need to release audio patch here but just return NO_ERROR.
6179 return NO_ERROR;
6180 }
6181 } else {
6182 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
6183 if (hwOutputDesc != 0) {
6184 // close Hwoutput and remove from mHwOutputs
6185 } else {
6186 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6187 }
6188 }
6189 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
6190 sourceDesc->disconnect();
6191 return status;
6192 }
6193
getSourceForAttributesOnOutput(audio_io_handle_t output,const audio_attributes_t & attr)6194 sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6195 audio_io_handle_t output, const audio_attributes_t &attr)
6196 {
6197 sp<SourceClientDescriptor> source;
6198 for (size_t i = 0; i < mAudioSources.size(); i++) {
6199 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6200 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
6201 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6202 outputDesc != 0 && outputDesc->mIoHandle == output) {
6203 source = sourceDesc;
6204 break;
6205 }
6206 }
6207 return source;
6208 }
6209
canBeSpatializedInt(const audio_attributes_t * attr,const audio_config_t * config,const AudioDeviceTypeAddrVector & devices) const6210 bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
6211 const audio_config_t *config,
6212 const AudioDeviceTypeAddrVector &devices) const
6213 {
6214 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6215 // the AUDIO_ATTRIBUTES_INITIALIZER value.
6216 // If attributes are specified, current policy is to only allow spatialization for media
6217 // and game usages.
6218 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6219 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6220 return false;
6221 }
6222 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6223 return false;
6224 }
6225 }
6226
6227 // The caller can have the audio config criteria ignored by either passing a null ptr or
6228 // the AUDIO_CONFIG_INITIALIZER value.
6229 // If an audio config is specified, current policy is to only allow spatialization for
6230 // some positional channel masks and PCM format and for stereo if low latency performance
6231 // mode is not requested.
6232
6233 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
6234 static const bool stereo_spatialization_enabled =
6235 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
6236 const bool channel_mask_spatialized =
6237 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
6238 ? audio_channel_mask_contains_stereo(config->channel_mask)
6239 : audio_is_channel_mask_spatialized(config->channel_mask);
6240 if (!channel_mask_spatialized) {
6241 return false;
6242 }
6243 if (!audio_is_linear_pcm(config->format)) {
6244 return false;
6245 }
6246 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6247 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6248 return false;
6249 }
6250 }
6251
6252 sp<IOProfile> profile =
6253 getSpatializerOutputProfile(config, devices);
6254 if (profile == nullptr) {
6255 return false;
6256 }
6257
6258 return true;
6259 }
6260
6261 // The Spatializer output is compatible with Haptic use cases if:
6262 // 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6263 // with client if client haptic channel bits were set, or
6264 // 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6265 // including the haptic bits or creating the HapticGenerator effect for same session.
checkHapticCompatibilityOnSpatializerOutput(const audio_config_t * config,audio_session_t sessionId) const6266 bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6267 const audio_config_t* config, audio_session_t sessionId) const {
6268 const auto clientHapticChannel =
6269 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6270 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6271 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6272
6273 if (threadOutputHapticChannel) {
6274 // check format and sampleRate match if client haptic channel mask exist
6275 if (clientHapticChannel) {
6276 return mSpatializerOutput->getFormat() == config->format &&
6277 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6278 }
6279 return true;
6280 } else {
6281 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6282 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6283 // HapticGenerator effect for this session) are not supported.
6284 return clientHapticChannel == 0 &&
6285 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6286 }
6287 }
6288
checkVirtualizerClientRoutes()6289 void AudioPolicyManager::checkVirtualizerClientRoutes() {
6290 std::set<audio_stream_type_t> streamsToInvalidate;
6291 for (size_t i = 0; i < mOutputs.size(); i++) {
6292 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6293 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6294 audio_attributes_t attr = client->attributes();
6295 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6296 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6297 audio_config_base_t clientConfig = client->config();
6298 audio_config_t config = audio_config_initializer(&clientConfig);
6299 if (desc != mSpatializerOutput
6300 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
6301 streamsToInvalidate.insert(client->stream());
6302 }
6303 }
6304 }
6305
6306 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
6307 }
6308
6309
isOutputOnlyAvailableRouteToSomeDevice(const sp<SwAudioOutputDescriptor> & outputDesc)6310 bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6311 const sp<SwAudioOutputDescriptor>& outputDesc) {
6312 if (outputDesc->isDuplicated()) {
6313 return false;
6314 }
6315 DeviceVector devices = outputDesc->supportedDevices();
6316 for (size_t i = 0; i < mOutputs.size(); i++) {
6317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6318 if (desc == outputDesc || desc->isDuplicated()) {
6319 continue;
6320 }
6321 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6322 if (!sharedDevices.isEmpty()
6323 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6324 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6325 return false;
6326 }
6327 }
6328 return true;
6329 }
6330
6331
getSpatializerOutput(const audio_config_base_t * mixerConfig,const audio_attributes_t * attr,audio_io_handle_t * output)6332 status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
6333 const audio_attributes_t *attr,
6334 audio_io_handle_t *output) {
6335 *output = AUDIO_IO_HANDLE_NONE;
6336
6337 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6338 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6339 audio_config_t *configPtr = nullptr;
6340 audio_config_t config;
6341 if (mixerConfig != nullptr) {
6342 config = audio_config_initializer(mixerConfig);
6343 configPtr = &config;
6344 }
6345 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
6346 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
6347 return BAD_VALUE;
6348 }
6349
6350 sp<IOProfile> profile =
6351 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
6352 if (profile == nullptr) {
6353 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
6354 return BAD_VALUE;
6355 }
6356
6357 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
6358 for (size_t i = 0; i < mOutputs.size(); i++) {
6359 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6360 if (!desc->isDuplicated()
6361 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6362 spatializerOutputs.push_back(desc);
6363 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
6364 }
6365 }
6366 mSpatializerOutput.clear();
6367 bool outputsChanged = false;
6368 for (const auto& desc : spatializerOutputs) {
6369 if (desc->mProfile == profile
6370 && (configPtr == nullptr
6371 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6372 mSpatializerOutput = desc;
6373 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6374 } else {
6375 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6376 " and devices %s", __func__, desc->mIoHandle,
6377 configPtr != nullptr ? configPtr->channel_mask : 0,
6378 devices.toString().c_str());
6379 closeOutput(desc->mIoHandle);
6380 outputsChanged = true;
6381 }
6382 }
6383
6384 if (mSpatializerOutput == nullptr) {
6385 sp<SwAudioOutputDescriptor> desc =
6386 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
6387 if (desc != nullptr) {
6388 mSpatializerOutput = desc;
6389 outputsChanged = true;
6390 }
6391 }
6392
6393 checkVirtualizerClientRoutes();
6394
6395 if (outputsChanged) {
6396 mPreviousOutputs = mOutputs;
6397 mpClientInterface->onAudioPortListUpdate();
6398 }
6399
6400 if (mSpatializerOutput == nullptr) {
6401 ALOGV("%s could not open spatializer output with requested config", __func__);
6402 return BAD_VALUE;
6403 }
6404 *output = mSpatializerOutput->mIoHandle;
6405 ALOGV("%s returning new spatializer output %d", __func__, *output);
6406 return OK;
6407 }
6408
releaseSpatializerOutput(audio_io_handle_t output)6409 status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6410 if (mSpatializerOutput == nullptr) {
6411 return INVALID_OPERATION;
6412 }
6413 if (mSpatializerOutput->mIoHandle != output) {
6414 return BAD_VALUE;
6415 }
6416
6417 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6418 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6419 closeOutput(mSpatializerOutput->mIoHandle);
6420 //from now on mSpatializerOutput is null
6421 checkVirtualizerClientRoutes();
6422 }
6423
6424 return NO_ERROR;
6425 }
6426
6427 // ----------------------------------------------------------------------------
6428 // AudioPolicyManager
6429 // ----------------------------------------------------------------------------
nextAudioPortGeneration()6430 uint32_t AudioPolicyManager::nextAudioPortGeneration()
6431 {
6432 return mAudioPortGeneration++;
6433 }
6434
AudioPolicyManager(const sp<const AudioPolicyConfig> & config,EngineInstance && engine,AudioPolicyClientInterface * clientInterface)6435 AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
6436 EngineInstance&& engine,
6437 AudioPolicyClientInterface *clientInterface)
6438 :
6439 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
6440 mConfig(config),
6441 mEngine(std::move(engine)),
6442 mpClientInterface(clientInterface),
6443 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
6444 mA2dpSuspended(false),
6445 mAudioPortGeneration(1),
6446 mBeaconMuteRefCount(0),
6447 mBeaconPlayingRefCount(0),
6448 mBeaconMuted(false),
6449 mTtsOutputAvailable(false),
6450 mMasterMono(false),
6451 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
6452 {
6453 }
6454
initialize()6455 status_t AudioPolicyManager::initialize() {
6456 if (mEngine == nullptr) {
6457 return NO_INIT;
6458 }
6459 mEngine->setObserver(this);
6460 status_t status = mEngine->initCheck();
6461 if (status != NO_ERROR) {
6462 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6463 return status;
6464 }
6465
6466 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6467 // at the end of this function.
6468 mEngine->initializeDeviceSelectionCache();
6469 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6470 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6471
6472 // after parsing the config, mConfig contain all known devices;
6473 // open all output streams needed to access attached devices
6474 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
6475
6476 // make sure default device is reachable
6477 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6478 defaultOutputDevice == nullptr ||
6479 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6480 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6481 defaultOutputDevice->toString().c_str());
6482 status = NO_INIT;
6483 }
6484 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
6485
6486 // Silence ALOGV statements
6487 property_set("log.tag." LOG_TAG, "D");
6488
6489 updateDevicesAndOutputs();
6490 return status;
6491 }
6492
~AudioPolicyManager()6493 AudioPolicyManager::~AudioPolicyManager()
6494 {
6495 for (size_t i = 0; i < mOutputs.size(); i++) {
6496 mOutputs.valueAt(i)->close();
6497 }
6498 for (size_t i = 0; i < mInputs.size(); i++) {
6499 mInputs.valueAt(i)->close();
6500 }
6501 mAvailableOutputDevices.clear();
6502 mAvailableInputDevices.clear();
6503 mOutputs.clear();
6504 mInputs.clear();
6505 mHwModules.clear();
6506 mManualSurroundFormats.clear();
6507 mConfig.clear();
6508 }
6509
initCheck()6510 status_t AudioPolicyManager::initCheck()
6511 {
6512 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
6513 }
6514
6515 // ---
6516
onNewAudioModulesAvailable()6517 void AudioPolicyManager::onNewAudioModulesAvailable()
6518 {
6519 DeviceVector newDevices;
6520 onNewAudioModulesAvailableInt(&newDevices);
6521 if (!newDevices.empty()) {
6522 nextAudioPortGeneration();
6523 mpClientInterface->onAudioPortListUpdate();
6524 }
6525 }
6526
onNewAudioModulesAvailableInt(DeviceVector * newDevices)6527 void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6528 {
6529 for (const auto& hwModule : mConfig->getHwModules()) {
6530 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6531 continue;
6532 }
6533 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6534 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6535 handle != AUDIO_MODULE_HANDLE_NONE) {
6536 hwModule->setHandle(handle);
6537 } else {
6538 ALOGW("could not load HW module %s", hwModule->getName());
6539 continue;
6540 }
6541 }
6542 mHwModules.push_back(hwModule);
6543 // open all output streams needed to access attached devices.
6544 // direct outputs are closed immediately after checking the availability of attached devices
6545 // This also validates mAvailableOutputDevices list
6546 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6547 if (!outProfile->canOpenNewIo()) {
6548 ALOGE("Invalid Output profile max open count %u for profile %s",
6549 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6550 continue;
6551 }
6552 if (!outProfile->hasSupportedDevices()) {
6553 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6554 continue;
6555 }
6556 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6557 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
6558 mTtsOutputAvailable = true;
6559 }
6560
6561 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6562 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
6563 sp<DeviceDescriptor> supportedDevice = 0;
6564 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6565 supportedDevice = mConfig->getDefaultOutputDevice();
6566 } else {
6567 // choose first device present in profile's SupportedDevices also part of
6568 // mAvailableOutputDevices.
6569 if (availProfileDevices.isEmpty()) {
6570 continue;
6571 }
6572 supportedDevice = availProfileDevices.itemAt(0);
6573 }
6574 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
6575 continue;
6576 }
6577 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6578 mpClientInterface);
6579 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
6580 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6581 DeviceVector(supportedDevice),
6582 AUDIO_STREAM_DEFAULT,
6583 AUDIO_OUTPUT_FLAG_NONE, &output);
6584 if (status != NO_ERROR) {
6585 ALOGW("Cannot open output stream for devices %s on hw module %s",
6586 supportedDevice->toString().c_str(), hwModule->getName());
6587 continue;
6588 }
6589 for (const auto &device : availProfileDevices) {
6590 // give a valid ID to an attached device once confirmed it is reachable
6591 if (!device->isAttached()) {
6592 device->attach(hwModule);
6593 mAvailableOutputDevices.add(device);
6594 device->setEncapsulationInfoFromHal(mpClientInterface);
6595 if (newDevices) newDevices->add(device);
6596 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6597 }
6598 }
6599 if (mPrimaryOutput == nullptr &&
6600 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6601 mPrimaryOutput = outputDesc;
6602 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
6603 }
6604 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
6605 outputDesc->close();
6606 } else {
6607 addOutput(output, outputDesc);
6608 setOutputDevices(__func__, outputDesc,
6609 DeviceVector(supportedDevice),
6610 true,
6611 0,
6612 NULL);
6613 }
6614 }
6615 // open input streams needed to access attached devices to validate
6616 // mAvailableInputDevices list
6617 for (const auto& inProfile : hwModule->getInputProfiles()) {
6618 if (!inProfile->canOpenNewIo()) {
6619 ALOGE("Invalid Input profile max open count %u for profile %s",
6620 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6621 continue;
6622 }
6623 if (!inProfile->hasSupportedDevices()) {
6624 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6625 continue;
6626 }
6627 // chose first device present in profile's SupportedDevices also part of
6628 // available input devices
6629 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6630 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
6631 if (availProfileDevices.isEmpty()) {
6632 ALOGV("%s: Input device list is empty! for profile %s",
6633 __func__, inProfile->getTagName().c_str());
6634 continue;
6635 }
6636 sp<AudioInputDescriptor> inputDesc =
6637 new AudioInputDescriptor(inProfile, mpClientInterface);
6638
6639 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6640 status_t status = inputDesc->open(nullptr,
6641 availProfileDevices.itemAt(0),
6642 AUDIO_SOURCE_MIC,
6643 AUDIO_INPUT_FLAG_NONE,
6644 &input);
6645 if (status != NO_ERROR) {
6646 ALOGW("Cannot open input stream for device %s on hw module %s",
6647 availProfileDevices.toString().c_str(),
6648 hwModule->getName());
6649 continue;
6650 }
6651 for (const auto &device : availProfileDevices) {
6652 // give a valid ID to an attached device once confirmed it is reachable
6653 if (!device->isAttached()) {
6654 device->attach(hwModule);
6655 device->importAudioPortAndPickAudioProfile(inProfile, true);
6656 mAvailableInputDevices.add(device);
6657 if (newDevices) newDevices->add(device);
6658 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6659 }
6660 }
6661 inputDesc->close();
6662 }
6663 }
6664
6665 // Check if spatializer outputs can be closed until used.
6666 // mOutputs vector never contains duplicated outputs at this point.
6667 std::vector<audio_io_handle_t> outputsClosed;
6668 for (size_t i = 0; i < mOutputs.size(); i++) {
6669 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6670 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6671 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6672 outputsClosed.push_back(desc->mIoHandle);
6673 nextAudioPortGeneration();
6674 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6675 if (index >= 0) {
6676 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6677 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6678 patchDesc->getAfHandle(), 0);
6679 mAudioPatches.removeItemsAt(index);
6680 mpClientInterface->onAudioPatchListUpdate();
6681 }
6682 desc->close();
6683 }
6684 }
6685 for (auto output : outputsClosed) {
6686 removeOutput(output);
6687 }
6688 }
6689
addOutput(audio_io_handle_t output,const sp<SwAudioOutputDescriptor> & outputDesc)6690 void AudioPolicyManager::addOutput(audio_io_handle_t output,
6691 const sp<SwAudioOutputDescriptor>& outputDesc)
6692 {
6693 mOutputs.add(output, outputDesc);
6694 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
6695 updateMono(output); // update mono status when adding to output list
6696 selectOutputForMusicEffects();
6697 nextAudioPortGeneration();
6698 }
6699
removeOutput(audio_io_handle_t output)6700 void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6701 {
6702 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6703 ALOGV("%s: removing primary output", __func__);
6704 mPrimaryOutput = nullptr;
6705 }
6706 mOutputs.removeItem(output);
6707 selectOutputForMusicEffects();
6708 }
6709
addInput(audio_io_handle_t input,const sp<AudioInputDescriptor> & inputDesc)6710 void AudioPolicyManager::addInput(audio_io_handle_t input,
6711 const sp<AudioInputDescriptor>& inputDesc)
6712 {
6713 mInputs.add(input, inputDesc);
6714 nextAudioPortGeneration();
6715 }
6716
checkOutputsForDevice(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state,SortedVector<audio_io_handle_t> & outputs)6717 status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
6718 audio_policy_dev_state_t state,
6719 SortedVector<audio_io_handle_t>& outputs)
6720 {
6721 audio_devices_t deviceType = device->type();
6722 const String8 &address = String8(device->address().c_str());
6723 sp<SwAudioOutputDescriptor> desc;
6724
6725 if (audio_device_is_digital(deviceType)) {
6726 // erase all current sample rates, formats and channel masks
6727 device->clearAudioProfiles();
6728 }
6729
6730 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
6731 // first call getAudioPort to get the supported attributes from the HAL
6732 struct audio_port_v7 port = {};
6733 device->toAudioPort(&port);
6734 status_t status = mpClientInterface->getAudioPort(&port);
6735 if (status == NO_ERROR) {
6736 device->importAudioPort(port);
6737 }
6738
6739 // then list already open outputs that can be routed to this device
6740 for (size_t i = 0; i < mOutputs.size(); i++) {
6741 desc = mOutputs.valueAt(i);
6742 if (!desc->isDuplicated() && desc->supportsDevice(device)
6743 && desc->devicesSupportEncodedFormats({deviceType})) {
6744 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6745 mOutputs.keyAt(i), device->toString().c_str());
6746 outputs.add(mOutputs.keyAt(i));
6747 }
6748 }
6749 // then look for output profiles that can be routed to this device
6750 SortedVector< sp<IOProfile> > profiles;
6751 for (const auto& hwModule : mHwModules) {
6752 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6753 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
6754 if (profile->supportsDevice(device)) {
6755 profiles.add(profile);
6756 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6757 j, hwModule->getName());
6758 }
6759 }
6760 }
6761
6762 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
6763
6764 if (profiles.isEmpty() && outputs.isEmpty()) {
6765 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
6766 return BAD_VALUE;
6767 }
6768
6769 // open outputs for matching profiles if needed. Direct outputs are also opened to
6770 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6771 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6772 sp<IOProfile> profile = profiles[profile_index];
6773
6774 // nothing to do if one output is already opened for this profile
6775 size_t j;
6776 for (j = 0; j < outputs.size(); j++) {
6777 desc = mOutputs.valueFor(outputs.itemAt(j));
6778 if (!desc->isDuplicated() && desc->mProfile == profile) {
6779 // matching profile: save the sample rates, format and channel masks supported
6780 // by the profile in our device descriptor
6781 if (audio_device_is_digital(deviceType)) {
6782 device->importAudioPortAndPickAudioProfile(profile);
6783 }
6784 break;
6785 }
6786 }
6787 if (j != outputs.size()) {
6788 continue;
6789 }
6790
6791 if (!profile->canOpenNewIo()) {
6792 ALOGW("Max Output number %u already opened for this profile %s",
6793 profile->maxOpenCount, profile->getTagName().c_str());
6794 continue;
6795 }
6796
6797 ALOGV("opening output for device %08x with params %s profile %p name %s",
6798 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
6799 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6800 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
6801 if (output == AUDIO_IO_HANDLE_NONE) {
6802 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
6803 profiles.removeAt(profile_index);
6804 profile_index--;
6805 } else {
6806 outputs.add(output);
6807 // Load digital format info only for digital devices
6808 if (audio_device_is_digital(deviceType)) {
6809 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6810 // port but just pick audio profile
6811 device->importAudioPortAndPickAudioProfile(profile);
6812 }
6813
6814 if (device_distinguishes_on_address(deviceType)) {
6815 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6816 device->toString().c_str());
6817 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6818 0/*delay*/, NULL/*patch handle*/);
6819 }
6820 ALOGV("checkOutputsForDevice(): adding output %d", output);
6821 }
6822 }
6823
6824 if (profiles.isEmpty()) {
6825 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
6826 return BAD_VALUE;
6827 }
6828 } else { // Disconnect
6829 // check if one opened output is not needed any more after disconnecting one device
6830 for (size_t i = 0; i < mOutputs.size(); i++) {
6831 desc = mOutputs.valueAt(i);
6832 if (!desc->isDuplicated()) {
6833 // exact match on device
6834 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
6835 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
6836 outputs.add(mOutputs.keyAt(i));
6837 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
6838 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6839 mOutputs.keyAt(i));
6840 outputs.add(mOutputs.keyAt(i));
6841 }
6842 }
6843 }
6844 // Clear any profiles associated with the disconnected device.
6845 for (const auto& hwModule : mHwModules) {
6846 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6847 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
6848 if (!profile->supportsDevice(device)) {
6849 continue;
6850 }
6851 ALOGV("checkOutputsForDevice(): "
6852 "clearing direct output profile %zu on module %s",
6853 j, hwModule->getName());
6854 profile->clearAudioProfiles();
6855 if (!profile->hasDynamicAudioProfile()) {
6856 continue;
6857 }
6858 // When a device is disconnected, if there is an IOProfile that contains dynamic
6859 // profiles and supports the disconnected device, call getAudioPort to repopulate
6860 // the capabilities of the devices that is supported by the IOProfile.
6861 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6862 if (supportedDevice == device ||
6863 !mAvailableOutputDevices.contains(supportedDevice)) {
6864 continue;
6865 }
6866 struct audio_port_v7 port;
6867 supportedDevice->toAudioPort(&port);
6868 status_t status = mpClientInterface->getAudioPort(&port);
6869 if (status == NO_ERROR) {
6870 supportedDevice->importAudioPort(port);
6871 }
6872 }
6873 }
6874 }
6875 }
6876 return NO_ERROR;
6877 }
6878
checkInputsForDevice(const sp<DeviceDescriptor> & device,audio_policy_dev_state_t state)6879 status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
6880 audio_policy_dev_state_t state)
6881 {
6882 if (audio_device_is_digital(device->type())) {
6883 // erase all current sample rates, formats and channel masks
6884 device->clearAudioProfiles();
6885 }
6886
6887 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
6888 sp<AudioInputDescriptor> desc;
6889
6890 // first call getAudioPort to get the supported attributes from the HAL
6891 struct audio_port_v7 port = {};
6892 device->toAudioPort(&port);
6893 status_t status = mpClientInterface->getAudioPort(&port);
6894 if (status == NO_ERROR) {
6895 device->importAudioPort(port);
6896 }
6897
6898 // look for input profiles that can be routed to this device
6899 SortedVector< sp<IOProfile> > profiles;
6900 for (const auto& hwModule : mHwModules) {
6901 for (size_t profile_index = 0;
6902 profile_index < hwModule->getInputProfiles().size();
6903 profile_index++) {
6904 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
6905
6906 if (profile->supportsDevice(device)) {
6907 profiles.add(profile);
6908 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6909 profile_index, hwModule->getName());
6910 }
6911 }
6912 }
6913
6914 if (profiles.isEmpty()) {
6915 ALOGW("%s: No input profile available for device %s",
6916 __func__, device->toString().c_str());
6917 return BAD_VALUE;
6918 }
6919
6920 // open inputs for matching profiles if needed. Direct inputs are also opened to
6921 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6922 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6923
6924 sp<IOProfile> profile = profiles[profile_index];
6925
6926 // nothing to do if one input is already opened for this profile
6927 size_t input_index;
6928 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6929 desc = mInputs.valueAt(input_index);
6930 if (desc->mProfile == profile) {
6931 if (audio_device_is_digital(device->type())) {
6932 device->importAudioPortAndPickAudioProfile(profile);
6933 }
6934 break;
6935 }
6936 }
6937 if (input_index != mInputs.size()) {
6938 continue;
6939 }
6940
6941 if (!profile->canOpenNewIo()) {
6942 ALOGW("Max Input number %u already opened for this profile %s",
6943 profile->maxOpenCount, profile->getTagName().c_str());
6944 continue;
6945 }
6946
6947 desc = new AudioInputDescriptor(profile, mpClientInterface);
6948 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6949 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
6950
6951 if (status == NO_ERROR) {
6952 const String8& address = String8(device->address().c_str());
6953 if (!address.empty()) {
6954 char *param = audio_device_address_to_parameter(device->type(), address);
6955 mpClientInterface->setParameters(input, String8(param));
6956 free(param);
6957 }
6958 updateAudioProfiles(device, input, profile);
6959 if (!profile->hasValidAudioProfile()) {
6960 ALOGW("checkInputsForDevice() direct input missing param");
6961 desc->close();
6962 input = AUDIO_IO_HANDLE_NONE;
6963 }
6964
6965 if (input != AUDIO_IO_HANDLE_NONE) {
6966 addInput(input, desc);
6967 }
6968 } // endif input != 0
6969
6970 if (input == AUDIO_IO_HANDLE_NONE) {
6971 ALOGW("%s could not open input for device %s", __func__,
6972 device->toString().c_str());
6973 profiles.removeAt(profile_index);
6974 profile_index--;
6975 } else {
6976 if (audio_device_is_digital(device->type())) {
6977 device->importAudioPortAndPickAudioProfile(profile);
6978 }
6979 ALOGV("checkInputsForDevice(): adding input %d", input);
6980
6981 if (checkCloseInput(desc)) {
6982 ALOGV("%s closing input %d", __func__, input);
6983 closeInput(input);
6984 }
6985 }
6986 } // end scan profiles
6987
6988 if (profiles.isEmpty()) {
6989 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
6990 return BAD_VALUE;
6991 }
6992 } else {
6993 // Disconnect
6994 // Clear any profiles associated with the disconnected device.
6995 for (const auto& hwModule : mHwModules) {
6996 for (size_t profile_index = 0;
6997 profile_index < hwModule->getInputProfiles().size();
6998 profile_index++) {
6999 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
7000 if (profile->supportsDevice(device)) {
7001 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
7002 profile_index, hwModule->getName());
7003 profile->clearAudioProfiles();
7004 }
7005 }
7006 }
7007 } // end disconnect
7008
7009 return NO_ERROR;
7010 }
7011
7012
closeOutput(audio_io_handle_t output)7013 void AudioPolicyManager::closeOutput(audio_io_handle_t output)
7014 {
7015 ALOGV("closeOutput(%d)", output);
7016
7017 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7018 if (closingOutput == NULL) {
7019 ALOGW("closeOutput() unknown output %d", output);
7020 return;
7021 }
7022 const bool closingOutputWasActive = closingOutput->isActive();
7023 mPolicyMixes.closeOutput(closingOutput, mOutputs);
7024
7025 // look for duplicated outputs connected to the output being removed.
7026 for (size_t i = 0; i < mOutputs.size(); i++) {
7027 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7028 if (dupOutput->isDuplicated() &&
7029 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7030 sp<SwAudioOutputDescriptor> remainingOutput =
7031 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
7032 // As all active tracks on duplicated output will be deleted,
7033 // and as they were also referenced on the other output, the reference
7034 // count for their stream type must be adjusted accordingly on
7035 // the other output.
7036 const bool wasActive = remainingOutput->isActive();
7037 // Note: no-op on the closing output where all clients has already been set inactive
7038 dupOutput->setAllClientsInactive();
7039 // stop() will be a no op if the output is still active but is needed in case all
7040 // active streams refcounts where cleared above
7041 if (wasActive) {
7042 remainingOutput->stop();
7043 }
7044 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7045 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7046
7047 mpClientInterface->closeOutput(duplicatedOutput);
7048 removeOutput(duplicatedOutput);
7049 }
7050 }
7051
7052 nextAudioPortGeneration();
7053
7054 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
7055 if (index >= 0) {
7056 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7057 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7058 patchDesc->getAfHandle(), 0);
7059 mAudioPatches.removeItemsAt(index);
7060 mpClientInterface->onAudioPatchListUpdate();
7061 }
7062
7063 if (closingOutputWasActive) {
7064 closingOutput->stop();
7065 }
7066 closingOutput->close();
7067 if (closingOutput->isBitPerfect()) {
7068 for (const auto device : closingOutput->devices()) {
7069 device->setPreferredConfig(nullptr);
7070 }
7071 }
7072
7073 removeOutput(output);
7074 mPreviousOutputs = mOutputs;
7075 if (closingOutput == mSpatializerOutput) {
7076 mSpatializerOutput.clear();
7077 }
7078
7079 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7080 // no direct outputs are open.
7081 if (!getMsdAudioOutDevices().isEmpty()) {
7082 bool directOutputOpen = false;
7083 for (size_t i = 0; i < mOutputs.size(); i++) {
7084 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7085 directOutputOpen = true;
7086 break;
7087 }
7088 }
7089 if (!directOutputOpen) {
7090 ALOGV("no direct outputs open, reset MSD patches");
7091 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7092 // how output devices for patching are resolved. Avoid by caching and reusing the
7093 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7094 // devices to patch to. This may be complicated by the fact that devices may become
7095 // unavailable.
7096 setMsdOutputPatches();
7097 }
7098 }
7099
7100 if (closingOutput->mPreferredAttrInfo != nullptr) {
7101 closingOutput->mPreferredAttrInfo->resetActiveClient();
7102 }
7103 }
7104
closeInput(audio_io_handle_t input)7105 void AudioPolicyManager::closeInput(audio_io_handle_t input)
7106 {
7107 ALOGV("closeInput(%d)", input);
7108
7109 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7110 if (inputDesc == NULL) {
7111 ALOGW("closeInput() unknown input %d", input);
7112 return;
7113 }
7114
7115 nextAudioPortGeneration();
7116
7117 sp<DeviceDescriptor> device = inputDesc->getDevice();
7118 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
7119 if (index >= 0) {
7120 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7121 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7122 patchDesc->getAfHandle(), 0);
7123 mAudioPatches.removeItemsAt(index);
7124 mpClientInterface->onAudioPatchListUpdate();
7125 }
7126
7127 mEffects.putOrphanEffectsForIo(input);
7128 inputDesc->close();
7129 mInputs.removeItem(input);
7130
7131 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7132 if (primaryInputDevices.contains(device) &&
7133 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
7134 mpClientInterface->setSoundTriggerCaptureState(false);
7135 }
7136 }
7137
getOutputsForDevices(const DeviceVector & devices,const SwAudioOutputCollection & openOutputs)7138 SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7139 const DeviceVector &devices,
7140 const SwAudioOutputCollection& openOutputs)
7141 {
7142 SortedVector<audio_io_handle_t> outputs;
7143
7144 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
7145 for (size_t i = 0; i < openOutputs.size(); i++) {
7146 ALOGVV("output %zu isDuplicated=%d device=%s",
7147 i, openOutputs.valueAt(i)->isDuplicated(),
7148 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
7149 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
7150 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
7151 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
7152 outputs.add(openOutputs.keyAt(i));
7153 }
7154 }
7155 return outputs;
7156 }
7157
checkForDeviceAndOutputChanges(std::function<bool ()> onOutputsChecked)7158 void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7159 {
7160 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7161 // output is suspended before any tracks are moved to it
7162 checkA2dpSuspend();
7163 checkOutputForAllStrategies();
7164 checkSecondaryOutputs();
7165 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
7166 updateDevicesAndOutputs();
7167 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
7168 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7169 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7170 // configuration changes will ultimately be rerouted correctly. We can still avoid
7171 // unnecessary rerouting by caching and reusing the arguments to
7172 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7173 // This may be complicated by the fact that devices may become unavailable.
7174 setMsdOutputPatches();
7175 }
7176 // an event that changed routing likely occurred, inform upper layers
7177 mpClientInterface->onRoutingUpdated();
7178 }
7179
followsSameRouting(const audio_attributes_t & lAttr,const audio_attributes_t & rAttr) const7180 bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7181 const audio_attributes_t &rAttr) const
7182 {
7183 return mEngine->getProductStrategyForAttributes(lAttr) ==
7184 mEngine->getProductStrategyForAttributes(rAttr);
7185 }
7186
checkAudioSourceForAttributes(const audio_attributes_t & attr)7187 void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7188 {
7189 for (size_t i = 0; i < mAudioSources.size(); i++) {
7190 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7191 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
7192 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
7193 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
7194 connectAudioSource(sourceDesc, 0 /*delayMs*/);
7195 }
7196 }
7197 }
7198
clearAudioSourcesForOutput(audio_io_handle_t output)7199 void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7200 {
7201 for (size_t i = 0; i < mAudioSources.size(); i++) {
7202 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7203 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7204 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7205 disconnectAudioSource(sourceDesc);
7206 }
7207 }
7208 }
7209
checkOutputForAttributes(const audio_attributes_t & attr)7210 void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7211 {
7212 auto psId = mEngine->getProductStrategyForAttributes(attr);
7213
7214 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7215 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
7216
7217 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7218 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
7219
7220 uint32_t maxLatency = 0;
7221 bool unneededUsePrimaryOutputFromPolicyMixes = false;
7222 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
7223 // take into account dynamic audio policies related changes: if a client is now associated
7224 // to a different policy mix than at creation time, invalidate corresponding stream
7225 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
7226 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7227 if (desc->isDuplicated()) {
7228 continue;
7229 }
7230 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7231 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7232 continue;
7233 }
7234 sp<AudioPolicyMix> primaryMix;
7235 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
7236 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7237 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7238 unneededUsePrimaryOutputFromPolicyMixes);
7239 if (status != OK) {
7240 continue;
7241 }
7242 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7243 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7244 maxLatency = desc->latency();
7245 }
7246 invalidatedOutputs.push_back(desc);
7247 }
7248 }
7249 }
7250
7251 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
7252 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7253 // audio from invalidated tracks will be rendered when unmuting
7254 for (audio_io_handle_t srcOut : srcOutputs) {
7255 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
7256 if (desc == nullptr) continue;
7257
7258 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7259 maxLatency = desc->latency();
7260 }
7261
7262 bool invalidate = false;
7263 for (auto client : desc->clientsList(false /*activeOnly*/)) {
7264 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
7265 // a client on a non direct outputs has necessarily a linear PCM format
7266 // so we can call selectOutput() safely
7267 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7268 client->flags(),
7269 client->config().format,
7270 client->config().channel_mask,
7271 client->config().sample_rate,
7272 client->session());
7273 if (newOutput != srcOut) {
7274 invalidate = true;
7275 break;
7276 }
7277 } else {
7278 sp<IOProfile> profile = getProfileForOutput(newDevices,
7279 client->config().sample_rate,
7280 client->config().format,
7281 client->config().channel_mask,
7282 client->flags(),
7283 true /* directOnly */);
7284 if (profile != desc->mProfile) {
7285 invalidate = true;
7286 break;
7287 }
7288 }
7289 }
7290 // mute strategy while moving tracks from one output to another
7291 if (invalidate) {
7292 invalidatedOutputs.push_back(desc);
7293 if (desc->isStrategyActive(psId)) {
7294 setStrategyMute(psId, true, desc);
7295 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7296 newDevices.types());
7297 }
7298 }
7299 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
7300 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
7301 connectAudioSource(source, 0 /*delayMs*/);
7302 }
7303 }
7304
7305 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7306 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7307 std::to_string(srcOutputs[0]).c_str(),
7308 std::to_string(dstOutputs[0]).c_str());
7309
7310 // Move effects associated to this stream from previous output to new output
7311 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
7312 selectOutputForMusicEffects();
7313 }
7314 // Move tracks associated to this stream (and linked) from previous output to new output
7315 if (!invalidatedOutputs.empty()) {
7316 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
7317 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
7318 desc->setTracksInvalidatedStatusByStrategy(psId);
7319 }
7320 }
7321 }
7322 }
7323
checkOutputForAllStrategies()7324 void AudioPolicyManager::checkOutputForAllStrategies()
7325 {
7326 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7327 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7328 checkOutputForAttributes(attributes);
7329 checkAudioSourceForAttributes(attributes);
7330 }
7331 }
7332
checkSecondaryOutputs()7333 void AudioPolicyManager::checkSecondaryOutputs() {
7334 PortHandleVector clientsToInvalidate;
7335 TrackSecondaryOutputsMap trackSecondaryOutputs;
7336 bool unneededUsePrimaryOutputFromPolicyMixes = false;
7337 for (size_t i = 0; i < mOutputs.size(); i++) {
7338 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7339 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
7340 sp<AudioPolicyMix> primaryMix;
7341 std::vector<sp<AudioPolicyMix>> secondaryMixes;
7342 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
7343 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7344 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7345 unneededUsePrimaryOutputFromPolicyMixes);
7346 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7347 for (auto &secondaryMix : secondaryMixes) {
7348 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7349 if (outputDesc != nullptr &&
7350 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7351 secondaryDescs.push_back(outputDesc);
7352 }
7353 }
7354
7355 if (status != OK &&
7356 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7357 // When it failed to query secondary output, only invalidate the client that is not
7358 // MMAP. The reason is that MMAP stream will not support secondary output.
7359 clientsToInvalidate.push_back(client->portId());
7360 } else if (!std::equal(
7361 client->getSecondaryOutputs().begin(),
7362 client->getSecondaryOutputs().end(),
7363 secondaryDescs.begin(), secondaryDescs.end())) {
7364 if (!audio_is_linear_pcm(client->config().format)) {
7365 // If the format is not PCM, the tracks should be invalidated to get correct
7366 // behavior when the secondary output is changed.
7367 clientsToInvalidate.push_back(client->portId());
7368 } else {
7369 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7370 std::vector<audio_io_handle_t> secondaryOutputIds;
7371 for (const auto &secondaryDesc: secondaryDescs) {
7372 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7373 weakSecondaryDescs.push_back(secondaryDesc);
7374 }
7375 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7376 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
7377 }
7378 }
7379 }
7380 }
7381 if (!trackSecondaryOutputs.empty()) {
7382 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7383 }
7384 if (!clientsToInvalidate.empty()) {
7385 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7386 mpClientInterface->invalidateTracks(clientsToInvalidate);
7387 }
7388 }
7389
isScoRequestedForComm() const7390 bool AudioPolicyManager::isScoRequestedForComm() const {
7391 AudioDeviceTypeAddrVector devices;
7392 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7393 for (const auto &device : devices) {
7394 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7395 return true;
7396 }
7397 }
7398 return false;
7399 }
7400
isHearingAidUsedForComm() const7401 bool AudioPolicyManager::isHearingAidUsedForComm() const {
7402 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7403 true /*fromCache*/);
7404 for (const auto &device : devices) {
7405 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7406 return true;
7407 }
7408 }
7409 return false;
7410 }
7411
7412
checkA2dpSuspend()7413 void AudioPolicyManager::checkA2dpSuspend()
7414 {
7415 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
7416 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
7417 mA2dpSuspended = false;
7418 return;
7419 }
7420
7421 bool isScoConnected =
7422 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7423 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
7424 bool isScoRequested = isScoRequestedForComm();
7425
7426 // if suspended, restore A2DP output if:
7427 // ((SCO device is NOT connected) ||
7428 // ((SCO is not requested) &&
7429 // (phone state is NOT in call) && (phone state is NOT ringing)))
7430 //
7431 // if not suspended, suspend A2DP output if:
7432 // (SCO device is connected) &&
7433 // ((SCO is requested) ||
7434 // ((phone state is in call) || (phone state is ringing)))
7435 //
7436 if (mA2dpSuspended) {
7437 if (!isScoConnected ||
7438 (!isScoRequested &&
7439 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
7440 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
7441
7442 mpClientInterface->restoreOutput(a2dpOutput);
7443 mA2dpSuspended = false;
7444 }
7445 } else {
7446 if (isScoConnected &&
7447 (isScoRequested ||
7448 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
7449 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
7450
7451 mpClientInterface->suspendOutput(a2dpOutput);
7452 mA2dpSuspended = true;
7453 }
7454 }
7455 }
7456
getNewOutputDevices(const sp<SwAudioOutputDescriptor> & outputDesc,bool fromCache)7457 DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7458 bool fromCache)
7459 {
7460 if (outputDesc == nullptr) {
7461 return DeviceVector{};
7462 }
7463
7464 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
7465 if (index >= 0) {
7466 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7467 if (patchDesc->getUid() != mUidCached) {
7468 ALOGV("%s device %s forced by patch %d", __func__,
7469 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7470 return outputDesc->devices();
7471 }
7472 }
7473
7474 // Do not retrieve engine device for outputs through MSD
7475 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7476 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7477 return outputDesc->devices();
7478 }
7479
7480 // Honor explicit routing requests only if no client using default routing is active on this
7481 // input: a specific app can not force routing for other apps by setting a preferred device.
7482 bool active; // unused
7483 sp<DeviceDescriptor> device =
7484 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
7485 if (device != nullptr) {
7486 return DeviceVector(device);
7487 }
7488
7489 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7490 // of setForceUse / Default Bus device here
7491 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7492 if (device != nullptr) {
7493 return DeviceVector(device);
7494 }
7495
7496 DeviceVector devices;
7497 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7498 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7499 auto hasStreamActive = [&](auto stream) {
7500 return hasStream(streams, stream) && isStreamActive(stream, 0);
7501 };
7502
7503 auto doGetOutputDevicesForVoice = [&]() {
7504 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
7505 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
7506 (isInCall() ||
7507 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7508 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
7509 };
7510
7511 // With low-latency playing on speaker, music on WFD, when the first low-latency
7512 // output is stopped, getNewOutputDevices checks for a product strategy
7513 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
7514 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
7515 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7516 // stream is associated to the output descriptor.
7517 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7518 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7519 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7520 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
7521 // Retrieval of devices for voice DL is done on primary output profile, cannot
7522 // check the route (would force modifying configuration file for this profile)
7523 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7524 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7525 break;
7526 }
7527 }
7528 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
7529 return devices;
7530 }
7531
getNewInputDevice(const sp<AudioInputDescriptor> & inputDesc)7532 sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7533 const sp<AudioInputDescriptor>& inputDesc)
7534 {
7535 sp<DeviceDescriptor> device;
7536
7537 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
7538 if (index >= 0) {
7539 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7540 if (patchDesc->getUid() != mUidCached) {
7541 ALOGV("getNewInputDevice() device %s forced by patch %d",
7542 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7543 return inputDesc->getDevice();
7544 }
7545 }
7546
7547 // Honor explicit routing requests only if no client using default routing is active on this
7548 // input: a specific app can not force routing for other apps by setting a preferred device.
7549 bool active;
7550 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7551 if (device != nullptr) {
7552 return device;
7553 }
7554
7555 // If we are not in call and no client is active on this input, this methods returns
7556 // a null sp<>, causing the patch on the input stream to be released.
7557 audio_attributes_t attributes;
7558 uid_t uid;
7559 audio_session_t session;
7560 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7561 if (topClient != nullptr) {
7562 attributes = topClient->attributes();
7563 uid = topClient->uid();
7564 session = topClient->session();
7565 } else {
7566 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7567 uid = 0;
7568 session = AUDIO_SESSION_NONE;
7569 }
7570
7571 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7572 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
7573 }
7574 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
7575 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
7576 }
7577
7578 return device;
7579 }
7580
streamsMatchForvolume(audio_stream_type_t stream1,audio_stream_type_t stream2)7581 bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7582 audio_stream_type_t stream2) {
7583 return (stream1 == stream2);
7584 }
7585
getDevicesForAttributes(const audio_attributes_t & attr,AudioDeviceTypeAddrVector * devices,bool forVolume)7586 status_t AudioPolicyManager::getDevicesForAttributes(
7587 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
7588 if (devices == nullptr) {
7589 return BAD_VALUE;
7590 }
7591
7592 DeviceVector curDevices;
7593 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7594 return status;
7595 }
7596 for (const auto& device : curDevices) {
7597 devices->push_back(device->getDeviceTypeAddr());
7598 }
7599 return NO_ERROR;
7600 }
7601
handleNotificationRoutingForStream(audio_stream_type_t stream)7602 void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
7603 switch(stream) {
7604 case AUDIO_STREAM_MUSIC:
7605 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
7606 updateDevicesAndOutputs();
7607 break;
7608 default:
7609 break;
7610 }
7611 }
7612
handleEventForBeacon(int event)7613 uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
7614
7615 // skip beacon mute management if a dedicated TTS output is available
7616 if (mTtsOutputAvailable) {
7617 return 0;
7618 }
7619
7620 switch(event) {
7621 case STARTING_OUTPUT:
7622 mBeaconMuteRefCount++;
7623 break;
7624 case STOPPING_OUTPUT:
7625 if (mBeaconMuteRefCount > 0) {
7626 mBeaconMuteRefCount--;
7627 }
7628 break;
7629 case STARTING_BEACON:
7630 mBeaconPlayingRefCount++;
7631 break;
7632 case STOPPING_BEACON:
7633 if (mBeaconPlayingRefCount > 0) {
7634 mBeaconPlayingRefCount--;
7635 }
7636 break;
7637 }
7638
7639 if (mBeaconMuteRefCount > 0) {
7640 // any playback causes beacon to be muted
7641 return setBeaconMute(true);
7642 } else {
7643 // no other playback: unmute when beacon starts playing, mute when it stops
7644 return setBeaconMute(mBeaconPlayingRefCount == 0);
7645 }
7646 }
7647
setBeaconMute(bool mute)7648 uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7649 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7650 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7651 // keep track of muted state to avoid repeating mute/unmute operations
7652 if (mBeaconMuted != mute) {
7653 // mute/unmute AUDIO_STREAM_TTS on all outputs
7654 ALOGV("\t muting %d", mute);
7655 uint32_t maxLatency = 0;
7656 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7657 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7658 ALOGV("\t no tts volume source available");
7659 return 0;
7660 }
7661 for (size_t i = 0; i < mOutputs.size(); i++) {
7662 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
7663 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
7664 const uint32_t latency = desc->latency() * 2;
7665 if (desc->isActive(latency * 2) && latency > maxLatency) {
7666 maxLatency = latency;
7667 }
7668 }
7669 mBeaconMuted = mute;
7670 return maxLatency;
7671 }
7672 return 0;
7673 }
7674
updateDevicesAndOutputs()7675 void AudioPolicyManager::updateDevicesAndOutputs()
7676 {
7677 mEngine->updateDeviceSelectionCache();
7678 mPreviousOutputs = mOutputs;
7679 }
7680
checkDeviceMuteStrategies(const sp<AudioOutputDescriptor> & outputDesc,const DeviceVector & prevDevices,uint32_t delayMs)7681 uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
7682 const DeviceVector &prevDevices,
7683 uint32_t delayMs)
7684 {
7685 // mute/unmute strategies using an incompatible device combination
7686 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7687 // if unmuting, unmute only after the specified delay
7688 if (outputDesc->isDuplicated()) {
7689 return 0;
7690 }
7691
7692 uint32_t muteWaitMs = 0;
7693 DeviceVector devices = outputDesc->devices();
7694 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
7695
7696 auto productStrategies = mEngine->getOrderedProductStrategies();
7697 for (const auto &productStrategy : productStrategies) {
7698 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7699 DeviceVector curDevices =
7700 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7701 curDevices = curDevices.filter(outputDesc->supportedDevices());
7702 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
7703 bool doMute = false;
7704
7705 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
7706 doMute = true;
7707 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7708 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
7709 doMute = true;
7710 outputDesc->setStrategyMutedByDevice(productStrategy, false);
7711 }
7712 if (doMute) {
7713 for (size_t j = 0; j < mOutputs.size(); j++) {
7714 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
7715 // skip output if it does not share any device with current output
7716 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
7717 continue;
7718 }
7719 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
7720 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7721 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7722 if (desc->isStrategyActive(productStrategy)) {
7723 if (mute) {
7724 // FIXME: should not need to double latency if volume could be applied
7725 // immediately by the audioflinger mixer. We must account for the delay
7726 // between now and the next time the audioflinger thread for this output
7727 // will process a buffer (which corresponds to one buffer size,
7728 // usually 1/2 or 1/4 of the latency).
7729 if (muteWaitMs < desc->latency() * 2) {
7730 muteWaitMs = desc->latency() * 2;
7731 }
7732 }
7733 }
7734 }
7735 }
7736 }
7737
7738 // temporary mute output if device selection changes to avoid volume bursts due to
7739 // different per device volumes
7740 if (outputDesc->isActive() && (devices != prevDevices)) {
7741 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
7742
7743 if (muteWaitMs < tempMuteWaitMs) {
7744 muteWaitMs = tempMuteWaitMs;
7745 }
7746
7747 // If recommended duration is defined, replace temporary mute duration to avoid
7748 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7749 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7750 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7751 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7752 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7753
7754 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7755 // make sure that we do not start the temporary mute period too early in case of
7756 // delayed device change
7757 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7758 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
7759 devices.types());
7760 }
7761 }
7762
7763 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7764 if (muteWaitMs > delayMs) {
7765 muteWaitMs -= delayMs;
7766 usleep(muteWaitMs * 1000);
7767 return muteWaitMs;
7768 }
7769 return 0;
7770 }
7771
setOutputDevices(const char * caller,const sp<SwAudioOutputDescriptor> & outputDesc,const DeviceVector & devices,bool force,int delayMs,audio_patch_handle_t * patchHandle,bool requiresMuteCheck,bool requiresVolumeCheck,bool skipMuteDelay)7772 uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7773 const sp<SwAudioOutputDescriptor>& outputDesc,
7774 const DeviceVector &devices,
7775 bool force,
7776 int delayMs,
7777 audio_patch_handle_t *patchHandle,
7778 bool requiresMuteCheck, bool requiresVolumeCheck,
7779 bool skipMuteDelay)
7780 {
7781 // TODO(b/262404095): Consider if the output need to be reopened.
7782 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7783 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7784 devices.toString().c_str(), delayMs);
7785 uint32_t muteWaitMs;
7786
7787 if (outputDesc->isDuplicated()) {
7788 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
7789 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
7790 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
7791 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
7792 return muteWaitMs;
7793 }
7794
7795 // filter devices according to output selected
7796 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
7797 DeviceVector prevDevices = outputDesc->devices();
7798 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
7799
7800 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7801 prevDevices.toString().c_str());
7802
7803 if (!filteredDevices.isEmpty()) {
7804 outputDesc->setDevices(filteredDevices);
7805 }
7806
7807 // if the outputs are not materially active, there is no need to mute.
7808 if (requiresMuteCheck) {
7809 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
7810 } else {
7811 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7812 logPrefix.c_str());
7813 muteWaitMs = 0;
7814 }
7815
7816 bool outputRouted = outputDesc->isRouted();
7817
7818 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7819 // output profile or if new device is not supported AND previous device(s) is(are) still
7820 // available (otherwise reset device must be done on the output)
7821 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
7822 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7823 devices.toString().c_str());
7824 // restore previous device after evaluating strategy mute state
7825 outputDesc->setDevices(prevDevices);
7826 return muteWaitMs;
7827 }
7828
7829 // Do not change the routing if:
7830 // the requested device is AUDIO_DEVICE_NONE
7831 // OR the requested device is the same as current device
7832 // AND force is not specified
7833 // AND the output is connected by a valid audio patch.
7834 // Doing this check here allows the caller to call setOutputDevices() without conditions
7835 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
7836 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7837 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7838 outputDesc->getPatchHandle());
7839 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7840 ALOGV("%s %s setting same device on routed output, force apply volumes",
7841 __func__, logPrefix.c_str());
7842 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7843 }
7844 return muteWaitMs;
7845 }
7846
7847 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7848 filteredDevices.toString().c_str());
7849
7850 // do the routing
7851 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
7852 resetOutputDevice(outputDesc, delayMs, NULL);
7853 } else {
7854 PatchBuilder patchBuilder;
7855 patchBuilder.addSource(outputDesc);
7856 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7857 for (const auto &filteredDevice : filteredDevices) {
7858 patchBuilder.addSink(filteredDevice);
7859 }
7860
7861 // Add half reported latency to delayMs when muteWaitMs is null in order
7862 // to avoid disordered sequence of muting volume and changing devices.
7863 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7864 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7865 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
7866 }
7867
7868 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7869 if (!skipMuteDelay) {
7870 // update stream volumes according to new device
7871 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7872 }
7873
7874 return muteWaitMs;
7875 }
7876
resetOutputDevice(const sp<AudioOutputDescriptor> & outputDesc,int delayMs,audio_patch_handle_t * patchHandle)7877 status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
7878 int delayMs,
7879 audio_patch_handle_t *patchHandle)
7880 {
7881 ssize_t index;
7882 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7883 return INVALID_OPERATION;
7884 }
7885 if (patchHandle) {
7886 index = mAudioPatches.indexOfKey(*patchHandle);
7887 } else {
7888 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
7889 }
7890 if (index < 0) {
7891 return INVALID_OPERATION;
7892 }
7893 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7894 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
7895 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
7896 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
7897 removeAudioPatch(patchDesc->getHandle());
7898 nextAudioPortGeneration();
7899 mpClientInterface->onAudioPatchListUpdate();
7900 return status;
7901 }
7902
setInputDevice(audio_io_handle_t input,const sp<DeviceDescriptor> & device,bool force,audio_patch_handle_t * patchHandle)7903 status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
7904 const sp<DeviceDescriptor> &device,
7905 bool force,
7906 audio_patch_handle_t *patchHandle)
7907 {
7908 status_t status = NO_ERROR;
7909
7910 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7911 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7912 inputDesc->setDevice(device);
7913
7914 if (mAvailableInputDevices.contains(device)) {
7915 PatchBuilder patchBuilder;
7916 patchBuilder.addSink(inputDesc,
7917 // AUDIO_SOURCE_HOTWORD is for internal use only:
7918 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
7919 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7920 auto result = usecase;
7921 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7922 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7923 }
7924 return result; }).
7925 //only one input device for now
7926 addSource(device);
7927 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
7928 }
7929 }
7930 return status;
7931 }
7932
resetInputDevice(audio_io_handle_t input,audio_patch_handle_t * patchHandle)7933 status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7934 audio_patch_handle_t *patchHandle)
7935 {
7936 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7937 ssize_t index;
7938 if (patchHandle) {
7939 index = mAudioPatches.indexOfKey(*patchHandle);
7940 } else {
7941 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
7942 }
7943 if (index < 0) {
7944 return INVALID_OPERATION;
7945 }
7946 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7947 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
7948 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
7949 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
7950 removeAudioPatch(patchDesc->getHandle());
7951 nextAudioPortGeneration();
7952 mpClientInterface->onAudioPatchListUpdate();
7953 return status;
7954 }
7955
getInputProfile(const sp<DeviceDescriptor> & device,uint32_t & samplingRate,audio_format_t & format,audio_channel_mask_t & channelMask,audio_input_flags_t flags)7956 sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
7957 uint32_t& samplingRate,
7958 audio_format_t& format,
7959 audio_channel_mask_t& channelMask,
7960 audio_input_flags_t flags)
7961 {
7962 // Choose an input profile based on the requested capture parameters: select the first available
7963 // profile supporting all requested parameters.
7964 // The flags can be ignored if it doesn't contain a much match flag.
7965
7966 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7967 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7968 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7969
7970 const underlying_input_flag_t oriFlags = flags;
7971
7972 for (;;) {
7973 sp<IOProfile> firstInexact = nullptr;
7974 uint32_t updatedSamplingRate = 0;
7975 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7976 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7977 for (const auto& hwModule : mHwModules) {
7978 for (const auto& profile : hwModule->getInputProfiles()) {
7979 // profile->log();
7980 //updatedFormat = format;
7981 if (profile->getCompatibilityScore(
7982 DeviceVector(device),
7983 samplingRate,
7984 &updatedSamplingRate,
7985 format,
7986 &updatedFormat,
7987 channelMask,
7988 &updatedChannelMask,
7989 // FIXME ugly cast
7990 (audio_output_flags_t) flags,
7991 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7992 samplingRate = updatedSamplingRate;
7993 format = updatedFormat;
7994 channelMask = updatedChannelMask;
7995 return profile;
7996 }
7997 if (firstInexact == nullptr
7998 && profile->getCompatibilityScore(
7999 DeviceVector(device),
8000 samplingRate,
8001 &updatedSamplingRate,
8002 format,
8003 &updatedFormat,
8004 channelMask,
8005 &updatedChannelMask,
8006 // FIXME ugly cast
8007 (audio_output_flags_t) flags,
8008 false /*exactMatchRequiredForInputFlags*/)
8009 != IOProfile::NO_MATCH) {
8010 firstInexact = profile;
8011 }
8012 }
8013 }
8014
8015 if (firstInexact != nullptr) {
8016 samplingRate = updatedSamplingRate;
8017 format = updatedFormat;
8018 channelMask = updatedChannelMask;
8019 return firstInexact;
8020 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8021 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8022 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8023 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8024 flags = AUDIO_INPUT_FLAG_NONE;
8025 } else { // fail
8026 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8027 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8028 samplingRate, format, channelMask, oriFlags);
8029 break;
8030 }
8031 }
8032
8033 return nullptr;
8034 }
8035
adjustDeviceAttenuationForAbsVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const DeviceTypeSet & deviceTypes)8036 float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8037 VolumeSource volumeSource,
8038 int index,
8039 const DeviceTypeSet &deviceTypes)
8040 {
8041 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8042 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8043 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8044
8045 if (com_android_media_audio_abs_volume_index_fix()) {
8046 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8047 mAbsoluteVolumeDrivingStreams.end()) {
8048 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8049 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8050 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8051 ALOGD("%s: no group matching with %s", __FUNCTION__,
8052 toString(attributesToDriveAbs).c_str());
8053 return volumeDb;
8054 }
8055
8056 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8057 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8058 if (vsToDriveAbs == volumeSource) {
8059 // attenuation is applied by the abs volume controller
8060 return volumeDbMax;
8061 } else {
8062 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8063 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8064 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8065 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8066 curvesAbs.getVolumeIndexMax());
8067 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8068 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8069 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8070 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8071 return newVolumeDb;
8072 }
8073 }
8074 return volumeDb;
8075 } else {
8076 return volumeDb;
8077 }
8078 }
8079
computeVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const DeviceTypeSet & deviceTypes,bool computeInternalInteraction)8080 float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8081 VolumeSource volumeSource,
8082 int index,
8083 const DeviceTypeSet& deviceTypes,
8084 bool computeInternalInteraction)
8085 {
8086 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8087 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8088 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8089
8090 if (!computeInternalInteraction) {
8091 return volumeDb;
8092 }
8093
8094 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8095 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8096 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8097 // the ringtone volume
8098 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8099 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8100 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8101 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8102 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
8103 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
8104 mOutputs.isActive(ringVolumeSrc, 0)) {
8105 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
8106 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8107 /* computeInternalInteraction= */ false);
8108 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
8109 }
8110
8111 // in-call: always cap volume by voice volume + some low headroom
8112 if ((volumeSource != callVolumeSrc && (isInCall() ||
8113 mOutputs.isActiveLocally(callVolumeSrc))) &&
8114 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
8115 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8116 volumeSource == alarmVolumeSrc ||
8117 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8118 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8119 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
8120 volumeSource == a11yVolumeSrc)) {
8121 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
8122 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
8123 const float maxVoiceVolDb =
8124 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8125 /* computeInternalInteraction= */ false)
8126 + IN_CALL_EARPIECE_HEADROOM_DB;
8127 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8128 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8129 // programmatically muted.
8130 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8131 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8132 // stream. See setVolumeCurveIndex() for more information.
8133 bool exemptFromCapping =
8134 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8135 && (voiceVolumeIndex == 0);
8136 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8137 volumeSource, volumeDb);
8138 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
8139 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8140 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8141 volumeDb = maxVoiceVolDb;
8142 }
8143 }
8144 // if a headset is connected, apply the following rules to ring tones and notifications
8145 // to avoid sound level bursts in user's ears:
8146 // - always attenuate notifications volume by 6dB
8147 // - attenuate ring tones volume by 6dB unless music is not playing and
8148 // speaker is part of the select devices
8149 // - if music is playing, always limit the volume to current music volume,
8150 // with a minimum threshold at -36dB so that notification is always perceived.
8151 if (!Intersection(deviceTypes,
8152 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8153 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
8154 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8155 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
8156 ((volumeSource == alarmVolumeSrc ||
8157 volumeSource == ringVolumeSrc) ||
8158 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8159 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8160 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
8161 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8162 curves.canBeMuted()) {
8163
8164 // when the phone is ringing we must consider that music could have been paused just before
8165 // by the music application and behave as if music was active if the last music track was
8166 // just stopped
8167 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8168 || mLimitRingtoneVolume) {
8169 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
8170 DeviceTypeSet musicDevice =
8171 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8172 nullptr, true /*fromCache*/).types();
8173 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
8174 float musicVolDb = computeVolume(musicCurves,
8175 musicVolumeSrc,
8176 musicCurves.getVolumeIndex(musicDevice),
8177 musicDevice,
8178 /* computeInternalInteraction= */ false);
8179 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8180 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8181 if (volumeDb > minVolDb) {
8182 volumeDb = minVolDb;
8183 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
8184 }
8185 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8186 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8187 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8188 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8189 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8190 // when intended to be played.
8191 if ((volumeDb > -96.0f) &&
8192 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
8193 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8194 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
8195 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8196 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
8197 }
8198 }
8199 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
8200 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
8201 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
8202 }
8203 }
8204
8205 return volumeDb;
8206 }
8207
rescaleVolumeIndex(int srcIndex,VolumeSource fromVolumeSource,VolumeSource toVolumeSource)8208 int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
8209 VolumeSource fromVolumeSource,
8210 VolumeSource toVolumeSource)
8211 {
8212 if (fromVolumeSource == toVolumeSource) {
8213 return srcIndex;
8214 }
8215 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8216 auto &dstCurves = getVolumeCurves(toVolumeSource);
8217 float minSrc = (float)srcCurves.getVolumeIndexMin();
8218 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8219 float minDst = (float)dstCurves.getVolumeIndexMin();
8220 float maxDst = (float)dstCurves.getVolumeIndexMax();
8221
8222 // preserve mute request or correct range
8223 if (srcIndex < minSrc) {
8224 if (srcIndex == 0) {
8225 return 0;
8226 }
8227 srcIndex = minSrc;
8228 } else if (srcIndex > maxSrc) {
8229 srcIndex = maxSrc;
8230 }
8231 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8232 }
8233
checkAndSetVolume(IVolumeCurves & curves,VolumeSource volumeSource,int index,const sp<AudioOutputDescriptor> & outputDesc,DeviceTypeSet deviceTypes,int delayMs,bool force)8234 status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8235 VolumeSource volumeSource,
8236 int index,
8237 const sp<AudioOutputDescriptor>& outputDesc,
8238 DeviceTypeSet deviceTypes,
8239 int delayMs,
8240 bool force)
8241 {
8242 // do not change actual attributes volume if the attributes is muted
8243 if (outputDesc->isMuted(volumeSource)) {
8244 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8245 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
8246 return NO_ERROR;
8247 }
8248
8249 bool isVoiceVolSrc;
8250 bool isBtScoVolSrc;
8251 if (!isVolumeConsistentForCalls(
8252 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
8253 // Do not return an error here as AudioService will always set both voice call
8254 // and Bluetooth SCO volumes due to stream aliasing.
8255 return NO_ERROR;
8256 }
8257
8258 if (deviceTypes.empty()) {
8259 deviceTypes = outputDesc->devices().types();
8260 index = curves.getVolumeIndex(deviceTypes);
8261 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
8262 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
8263 }
8264
8265 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8266 ALOGE("invalid volume index range");
8267 return BAD_VALUE;
8268 }
8269
8270 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8271 if (outputDesc->isFixedVolume(deviceTypes) ||
8272 // Force VoIP volume to max for bluetooth SCO device except if muted
8273 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
8274 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
8275 volumeDb = 0.0f;
8276 }
8277 const bool muted = (index == 0) && (volumeDb != 0.0f);
8278 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8279 deviceTypes, delayMs, force, isVoiceVolSrc);
8280
8281 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
8282 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
8283 }
8284 return NO_ERROR;
8285 }
8286
setVoiceVolume(int index,IVolumeCurves & curves,bool isVoiceVolSrc,int delayMs)8287 void AudioPolicyManager::setVoiceVolume(
8288 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8289 float voiceVolume;
8290 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8291 // by the headset
8292 if (isVoiceVolSrc) {
8293 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8294 } else {
8295 voiceVolume = index == 0 ? 0.0 : 1.0;
8296 }
8297 if (voiceVolume != mLastVoiceVolume) {
8298 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8299 mLastVoiceVolume = voiceVolume;
8300 }
8301 }
8302
isVolumeConsistentForCalls(VolumeSource volumeSource,const DeviceTypeSet & deviceTypes,bool & isVoiceVolSrc,bool & isBtScoVolSrc,const char * caller)8303 bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8304 const DeviceTypeSet& deviceTypes,
8305 bool& isVoiceVolSrc,
8306 bool& isBtScoVolSrc,
8307 const char* caller) {
8308 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8309 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8310 const bool isScoRequested = isScoRequestedForComm();
8311 const bool isHAUsed = isHearingAidUsedForComm();
8312
8313 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8314 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8315
8316 if ((callVolSrc != btScoVolSrc) &&
8317 ((isVoiceVolSrc && isScoRequested) ||
8318 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8319 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8320 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8321 volumeSource, isScoRequested ? " " : " not ");
8322 return false;
8323 }
8324 return true;
8325 }
8326
applyStreamVolumes(const sp<AudioOutputDescriptor> & outputDesc,const DeviceTypeSet & deviceTypes,int delayMs,bool force)8327 void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
8328 const DeviceTypeSet& deviceTypes,
8329 int delayMs,
8330 bool force)
8331 {
8332 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
8333 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8334 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8335 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
8336 curves.getVolumeIndex(deviceTypes),
8337 outputDesc, deviceTypes, delayMs, force);
8338 }
8339 }
8340
setStrategyMute(product_strategy_t strategy,bool on,const sp<AudioOutputDescriptor> & outputDesc,int delayMs,DeviceTypeSet deviceTypes)8341 void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8342 bool on,
8343 const sp<AudioOutputDescriptor>& outputDesc,
8344 int delayMs,
8345 DeviceTypeSet deviceTypes)
8346 {
8347 std::vector<VolumeSource> sourcesToMute;
8348 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8349 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8350 toString(attributes).c_str(), on, outputDesc->getId());
8351 VolumeSource source = toVolumeSource(attributes, false);
8352 if ((source != VOLUME_SOURCE_NONE) &&
8353 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8354 == end(sourcesToMute))) {
8355 sourcesToMute.push_back(source);
8356 }
8357 }
8358 for (auto source : sourcesToMute) {
8359 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
8360 }
8361
8362 }
8363
setVolumeSourceMute(VolumeSource volumeSource,bool on,const sp<AudioOutputDescriptor> & outputDesc,int delayMs,DeviceTypeSet deviceTypes)8364 void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8365 bool on,
8366 const sp<AudioOutputDescriptor>& outputDesc,
8367 int delayMs,
8368 DeviceTypeSet deviceTypes)
8369 {
8370 if (deviceTypes.empty()) {
8371 deviceTypes = outputDesc->devices().types();
8372 }
8373 auto &curves = getVolumeCurves(volumeSource);
8374 if (on) {
8375 if (!outputDesc->isMuted(volumeSource)) {
8376 if (curves.canBeMuted() &&
8377 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8378 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8379 AUDIO_POLICY_FORCE_NONE))) {
8380 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
8381 }
8382 }
8383 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8384 // ignored
8385 outputDesc->incMuteCount(volumeSource);
8386 } else {
8387 if (!outputDesc->isMuted(volumeSource)) {
8388 ALOGV("%s unmuting non muted attributes!", __func__);
8389 return;
8390 }
8391 if (outputDesc->decMuteCount(volumeSource) == 0) {
8392 checkAndSetVolume(curves, volumeSource,
8393 curves.getVolumeIndex(deviceTypes),
8394 outputDesc,
8395 deviceTypes,
8396 delayMs);
8397 }
8398 }
8399 }
8400
isValidAttributes(const audio_attributes_t * paa)8401 bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8402 {
8403 // has flags that map to a stream type?
8404 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8405 return true;
8406 }
8407
8408 // has known usage?
8409 switch (paa->usage) {
8410 case AUDIO_USAGE_UNKNOWN:
8411 case AUDIO_USAGE_MEDIA:
8412 case AUDIO_USAGE_VOICE_COMMUNICATION:
8413 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8414 case AUDIO_USAGE_ALARM:
8415 case AUDIO_USAGE_NOTIFICATION:
8416 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8417 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8418 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8419 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8420 case AUDIO_USAGE_NOTIFICATION_EVENT:
8421 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8422 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8423 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8424 case AUDIO_USAGE_GAME:
8425 case AUDIO_USAGE_VIRTUAL_SOURCE:
8426 case AUDIO_USAGE_ASSISTANT:
8427 case AUDIO_USAGE_CALL_ASSISTANT:
8428 case AUDIO_USAGE_EMERGENCY:
8429 case AUDIO_USAGE_SAFETY:
8430 case AUDIO_USAGE_VEHICLE_STATUS:
8431 case AUDIO_USAGE_ANNOUNCEMENT:
8432 break;
8433 default:
8434 return false;
8435 }
8436 return true;
8437 }
8438
getForceUse(audio_policy_force_use_t usage)8439 audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8440 {
8441 return mEngine->getForceUse(usage);
8442 }
8443
isInCall() const8444 bool AudioPolicyManager::isInCall() const {
8445 return isStateInCall(mEngine->getPhoneState());
8446 }
8447
isStateInCall(int state) const8448 bool AudioPolicyManager::isStateInCall(int state) const {
8449 return is_state_in_call(state);
8450 }
8451
isCallAudioAccessible() const8452 bool AudioPolicyManager::isCallAudioAccessible() const {
8453 audio_mode_t mode = mEngine->getPhoneState();
8454 return (mode == AUDIO_MODE_IN_CALL)
8455 || (mode == AUDIO_MODE_CALL_SCREEN)
8456 || (mode == AUDIO_MODE_CALL_REDIRECT);
8457 }
8458
isInCallOrScreening() const8459 bool AudioPolicyManager::isInCallOrScreening() const {
8460 audio_mode_t mode = mEngine->getPhoneState();
8461 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8462 }
8463
cleanUpForDevice(const sp<DeviceDescriptor> & deviceDesc)8464 void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8465 {
8466 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
8467 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
8468 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
8469 sourceDesc->sinkDevice()->equals(deviceDesc))
8470 && !sourceDesc->isCallRx()) {
8471 disconnectAudioSource(sourceDesc);
8472 }
8473 }
8474
8475 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8476 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8477 bool release = false;
8478 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8479 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8480 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8481 source->ext.device.type == deviceDesc->type()) {
8482 release = true;
8483 }
8484 }
8485 const char *address = deviceDesc->address().c_str();
8486 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8487 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8488 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
8489 sink->ext.device.type == deviceDesc->type() &&
8490 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8491 || strncmp(sink->ext.device.address, address,
8492 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
8493 release = true;
8494 }
8495 }
8496 if (release) {
8497 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8498 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
8499 }
8500 }
8501
8502 mInputs.clearSessionRoutesForDevice(deviceDesc);
8503
8504 mHwModules.cleanUpForDevice(deviceDesc);
8505 }
8506
modifySurroundFormats(const sp<DeviceDescriptor> & devDesc,FormatVector * formatsPtr)8507 void AudioPolicyManager::modifySurroundFormats(
8508 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
8509 std::unordered_set<audio_format_t> enforcedSurround(
8510 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
8511 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
8512 for (const auto& pair : mConfig->getSurroundFormats()) {
8513 allSurround.insert(pair.first);
8514 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8515 }
8516
8517 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8518 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8519 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
8520 // This is the resulting set of formats depending on the surround mode:
8521 // 'all surround' = allSurround
8522 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8523 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8524 // 'manual surround' = mManualSurroundFormats
8525 // AUTO: formats v 'enforced surround'
8526 // ALWAYS: formats v 'all surround' v 'enforced surround'
8527 // NEVER: formats ^ 'non-surround'
8528 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
8529
8530 std::unordered_set<audio_format_t> formatSet;
8531 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8532 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
8533 // formatSet is (formats ^ 'non-surround')
8534 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
8535 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
8536 formatSet.insert(*formatIter);
8537 }
8538 }
8539 } else {
8540 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8541 }
8542 formatsPtr->clear(); // Re-filled from the formatSet at the end.
8543
8544 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
8545 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
8546 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8547 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8548 formatSet.insert(AUDIO_FORMAT_IEC61937);
8549 }
8550 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8551 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8552 formatSet.insert(allSurround.begin(), allSurround.end());
8553 }
8554 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
8555 }
8556 for (const auto& format : formatSet) {
8557 formatsPtr->push_back(format);
8558 }
8559 }
8560
modifySurroundChannelMasks(ChannelMaskSet * channelMasksPtr)8561 void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8562 ChannelMaskSet &channelMasks = *channelMasksPtr;
8563 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8564 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8565
8566 // If NEVER, then remove support for channelMasks > stereo.
8567 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
8568 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8569 audio_channel_mask_t channelMask = *it;
8570 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
8571 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
8572 it = channelMasks.erase(it);
8573 } else {
8574 ++it;
8575 }
8576 }
8577 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8578 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8579 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
8580 bool supports5dot1 = false;
8581 // Are there any channel masks that can be considered "surround"?
8582 for (audio_channel_mask_t channelMask : channelMasks) {
8583 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8584 supports5dot1 = true;
8585 break;
8586 }
8587 }
8588 // If not then add 5.1 support.
8589 if (!supports5dot1) {
8590 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
8591 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
8592 }
8593 }
8594 }
8595
updateAudioProfiles(const sp<DeviceDescriptor> & devDesc,audio_io_handle_t ioHandle,const sp<IOProfile> & profile)8596 void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
8597 audio_io_handle_t ioHandle,
8598 const sp<IOProfile>& profile) {
8599 if (!profile->hasDynamicAudioProfile()) {
8600 return;
8601 }
8602
8603 audio_port_v7 devicePort;
8604 devDesc->toAudioPort(&devicePort);
8605
8606 audio_port_v7 mixPort;
8607 profile->toAudioPort(&mixPort);
8608 mixPort.ext.mix.handle = ioHandle;
8609
8610 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8611 if (status != NO_ERROR) {
8612 ALOGE("%s failed to query the attributes of the mix port", __func__);
8613 return;
8614 }
8615
8616 std::set<audio_format_t> supportedFormats;
8617 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8618 supportedFormats.insert(mixPort.audio_profiles[i].format);
8619 }
8620 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8621 mReportedFormatsMap[devDesc] = formats;
8622
8623 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8624 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8625 modifySurroundFormats(devDesc, &formats);
8626 size_t modifiedNumProfiles = 0;
8627 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8628 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8629 formats.end()) {
8630 // Skip the format that is not present after modifying surround formats.
8631 continue;
8632 }
8633 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8634 sizeof(struct audio_profile));
8635 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8636 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8637 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8638 modifySurroundChannelMasks(&channels);
8639 std::copy(channels.begin(), channels.end(),
8640 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8641 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8642 }
8643 mixPort.num_audio_profiles = modifiedNumProfiles;
8644 }
8645 profile->importAudioPort(mixPort);
8646 }
8647
installPatch(const char * caller,audio_patch_handle_t * patchHandle,AudioIODescriptorInterface * ioDescriptor,const struct audio_patch * patch,int delayMs)8648 status_t AudioPolicyManager::installPatch(const char *caller,
8649 audio_patch_handle_t *patchHandle,
8650 AudioIODescriptorInterface *ioDescriptor,
8651 const struct audio_patch *patch,
8652 int delayMs)
8653 {
8654 ssize_t index = mAudioPatches.indexOfKey(
8655 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8656 *patchHandle : ioDescriptor->getPatchHandle());
8657 sp<AudioPatch> patchDesc;
8658 status_t status = installPatch(
8659 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8660 if (status == NO_ERROR) {
8661 ioDescriptor->setPatchHandle(patchDesc->getHandle());
8662 }
8663 return status;
8664 }
8665
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)8666 status_t AudioPolicyManager::installPatch(const char *caller,
8667 ssize_t index,
8668 audio_patch_handle_t *patchHandle,
8669 const struct audio_patch *patch,
8670 int delayMs,
8671 uid_t uid,
8672 sp<AudioPatch> *patchDescPtr)
8673 {
8674 sp<AudioPatch> patchDesc;
8675 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8676 if (index >= 0) {
8677 patchDesc = mAudioPatches.valueAt(index);
8678 afPatchHandle = patchDesc->getAfHandle();
8679 }
8680
8681 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8682 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8683 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8684 if (status == NO_ERROR) {
8685 if (index < 0) {
8686 patchDesc = new AudioPatch(patch, uid);
8687 addAudioPatch(patchDesc->getHandle(), patchDesc);
8688 } else {
8689 patchDesc->mPatch = *patch;
8690 }
8691 patchDesc->setAfHandle(afPatchHandle);
8692 if (patchHandle) {
8693 *patchHandle = patchDesc->getHandle();
8694 }
8695 nextAudioPortGeneration();
8696 mpClientInterface->onAudioPatchListUpdate();
8697 }
8698 if (patchDescPtr) *patchDescPtr = patchDesc;
8699 return status;
8700 }
8701
areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor> & output)8702 bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8703 {
8704 const TrackClientVector activeClients = output->getActiveClients();
8705 if (activeClients.empty()) {
8706 return true;
8707 }
8708 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8709 if (index < 0) {
8710 ALOGE("%s, no audio patch found while there are active clients on output %d",
8711 __func__, output->getId());
8712 return false;
8713 }
8714 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8715 DeviceVector routedDevices;
8716 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8717 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8718 patchDesc->mPatch.sinks[i].id);
8719 if (device == nullptr) {
8720 ALOGE("%s, no audio device found with id(%d)",
8721 __func__, patchDesc->mPatch.sinks[i].id);
8722 return false;
8723 }
8724 routedDevices.add(device);
8725 }
8726 for (const auto& client : activeClients) {
8727 if (client->isInvalid()) {
8728 // No need to take care about invalidated clients.
8729 continue;
8730 }
8731 sp<DeviceDescriptor> preferredDevice =
8732 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8733 if (mEngine->getOutputDevicesForAttributes(
8734 client->attributes(), preferredDevice, false) == routedDevices) {
8735 return false;
8736 }
8737 }
8738 return true;
8739 }
8740
openOutputWithProfileAndDevice(const sp<IOProfile> & profile,const DeviceVector & devices,const audio_config_base_t * mixerConfig,const audio_config_t * halConfig,audio_output_flags_t flags)8741 sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
8742 const sp<IOProfile>& profile, const DeviceVector& devices,
8743 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8744 audio_output_flags_t flags)
8745 {
8746 for (const auto& device : devices) {
8747 // TODO: This should be checking if the profile supports the device combo.
8748 if (!profile->supportsDevice(device)) {
8749 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8750 device->type());
8751 return nullptr;
8752 }
8753 }
8754 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8755 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
8756 status_t status = desc->open(halConfig, mixerConfig, devices,
8757 AUDIO_STREAM_DEFAULT, flags, &output);
8758 if (status != NO_ERROR) {
8759 ALOGE("%s failed to open output %d", __func__, status);
8760 return nullptr;
8761 }
8762 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8763 auto portConfig = desc->getConfig();
8764 for (const auto& device : devices) {
8765 device->setPreferredConfig(&portConfig);
8766 }
8767 }
8768
8769 // Here is where the out_set_parameters() for card & device gets called
8770 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8771 const audio_devices_t deviceType = device->type();
8772 const String8 &address = String8(device->address().c_str());
8773 if (!address.empty()) {
8774 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8775 mpClientInterface->setParameters(output, String8(param));
8776 free(param);
8777 }
8778 updateAudioProfiles(device, output, profile);
8779 if (!profile->hasValidAudioProfile()) {
8780 ALOGW("%s() missing param", __func__);
8781 desc->close();
8782 return nullptr;
8783 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8784 // Reopen the output with the best audio profile picked by APM when the profile supports
8785 // dynamic audio profile and the hal config is not specified.
8786 desc->close();
8787 output = AUDIO_IO_HANDLE_NONE;
8788 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8789 profile->pickAudioProfile(
8790 config.sample_rate, config.channel_mask, config.format);
8791 config.offload_info.sample_rate = config.sample_rate;
8792 config.offload_info.channel_mask = config.channel_mask;
8793 config.offload_info.format = config.format;
8794
8795 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
8796 if (status != NO_ERROR) {
8797 return nullptr;
8798 }
8799 }
8800
8801 addOutput(output, desc);
8802 setOutputDevices(__func__, desc,
8803 devices,
8804 true,
8805 0,
8806 NULL);
8807 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8808 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8809
8810 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8811 sp<AudioPolicyMix> policyMix;
8812 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8813 policyMix->setOutput(desc);
8814 desc->mPolicyMix = policyMix;
8815 } else {
8816 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8817 address.c_str());
8818 }
8819
8820 } else if (hasPrimaryOutput() && speaker != nullptr
8821 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
8822 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8823 // no duplicated output for:
8824 // - direct outputs
8825 // - outputs used by dynamic policy mixes
8826 // - outputs that supports SPEAKER while the primary output does not.
8827 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8828
8829 //TODO: configure audio effect output stage here
8830
8831 // open a duplicating output thread for the new output and the primary output
8832 sp<SwAudioOutputDescriptor> dupOutputDesc =
8833 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8834 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8835 if (status == NO_ERROR) {
8836 // add duplicated output descriptor
8837 addOutput(duplicatedOutput, dupOutputDesc);
8838 } else {
8839 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8840 mPrimaryOutput->mIoHandle, output);
8841 desc->close();
8842 removeOutput(output);
8843 nextAudioPortGeneration();
8844 return nullptr;
8845 }
8846 }
8847 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8848 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8849 mPrimaryOutput = desc;
8850 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
8851 }
8852 return desc;
8853 }
8854
getDevicesForAttributes(const audio_attributes_t & attr,DeviceVector & devices,bool forVolume)8855 status_t AudioPolicyManager::getDevicesForAttributes(
8856 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8857 // Devices are determined in the following precedence:
8858 //
8859 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8860 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8861 //
8862 // If no such dynamic policy then
8863 // 2) Devices containing an active client using setPreferredDevice
8864 // with same strategy as the attributes.
8865 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8866 //
8867 // If no corresponding active client with setPreferredDevice then
8868 // 3) Devices associated with the strategy determined by the attributes
8869 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8870 //
8871 // See related getOutputForAttrInt().
8872
8873 // check dynamic policies but only for primary descriptors (secondary not used for audible
8874 // audio routing, only used for duplication for playback capture)
8875 sp<AudioPolicyMix> policyMix;
8876 bool unneededUsePrimaryOutputFromPolicyMixes = false;
8877 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
8878 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8879 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8880 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
8881 if (status != OK) {
8882 return status;
8883 }
8884
8885 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8886 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8887 // as they are unaffected by device/stream volume
8888 // (per SwAudioOutputDescriptor::isFixedVolume()).
8889 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8890 ) {
8891 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8892 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8893 devices.add(deviceDesc);
8894 } else {
8895 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8896 // which selects setPreferredDevice if active. This means forVolume call
8897 // will take an active setPreferredDevice, if such exists.
8898
8899 devices = mEngine->getOutputDevicesForAttributes(
8900 attr, nullptr /* preferredDevice */, false /* fromCache */);
8901 }
8902
8903 if (forVolume) {
8904 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8905 // for single volume control in AudioService (such relationship should exist if
8906 // SPEAKER_SAFE is present).
8907 //
8908 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8909 DeviceVector speakerSafeDevices =
8910 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8911 if (!speakerSafeDevices.isEmpty()) {
8912 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8913 devices.remove(speakerSafeDevices);
8914 }
8915 }
8916
8917 return NO_ERROR;
8918 }
8919
getProfilesForDevices(const DeviceVector & devices,AudioProfileVector & audioProfiles,uint32_t flags,bool isInput)8920 status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8921 AudioProfileVector& audioProfiles,
8922 uint32_t flags,
8923 bool isInput) {
8924 for (const auto& hwModule : mHwModules) {
8925 // the MSD module checks for different conditions
8926 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8927 continue;
8928 }
8929 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8930 : hwModule->getOutputProfiles();
8931 for (const auto& profile : ioProfiles) {
8932 if (!profile->areAllDevicesSupported(devices) ||
8933 !profile->isCompatibleProfileForFlags(
8934 flags, false /*exactMatchRequiredForInputFlags*/)) {
8935 continue;
8936 }
8937 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8938 }
8939 }
8940
8941 if (!isInput) {
8942 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8943 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8944 if (msdModule != nullptr) {
8945 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8946 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8947 for (const auto &profile: msdModule->getOutputProfiles()) {
8948 if (!profile->asAudioPort()->isDirectOutput()) {
8949 continue;
8950 }
8951 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8952 }
8953 } else {
8954 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8955 }
8956 }
8957 }
8958
8959 return NO_ERROR;
8960 }
8961
reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,const audio_config_t * config,audio_output_flags_t flags,const char * caller)8962 sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8963 const audio_config_t *config,
8964 audio_output_flags_t flags,
8965 const char* caller) {
8966 closeOutput(outputDesc->mIoHandle);
8967 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8968 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8969 if (preferredOutput == nullptr) {
8970 ALOGE("%s failed to reopen output device=%d, caller=%s",
8971 __func__, outputDesc->devices()[0]->getId(), caller);
8972 }
8973 return preferredOutput;
8974 }
8975
reopenOutputsWithDevices(const std::map<audio_io_handle_t,DeviceVector> & outputsToReopen)8976 void AudioPolicyManager::reopenOutputsWithDevices(
8977 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8978 for (const auto& [output, devices] : outputsToReopen) {
8979 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8980 closeOutput(output);
8981 openOutputWithProfileAndDevice(desc->mProfile, devices);
8982 }
8983 }
8984
getClientsForStream(audio_stream_type_t streamType) const8985 PortHandleVector AudioPolicyManager::getClientsForStream(
8986 audio_stream_type_t streamType) const {
8987 PortHandleVector clients;
8988 for (size_t i = 0; i < mOutputs.size(); ++i) {
8989 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8990 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8991 }
8992 return clients;
8993 }
8994
invalidateStreams(StreamTypeVector streams) const8995 void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8996 PortHandleVector clients;
8997 for (auto stream : streams) {
8998 PortHandleVector clientsForStream = getClientsForStream(stream);
8999 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9000 }
9001 mpClientInterface->invalidateTracks(clients);
9002 }
9003
updateClientsInternalMute(const sp<android::SwAudioOutputDescriptor> & desc)9004 void AudioPolicyManager::updateClientsInternalMute(
9005 const sp<android::SwAudioOutputDescriptor> &desc) {
9006 if (!desc->isBitPerfect() ||
9007 !com::android::media::audioserver::
9008 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9009 // This is only used for bit perfect output now.
9010 return;
9011 }
9012 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9013 bool bitPerfectClientInternalMute = false;
9014 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9015 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9016 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9017 bitPerfectClient = client;
9018 continue;
9019 }
9020 bool muted = false;
9021 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9022 // System sound is muted.
9023 muted = true;
9024 } else {
9025 bitPerfectClientInternalMute = true;
9026 }
9027 if (client->setInternalMute(muted)) {
9028 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9029 if (!result.ok()) {
9030 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9031 continue;
9032 }
9033 media::TrackInternalMuteInfo info;
9034 info.portId = result.value();
9035 info.muted = client->getInternalMute();
9036 clientsInternalMute.push_back(std::move(info));
9037 }
9038 }
9039 if (bitPerfectClient != nullptr &&
9040 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9041 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9042 if (result.ok()) {
9043 media::TrackInternalMuteInfo info;
9044 info.portId = result.value();
9045 info.muted = bitPerfectClient->getInternalMute();
9046 clientsInternalMute.push_back(std::move(info));
9047 } else {
9048 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9049 __func__, bitPerfectClient->portId());
9050 }
9051 }
9052 if (!clientsInternalMute.empty()) {
9053 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9054 status != NO_ERROR) {
9055 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9056 }
9057 }
9058 }
9059
9060 } // namespace android
9061