-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAudioPolicyManager.cpp
2213 lines (1968 loc) · 101 KB
/
AudioPolicyManager.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2013-2020 The Linux Foundation. All rights reserved.
* Not a contribution.
*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define LOG_TAG "AudioPolicyManagerCustom"
//#define LOG_NDEBUG 0
//#define VERY_VERBOSE_LOGGING
#ifdef VERY_VERBOSE_LOGGING
#define ALOGVV ALOGV
#else
#define ALOGVV(a...) do { } while(0)
#endif
// A device mask for all audio output devices that are considered "remote" when evaluating
// active output devices in isStreamActiveRemotely()
#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
// A device mask for all audio input and output devices where matching inputs/outputs on device
// type alone is not enough: the address must match too
#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
#define SAMPLE_RATE_8000 8000
#include <inttypes.h>
#include <math.h>
#include <cutils/properties.h>
#include <utils/Log.h>
#include <hardware/audio.h>
#include <hardware/audio_effect.h>
#include <media/AudioParameter.h>
#include "AudioPolicyManager.h"
#include <policy.h>
namespace android {
/*audio policy: workaround for truncated touch sounds*/
//FIXME: workaround for truncated touch sounds
// to be removed when the problem is handled by system UI
#define TOUCH_SOUND_FIXED_DELAY_MS 100
sp<APMConfigHelper> AudioPolicyManagerCustom::mApmConfigs = new APMConfigHelper();
audio_output_flags_t AudioPolicyManagerCustom::getFallBackPath()
{
audio_output_flags_t flag = AUDIO_OUTPUT_FLAG_FAST;
std::string fallback_path = mApmConfigs->getVoiceConcFallbackPath();
if (strlen(fallback_path.c_str()) > 0) {
if (!strncmp(fallback_path.c_str(), "deep-buffer", 11)) {
flag = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
}
else if (!strncmp(fallback_path.c_str(), "fast", 4)) {
flag = AUDIO_OUTPUT_FLAG_FAST;
}
else {
ALOGD("voice_conc:not a recognised path(%s) in prop vendor.voice.conc.fallbackpath",
fallback_path.c_str());
}
}
else {
ALOGD("voice_conc:prop vendor.voice.conc.fallbackpath not set");
}
ALOGD("voice_conc:picked up flag(0x%x) from prop vendor.voice.conc.fallbackpath",
flag);
return flag;
}
template <typename T>
bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
{
if (left.size() != right.size()) {
return false;
}
for (size_t index = 0; index < right.size(); index++) {
if (left[index] != right[index]) {
return false;
}
}
return true;
}
template <typename T>
bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
{
return !(left == right);
}
// ----------------------------------------------------------------------------
// AudioPolicyInterface implementation
// ----------------------------------------------------------------------------
extern "C" AudioPolicyInterface* createAudioPolicyManager(
AudioPolicyClientInterface *clientInterface)
{
AudioPolicyManagerCustom *apm = new AudioPolicyManagerCustom(clientInterface);
status_t status = apm->initialize();
if (status != NO_ERROR) {
delete apm;
apm = nullptr;
}
return apm;
}
extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface)
{
delete interface;
}
status_t AudioPolicyManagerCustom::setDeviceConnectionStateInt(audio_devices_t deviceType,
audio_policy_dev_state_t state,
const char *device_address,
const char *device_name,
audio_format_t encodedFormat)
{
ALOGD("setDeviceConnectionStateInt() device: 0x%X, state %d, address %s name %s format 0x%X",
deviceType, state, device_address, device_name, encodedFormat);
// connect/disconnect only 1 device at a time
if (!audio_is_output_device(deviceType) && !audio_is_input_device(deviceType)) return BAD_VALUE;
sp<DeviceDescriptor> device =
mHwModules.getDeviceDescriptor(deviceType, device_address, device_name, encodedFormat,
state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
if (device == 0) {
return INVALID_OPERATION;
}
// handle output devices
if (audio_is_output_device(deviceType)) {
SortedVector <audio_io_handle_t> outputs;
ssize_t index = mAvailableOutputDevices.indexOf(device);
// save a copy of the opened output descriptors before any output is opened or closed
// by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
mPreviousOutputs = mOutputs;
switch (state)
{
// handle output device connection
case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
if (index >= 0) {
if (mApmConfigs->isHDMISpkEnabled() &&
(popcount(deviceType) == 1) && (deviceType & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
if (!strncmp(device_address, "hdmi_spkr", 9)) {
mHdmiAudioDisabled = false;
} else {
mHdmiAudioEvent = true;
}
}
ALOGW("setDeviceConnectionState() device already connected: %x", deviceType);
return INVALID_OPERATION;
}
ALOGV("%s() connecting device %s format %x",
__func__, device->toString().c_str(), encodedFormat);
// register new device as available
if (mAvailableOutputDevices.add(device) < 0) {
return NO_MEMORY;
}
if (mApmConfigs->isHDMISpkEnabled() &&
(popcount(deviceType) == 1) && (deviceType & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
if (!strncmp(device_address, "hdmi_spkr", 9)) {
mHdmiAudioDisabled = false;
} else {
mHdmiAudioEvent = true;
}
if (mHdmiAudioDisabled || !mHdmiAudioEvent) {
mAvailableOutputDevices.remove(device);
ALOGW("HDMI sink not connected, do not route audio to HDMI out");
return INVALID_OPERATION;
}
}
// Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
// parameters on newly connected devices (instead of opening the outputs...)
broadcastDeviceConnectionState(device, state);
if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
mAvailableOutputDevices.remove(device);
mHwModules.cleanUpForDevice(device);
broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
return INVALID_OPERATION;
}
if (deviceType == AUDIO_DEVICE_OUT_AUX_DIGITAL) {
chkDpConnAndAllowedForVoice();
}
// outputs should never be empty here
ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
"checkOutputsForDevice() returned no outputs but status OK");
ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
} break;
// handle output device disconnection
case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
if (index < 0) {
if (mApmConfigs->isHDMISpkEnabled() &&
(popcount(deviceType) == 1) && (deviceType & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
if (!strncmp(device_address, "hdmi_spkr", 9)) {
mHdmiAudioDisabled = true;
} else {
mHdmiAudioEvent = false;
}
}
ALOGW("setDeviceConnectionState() device not connected: %x", deviceType);
return INVALID_OPERATION;
}
ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
// Send Disconnect to HALs
broadcastDeviceConnectionState(device, state);
// remove device from available output devices
mAvailableOutputDevices.remove(device);
mOutputs.clearSessionRoutesForDevice(device);
if (mApmConfigs->isHDMISpkEnabled() &&
(popcount(deviceType) == 1) && (deviceType & AUDIO_DEVICE_OUT_AUX_DIGITAL)) {
if (!strncmp(device_address, "hdmi_spkr", 9)) {
mHdmiAudioDisabled = true;
} else {
mHdmiAudioEvent = false;
}
}
checkOutputsForDevice(device, state, outputs);
// Reset active device codec
device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
if (deviceType == AUDIO_DEVICE_OUT_AUX_DIGITAL) {
mEngine->setDpConnAndAllowedForVoice(false);
}
} break;
default:
ALOGE("%s() invalid state: %x", __func__, state);
return BAD_VALUE;
}
// Propagate device availability to Engine
setEngineDeviceConnectionState(device, state);
if (!outputs.isEmpty()) {
for (size_t i = 0; i < outputs.size(); i++) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
// close voip output before track invalidation to allow creation of
// new voip stream from restoreTrack
if ((desc->mFlags == (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_VOIP_RX)) != 0) {
closeOutput(outputs[i]);
outputs.remove(outputs[i]);
}
}
}
// No need to evaluate playback routing when connecting a remote submix
// output device used by a dynamic policy of type recorder as no
// playback use case is affected.
bool doCheckForDeviceAndOutputChanges = true;
if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX
&& strncmp(device_address, "0", AUDIO_DEVICE_MAX_ADDRESS_LEN) != 0) {
for (audio_io_handle_t output : outputs) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
if (policyMix != nullptr
&& policyMix->mMixType == MIX_TYPE_RECORDERS
&& strncmp(device_address,
policyMix->mDeviceAddress.string(),
AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
doCheckForDeviceAndOutputChanges = false;
break;
}
}
}
auto checkCloseOutputs = [&]() {
// outputs must be closed after checkOutputForAllStrategies() is executed
if (!outputs.isEmpty()) {
for (audio_io_handle_t output : outputs) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
// close unused outputs after device disconnection or direct outputs that have
// been opened by checkOutputsForDevice() to query dynamic parameters
if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
(((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
(desc->mDirectOpenCount == 0))) {
closeOutput(output);
}
}
// check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
return true;
}
return false;
};
if (doCheckForDeviceAndOutputChanges) {
checkForDeviceAndOutputChanges(checkCloseOutputs);
} else {
checkCloseOutputs();
}
if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
updateCallRouting(newDevices);
}
const DeviceVector msdOutDevices = getMsdAudioOutDevices();
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
(desc != mPrimaryOutput))) {
DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
// do not force device change on duplicated output because if device is 0, it will
// also force a device 0 for the two outputs it is duplicated to which may override
// a valid device selection on those outputs.
bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
&& !desc->isDuplicated()
&& (!device_distinguishes_on_address(deviceType)
// always force when disconnecting (a non-duplicated device)
|| (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
setOutputDevices(desc, newDevices, force, 0);
}
}
if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
cleanUpForDevice(device);
}
mpClientInterface->onAudioPortListUpdate();
return NO_ERROR;
} // end if is output device
// handle input devices
if (audio_is_input_device(deviceType)) {
ssize_t index = mAvailableInputDevices.indexOf(device);
switch (state)
{
// handle input device connection
case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
if (index >= 0) {
ALOGW("setDeviceConnectionState() device already connected: %d", deviceType);
return INVALID_OPERATION;
}
if (mAvailableInputDevices.add(device) < 0) {
return NO_MEMORY;
}
// Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
// parameters on newly connected devices (instead of opening the inputs...)
broadcastDeviceConnectionState(device, state);
if (checkInputsForDevice(device, state) != NO_ERROR) {
mAvailableInputDevices.remove(device);
broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
mHwModules.cleanUpForDevice(device);
return INVALID_OPERATION;
}
} break;
// handle input device disconnection
case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
if (index < 0) {
ALOGW("setDeviceConnectionState() device not connected: %d", deviceType);
return INVALID_OPERATION;
}
ALOGV("setDeviceConnectionState() disconnecting input device %x", deviceType);
// Set Disconnect to HALs
broadcastDeviceConnectionState(device, state);
mAvailableInputDevices.remove(device);
checkInputsForDevice(device, state);
} break;
default:
ALOGE("setDeviceConnectionState() invalid state: %x", state);
return BAD_VALUE;
}
// Propagate device availability to Engine
setEngineDeviceConnectionState(device, state);
checkCloseInputs();
/*audio policy: fix call volume over USB*/
// As the input device list can impact the output device selection, update
// getDeviceForStrategy() cache
updateDevicesAndOutputs();
if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
updateCallRouting(newDevices);
}
if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
cleanUpForDevice(device);
}
mpClientInterface->onAudioPortListUpdate();
return NO_ERROR;
} // end if is input device
ALOGW("setDeviceConnectionState() invalid device: %x", deviceType);
return BAD_VALUE;
}
void AudioPolicyManagerCustom::chkDpConnAndAllowedForVoice()
{
String8 value;
bool connAndAllowed = false;
String8 valueStr = mpClientInterface->getParameters((audio_io_handle_t)0,
String8("dp_for_voice"));
AudioParameter result = AudioParameter(valueStr);
if (result.get(String8("dp_for_voice"), value) == NO_ERROR) {
connAndAllowed = value.contains("true");
}
mEngine->setDpConnAndAllowedForVoice(connAndAllowed);
}
bool AudioPolicyManagerCustom::isInvalidationOfMusicStreamNeeded(const audio_attributes_t &attr)
{
if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> newOutputDesc = mOutputs.valueAt(i);
if (newOutputDesc->getFormat() == AUDIO_FORMAT_DSD)
return false;
}
}
return true;
}
void AudioPolicyManagerCustom::checkOutputForAttributes(const audio_attributes_t &attr)
{
DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
// also take into account external policy-related changes: add all outputs which are
// associated with policies in the "before" and "after" output vectors
ALOGVV("%s(): policy related outputs", __func__);
for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
const sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
if (desc != 0 && desc->mPolicyMix != NULL) {
srcOutputs.add(desc->mIoHandle);
ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
}
}
for (size_t i = 0 ; i < mOutputs.size() ; i++) {
const sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
if (desc != 0 && desc->mPolicyMix != NULL) {
dstOutputs.add(desc->mIoHandle);
ALOGVV(" new outputs: adding %d", desc->mIoHandle);
}
}
if ((srcOutputs != dstOutputs) && isInvalidationOfMusicStreamNeeded(attr)) {
AudioPolicyManager::checkOutputForAttributes(attr);
}
}
// This function checks for the parameters which can be offloaded.
// This can be enhanced depending on the capability of the DSP and policy
// of the system.
bool AudioPolicyManagerCustom::isOffloadSupported(const audio_offload_info_t& offloadInfo)
{
DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
" BitRate=%u, duration=%" PRId64 " us, has_video=%d",
offloadInfo.sample_rate, offloadInfo.channel_mask,
offloadInfo.format,
offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
offloadInfo.has_video);
if (mMasterMono) {
return false; // no offloading if mono is set.
}
if (mApmConfigs->isVoiceConcEnabled()) {
if (mApmConfigs->isVoicePlayConcDisabled() && isInCall()) {
ALOGD("\n copl: blocking compress offload on call mode\n");
return false;
}
}
if (mApmConfigs->isVoiceDSDConcDisabled() &&
isInCall() && (offloadInfo.format == AUDIO_FORMAT_DSD)) {
ALOGD("blocking DSD compress offload on call mode");
return false;
}
if (mApmConfigs->isRecPlayConcEnabled()) {
if (mApmConfigs->isRecPlayConcDisabled() &&
((true == mIsInputRequestOnProgress) ||
(mInputs.activeInputsCountOnDevices(primaryInputDevices) > 0))) {
ALOGD("copl: blocking compress offload for record concurrency");
return false;
}
}
// Check if stream type is music, then only allow offload as of now.
if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
{
ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
return false;
}
// Check if offload has been disabled
bool offloadDisabled = mApmConfigs->isAudioOffloadDisabled();
if (offloadDisabled) {
ALOGI("offload disabled by audio.offload.disable=%d", offloadDisabled);
return false;
}
//check if it's multi-channel AAC (includes sub formats) and FLAC format
if ((popcount(offloadInfo.channel_mask) > 2) &&
(((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_VORBIS))) {
ALOGD("offload disabled for multi-channel AAC,FLAC and VORBIS format");
return false;
}
if (mApmConfigs->isExtnFormatsEnabled()) {
//check if it's multi-channel FLAC/ALAC/WMA format with sample rate > 48k
if ((popcount(offloadInfo.channel_mask) > 2) &&
(((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_FLAC) ||
(((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_ALAC) && (offloadInfo.sample_rate > 48000)) ||
(((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA) && (offloadInfo.sample_rate > 48000)) ||
(((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) && (offloadInfo.sample_rate > 48000)) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC_ADTS))) {
ALOGD("offload disabled for multi-channel FLAC/ALAC/WMA/AAC_ADTS clips with sample rate > 48kHz");
return false;
}
// check against wma std bit rate restriction
if ((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA) {
int32_t sr_id = -1;
uint32_t min_bitrate, max_bitrate;
for (int i = 0; i < WMA_STD_NUM_FREQ; i++) {
if (offloadInfo.sample_rate == wmaStdSampleRateTbl[i]) {
sr_id = i;
break;
}
}
if ((sr_id < 0) || (popcount(offloadInfo.channel_mask) > 2)
|| (popcount(offloadInfo.channel_mask) <= 0)) {
ALOGE("invalid sample rate or channel count");
return false;
}
min_bitrate = wmaStdMinAvgByteRateTbl[sr_id][popcount(offloadInfo.channel_mask) - 1];
max_bitrate = wmaStdMaxAvgByteRateTbl[sr_id][popcount(offloadInfo.channel_mask) - 1];
if ((offloadInfo.bit_rate > max_bitrate) || (offloadInfo.bit_rate < min_bitrate)) {
ALOGD("offload disabled for WMA clips with unsupported bit rate");
ALOGD("bit_rate %d, max_bitrate %d, min_bitrate %d", offloadInfo.bit_rate, max_bitrate, min_bitrate);
return false;
}
}
// Safely choose the min bitrate as threshold and leave the restriction to NT decoder as we can't distinguish wma pro and wma lossless here.
if ((((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) && (offloadInfo.bit_rate > MAX_BITRATE_WMA_PRO)) ||
(((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) && (offloadInfo.bit_rate > MAX_BITRATE_WMA_LOSSLESS))) {
ALOGD("offload disabled for WMA_PRO/WMA_LOSSLESS clips with bit rate over maximum supported value");
return false;
}
}
//TODO: enable audio offloading with video when ready
if (offloadInfo.has_video && !mApmConfigs->isAudioOffloadVideoEnabled()) {
ALOGV("isOffloadSupported: has_video == true, returning false");
return false;
}
if (offloadInfo.has_video && offloadInfo.is_streaming &&
!mApmConfigs->isAVStreamingOffloadEnabled()) {
ALOGW("offload disabled by vendor.audio.av.streaming.offload.enable %d",
mApmConfigs->isAVStreamingOffloadEnabled());
return false;
}
//If duration is less than minimum value defined in property, return false
if (mApmConfigs->getAudioOffloadMinDuration() > 0) {
if (offloadInfo.duration_us < (mApmConfigs->getAudioOffloadMinDuration() * 1000000 )) {
ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%u)", mApmConfigs->getAudioOffloadMinDuration());
return false;
}
} else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
//duration checks only valid for MP3/AAC/ formats,
//do not check duration for other audio formats, e.g. AAC/AC3 and amrwb+ formats
if ((offloadInfo.format == AUDIO_FORMAT_MP3) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_FLAC) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_VORBIS))
return false;
if (mApmConfigs->isExtnFormatsEnabled()) {
if (((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_WMA_PRO) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_ALAC) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_APE) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_DSD) ||
((offloadInfo.format & AUDIO_FORMAT_MAIN_MASK) == AUDIO_FORMAT_AAC_ADTS))
return false;
}
}
// Do not allow offloading if one non offloadable effect is enabled. This prevents from
// creating an offloaded track and tearing it down immediately after start when audioflinger
// detects there is an active non offloadable effect.
// FIXME: We should check the audio session here but we do not have it in this context.
// This may prevent offloading in rare situations where effects are left active by apps
// in the background.
if (mEffects.isNonOffloadableEffectEnabled()) {
return false;
}
// See if there is a profile to support this.
// AUDIO_DEVICE_NONE
sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
offloadInfo.sample_rate,
offloadInfo.format,
offloadInfo.channel_mask,
AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
true /*directOnly*/);
ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
return (profile != 0);
}
void AudioPolicyManagerCustom::setPhoneState(audio_mode_t state)
{
ALOGD("setPhoneState() state %d", state);
// store previous phone state for management of sonification strategy below
int oldState = mEngine->getPhoneState();
if (mEngine->setPhoneState(state) != NO_ERROR) {
ALOGW("setPhoneState() invalid or same state %d", state);
return;
}
/// Opens: can these line be executed after the switch of volume curves???
if (isStateInCall(oldState)) {
ALOGV("setPhoneState() in call state management: new state is %d", state);
// force reevaluating accessibility routing when call stops
mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
}
/**
* Switching to or from incall state or switching between telephony and VoIP lead to force
* routing command.
*/
bool force = ((is_state_in_call(oldState) != is_state_in_call(state))
|| (is_state_in_call(state) && (state != oldState)));
// check for device and output changes triggered by new phone state
checkForDeviceAndOutputChanges();
sp<SwAudioOutputDescriptor> hwOutputDesc = mPrimaryOutput;
if (mApmConfigs->isVoiceConcEnabled()) {
bool prop_playback_enabled = mApmConfigs->isVoicePlayConcDisabled();
bool prop_rec_enabled = mApmConfigs->isVoiceRecConcDisabled();
bool prop_voip_enabled = mApmConfigs->isVoiceVOIPConcDisabled();
if ((AUDIO_MODE_IN_CALL != oldState) && (AUDIO_MODE_IN_CALL == state)) {
ALOGD("voice_conc:Entering to call mode oldState :: %d state::%d ",
oldState, state);
mvoice_call_state = state;
if (prop_rec_enabled) {
//Close all active inputs
Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
if (activeInputs.size() != 0) {
for (size_t i = 0; i < activeInputs.size(); i++) {
sp<AudioInputDescriptor> activeInput = activeInputs[i];
switch(activeInput->source()) {
case AUDIO_SOURCE_VOICE_UPLINK:
case AUDIO_SOURCE_VOICE_DOWNLINK:
case AUDIO_SOURCE_VOICE_CALL:
ALOGD("voice_conc:FOUND active input during call active: %d",
activeInput->source());
break;
case AUDIO_SOURCE_VOICE_COMMUNICATION:
if (prop_voip_enabled) {
ALOGD("voice_conc:CLOSING VoIP input source on call setup :%d ",
activeInput->source());
RecordClientVector activeClients = activeInput->clientsList(true /*activeOnly*/);
for (const auto& activeClient : activeClients) {
closeClient(activeClient->portId());
}
}
break;
default:
ALOGD("voice_conc:CLOSING input on call setup for inputSource: %d",
activeInput->source());
RecordClientVector activeClients = activeInput->clientsList(true /*activeOnly*/);
for (const auto& activeClient : activeClients) {
closeClient(activeClient->portId());
}
break;
}
}
}
} else if (prop_voip_enabled) {
Vector<sp <AudioInputDescriptor> > activeInputs = mInputs.getActiveInputs();
if (activeInputs.size() != 0) {
for (size_t i = 0; i < activeInputs.size(); i++) {
sp<AudioInputDescriptor> activeInput = activeInputs[i];
if (AUDIO_SOURCE_VOICE_COMMUNICATION == activeInput->source()) {
ALOGD("voice_conc:CLOSING VoIP on call setup : %d",activeInput->source());
RecordClientVector activeClients = activeInput->clientsList(true /*activeOnly*/);
for (const auto& activeClient : activeClients) {
closeClient(activeClient->portId());
}
}
}
}
}
if (prop_playback_enabled) {
// Move tracks associated to this strategy from previous output to new output
for (int i = AUDIO_STREAM_SYSTEM; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
ALOGV("voice_conc:Invalidate on call mode for stream :: %d ", i);
if (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag) {
if ((AUDIO_STREAM_MUSIC == i) ||
(AUDIO_STREAM_VOICE_CALL == i) ) {
ALOGD("voice_conc:Invalidate stream type %d", i);
mpClientInterface->invalidateStream((audio_stream_type_t)i);
}
} else if (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) {
ALOGD("voice_conc:Invalidate stream type %d", i);
mpClientInterface->invalidateStream((audio_stream_type_t)i);
}
}
}
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
if ( (outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
ALOGD("voice_conc:ouput desc / profile is NULL");
continue;
}
bool isFastFallBackNeeded =
((AUDIO_OUTPUT_FLAG_DEEP_BUFFER | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT_PCM) & outputDesc->mProfile->getFlags());
if ((AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) && isFastFallBackNeeded) {
if (((!outputDesc->isDuplicated() && outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY))
&& prop_playback_enabled) {
ALOGD("voice_conc:calling suspendOutput on call mode for primary output");
mpClientInterface->suspendOutput(mOutputs.keyAt(i));
} //Close compress all sessions
else if ((outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
&& prop_playback_enabled) {
ALOGD("voice_conc:calling closeOutput on call mode for COMPRESS output");
closeOutput(mOutputs.keyAt(i));
}
else if ((outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_VOIP_RX)
&& prop_voip_enabled) {
ALOGD("voice_conc:calling closeOutput on call mode for DIRECT output");
closeOutput(mOutputs.keyAt(i));
}
} else if (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag) {
if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_VOIP_RX) {
if (prop_voip_enabled) {
ALOGD("voice_conc:calling closeOutput on call mode for DIRECT output");
closeOutput(mOutputs.keyAt(i));
}
}
else if (prop_playback_enabled
&& (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT)) {
ALOGD("voice_conc:calling closeOutput on call mode for COMPRESS output");
closeOutput(mOutputs.keyAt(i));
}
}
}
}
if ((AUDIO_MODE_IN_CALL == oldState || AUDIO_MODE_IN_COMMUNICATION == oldState) &&
(AUDIO_MODE_NORMAL == state) && prop_playback_enabled && mvoice_call_state) {
ALOGD("voice_conc:EXITING from call mode oldState :: %d state::%d \n",oldState, state);
mvoice_call_state = 0;
if (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) {
//restore PCM (deep-buffer) output after call termination
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
if ( (outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
ALOGD("voice_conc:ouput desc / profile is NULL");
continue;
}
if (!outputDesc->isDuplicated() && outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
ALOGD("voice_conc:calling restoreOutput after call mode for primary output");
mpClientInterface->restoreOutput(mOutputs.keyAt(i));
}
}
}
//call invalidate tracks so that any open streams can fall back to deep buffer/compress path from ULL
for (int i = AUDIO_STREAM_SYSTEM; i < AUDIO_STREAM_FOR_POLICY_CNT; i++) {
ALOGV("voice_conc:Invalidate on call mode for stream :: %d ", i);
if (AUDIO_OUTPUT_FLAG_DEEP_BUFFER == mFallBackflag) {
if ((AUDIO_STREAM_MUSIC == i) ||
(AUDIO_STREAM_VOICE_CALL == i) ) {
mpClientInterface->invalidateStream((audio_stream_type_t)i);
}
} else if (AUDIO_OUTPUT_FLAG_FAST == mFallBackflag) {
mpClientInterface->invalidateStream((audio_stream_type_t)i);
}
}
}
}
sp<SwAudioOutputDescriptor> outputDesc = NULL;
for (size_t i = 0; i < mOutputs.size(); i++) {
outputDesc = mOutputs.valueAt(i);
if ((outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
ALOGD("voice_conc:ouput desc / profile is NULL");
continue;
}
if (mApmConfigs->isVoiceDSDConcDisabled() &&
(outputDesc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) &&
(outputDesc->getFormat() == AUDIO_FORMAT_DSD)) {
ALOGD("voice_conc:calling closeOutput on call mode for DSD COMPRESS output");
closeOutput(mOutputs.keyAt(i));
// call invalidate for music, so that DSD compress will fallback to deep-buffer.
mpClientInterface->invalidateStream(AUDIO_STREAM_MUSIC);
}
}
if (mApmConfigs->isRecPlayConcEnabled()) {
if (mApmConfigs->isRecPlayConcDisabled()) {
if (AUDIO_MODE_IN_COMMUNICATION == mEngine->getPhoneState()) {
ALOGD("phone state changed to MODE_IN_COMM invlaidating music and voice streams");
// call invalidate for voice streams, so that it can use deepbuffer with VoIP out device from HAL
mpClientInterface->invalidateStream(AUDIO_STREAM_VOICE_CALL);
// call invalidate for music, so that compress will fallback to deep-buffer with VoIP out device
mpClientInterface->invalidateStream(AUDIO_STREAM_MUSIC);
// close compress output to make sure session will be closed before timeout(60sec)
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
if ((outputDesc == NULL) || (outputDesc->mProfile == NULL)) {
ALOGD("ouput desc / profile is NULL");
continue;
}
if (outputDesc->mProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
ALOGD("calling closeOutput on call mode for COMPRESS output");
closeOutput(mOutputs.keyAt(i));
}
}
} else if ((oldState == AUDIO_MODE_IN_COMMUNICATION) &&
(mEngine->getPhoneState() == AUDIO_MODE_NORMAL)) {
// call invalidate for music so that music can fallback to compress
mpClientInterface->invalidateStream(AUDIO_STREAM_MUSIC);
}
}
}
mPrevPhoneState = oldState;
int delayMs = 0;
if (isStateInCall(state)) {
nsecs_t sysTime = systemTime();
auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
// mute media and sonification strategies and delay device switch by the largest
// latency of any output where either strategy is active.
// This avoid sending the ring tone or music tail into the earpiece or headset.
if ((desc->isStrategyActive(musicStrategy,
SONIFICATION_HEADSET_MUSIC_DELAY,
sysTime) ||
desc->isStrategyActive(sonificationStrategy,
SONIFICATION_HEADSET_MUSIC_DELAY,
sysTime)) &&
(delayMs < (int)desc->latency()*2)) {
delayMs = desc->latency()*2;
}
setStrategyMute(musicStrategy, true, desc);
setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
nullptr, true /*fromCache*/).types());
setStrategyMute(sonificationStrategy, true, desc);
setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
nullptr, true /*fromCache*/).types());
}
}
if (hasPrimaryOutput()) {
// Note that despite the fact that getNewOutputDevice() is called on the primary output,
// the device returned is not necessarily reachable via this output
DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
// force routing command to audio hardware when ending call
// even if no device change is needed
if (isStateInCall(oldState) && rxDevices.isEmpty()) {
rxDevices = mPrimaryOutput->devices();
}
if (state == AUDIO_MODE_IN_CALL) {
updateCallRouting(rxDevices, delayMs);
} else if (oldState == AUDIO_MODE_IN_CALL) {
if (mCallRxPatch != 0) {
mpClientInterface->releaseAudioPatch(mCallRxPatch->getAfHandle(), 0);
mCallRxPatch.clear();
}
if (mCallTxPatch != 0) {
mpClientInterface->releaseAudioPatch(mCallTxPatch->getAfHandle(), 0);
mCallTxPatch.clear();
}
setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
} else {
setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
}
}
// reevaluate routing on all outputs in case tracks have been started during the call
for (size_t i = 0; i < mOutputs.size(); i++) {
sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
}
}
if (isStateInCall(state)) {
ALOGV("setPhoneState() in call state management: new state is %d", state);
// force reevaluating accessibility routing when call starts
mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
}
// Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
}
void AudioPolicyManagerCustom::setForceUse(audio_policy_force_use_t usage,
audio_policy_forced_cfg_t config)
{
ALOGD("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
if (config == mEngine->getForceUse(usage)) {
return;
}
if (mEngine->setForceUse(usage, config) != NO_ERROR) {
ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
return;
}
bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
(usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
(usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
// check for device and output changes triggered by new force usage
checkForDeviceAndOutputChanges();
// force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
}
//FIXME: workaround for truncated touch sounds
// to be removed when the problem is handled by system UI
uint32_t delayMs = 0;
uint32_t waitMs = 0;
if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
}
if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
DeviceVector newDevices = getNewOutputDevices(mPrimaryOutput, true /*fromCache*/);
if (forceVolumeReeval && !newDevices.isEmpty()) {
applyStreamVolumes(mPrimaryOutput, newDevices.types(), delayMs, true);
}
waitMs = updateCallRouting(newDevices, delayMs);