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