-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ShadowAudioManager.java
1074 lines (957 loc) · 39.3 KB
/
ShadowAudioManager.java
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
package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.LOLLIPOP;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.O;
import static android.os.Build.VERSION_CODES.P;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static android.os.Build.VERSION_CODES.S;
import static android.os.Build.VERSION_CODES.TIRAMISU;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
import static org.robolectric.util.ReflectionHelpers.ClassParameter.from;
import static org.robolectric.util.reflector.Reflector.reflector;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.TargetApi;
import android.media.AudioAttributes;
import android.media.AudioDeviceCallback;
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioPlaybackConfiguration;
import android.media.AudioProfile;
import android.media.AudioRecordingConfiguration;
import android.media.IPlayer;
import android.media.PlayerBase;
import android.media.audiopolicy.AudioPolicy;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Parcel;
import android.view.KeyEvent;
import com.android.internal.util.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.HiddenApi;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.RealObject;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.reflector.Constructor;
import org.robolectric.util.reflector.ForType;
@SuppressWarnings({"UnusedDeclaration"})
@Implements(value = AudioManager.class)
public class ShadowAudioManager {
@RealObject AudioManager realAudioManager;
public static final int MAX_VOLUME_MUSIC_DTMF = 15;
public static final int DEFAULT_MAX_VOLUME = 7;
public static final int MIN_VOLUME = 0;
public static final int DEFAULT_VOLUME = 7;
public static final int INVALID_VOLUME = 0;
public static final int FLAG_NO_ACTION = 0;
public static final ImmutableList<Integer> ALL_STREAMS =
ImmutableList.of(
AudioManager.STREAM_MUSIC,
AudioManager.STREAM_ALARM,
AudioManager.STREAM_NOTIFICATION,
AudioManager.STREAM_RING,
AudioManager.STREAM_SYSTEM,
AudioManager.STREAM_VOICE_CALL,
AudioManager.STREAM_DTMF,
AudioManager.STREAM_ACCESSIBILITY);
private static final int INVALID_PATCH_HANDLE = -1;
private static final float MAX_VOLUME_DB = 0;
private static final float MIN_VOLUME_DB = -100;
private AudioFocusRequest lastAudioFocusRequest;
private int nextResponseValue = AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
private AudioManager.OnAudioFocusChangeListener lastAbandonedAudioFocusListener;
private android.media.AudioFocusRequest lastAbandonedAudioFocusRequest;
private HashMap<Integer, AudioStream> streamStatus = new HashMap<>();
private List<AudioPlaybackConfiguration> activePlaybackConfigurations = Collections.emptyList();
private List<AudioRecordingConfiguration> activeRecordingConfigurations = ImmutableList.of();
private final HashSet<AudioManager.AudioRecordingCallback> audioRecordingCallbacks =
new HashSet<>();
private final HashSet<AudioManager.AudioPlaybackCallback> audioPlaybackCallbacks =
new HashSet<>();
private final HashSet<AudioDeviceCallback> audioDeviceCallbacks = new HashSet<>();
private int ringerMode = AudioManager.RINGER_MODE_NORMAL;
private int mode = AudioManager.MODE_NORMAL;
private boolean bluetoothA2dpOn;
private boolean isBluetoothScoOn;
private boolean isSpeakerphoneOn;
private boolean isMicrophoneMuted = false;
private boolean isMusicActive;
private boolean wiredHeadsetOn;
private boolean isBluetoothScoAvailableOffCall = false;
private final Map<String, String> parameters = new HashMap<>();
private final Map<Integer, Boolean> streamsMuteState = new HashMap<>();
private final Map<String, AudioPolicy> registeredAudioPolicies = new HashMap<>();
private int audioSessionIdCounter = 1;
private final Map<AudioAttributes, ImmutableList<Object>> devicesForAttributes = new HashMap<>();
private final List<AudioDeviceInfo> outputDevicesWithDirectProfiles = new ArrayList<>();
private ImmutableList<Object> defaultDevicesForAttributes = ImmutableList.of();
private final Map<AudioAttributes, ImmutableList<AudioDeviceInfo>> audioDevicesForAttributes =
new HashMap<>();
private List<AudioDeviceInfo> inputDevices = new ArrayList<>();
private List<AudioDeviceInfo> outputDevices = new ArrayList<>();
private List<AudioDeviceInfo> availableCommunicationDevices = new ArrayList<>();
private AudioDeviceInfo communicationDevice = null;
private final List<KeyEvent> dispatchedMediaKeyEvents = new ArrayList<>();
private boolean isHotwordStreamSupportedForLookbackAudio = false;
private boolean isHotwordStreamSupportedWithoutLookbackAudio = false;
public ShadowAudioManager() {
for (int stream : ALL_STREAMS) {
streamStatus.put(stream, new AudioStream(DEFAULT_VOLUME, DEFAULT_MAX_VOLUME, FLAG_NO_ACTION));
}
streamStatus.get(AudioManager.STREAM_MUSIC).setMaxVolume(MAX_VOLUME_MUSIC_DTMF);
streamStatus.get(AudioManager.STREAM_DTMF).setMaxVolume(MAX_VOLUME_MUSIC_DTMF);
}
@Implementation
protected int getStreamMaxVolume(int streamType) {
AudioStream stream = streamStatus.get(streamType);
return (stream != null) ? stream.getMaxVolume() : INVALID_VOLUME;
}
@Implementation
protected int getStreamVolume(int streamType) {
AudioStream stream = streamStatus.get(streamType);
return (stream != null) ? stream.getCurrentVolume() : INVALID_VOLUME;
}
@Implementation(minSdk = P)
protected float getStreamVolumeDb(int streamType, int index, int deviceType) {
AudioStream stream = streamStatus.get(streamType);
if (stream == null) {
return INVALID_VOLUME;
}
if (index < MIN_VOLUME || index > stream.getMaxVolume()) {
throw new IllegalArgumentException("Invalid stream volume index " + index);
}
if (index == MIN_VOLUME) {
return Float.NEGATIVE_INFINITY;
}
float interpolation = (index - MIN_VOLUME) / (float) (stream.getMaxVolume() - MIN_VOLUME);
return MIN_VOLUME_DB + interpolation * (MAX_VOLUME_DB - MIN_VOLUME_DB);
}
@Implementation
protected void setStreamVolume(int streamType, int index, int flags) {
AudioStream stream = streamStatus.get(streamType);
if (stream != null) {
stream.setCurrentVolume(index);
stream.setFlag(flags);
}
}
@Implementation
protected boolean isBluetoothScoAvailableOffCall() {
return isBluetoothScoAvailableOffCall;
}
@Implementation
protected int requestAudioFocus(
android.media.AudioManager.OnAudioFocusChangeListener l, int streamType, int durationHint) {
lastAudioFocusRequest = new AudioFocusRequest(l, streamType, durationHint);
return nextResponseValue;
}
/**
* Provides a mock like interface for the requestAudioFocus method by storing the request object
* for later inspection and returning the value specified in setNextFocusRequestResponse.
*/
@Implementation(minSdk = O)
protected int requestAudioFocus(android.media.AudioFocusRequest audioFocusRequest) {
lastAudioFocusRequest = new AudioFocusRequest(audioFocusRequest);
return nextResponseValue;
}
@Implementation
protected int abandonAudioFocus(AudioManager.OnAudioFocusChangeListener l) {
lastAbandonedAudioFocusListener = l;
return nextResponseValue;
}
/**
* Provides a mock like interface for the abandonAudioFocusRequest method by storing the request
* object for later inspection and returning the value specified in setNextFocusRequestResponse.
*/
@Implementation(minSdk = O)
protected int abandonAudioFocusRequest(android.media.AudioFocusRequest audioFocusRequest) {
lastAbandonedAudioFocusListener = audioFocusRequest.getOnAudioFocusChangeListener();
lastAbandonedAudioFocusRequest = audioFocusRequest;
return nextResponseValue;
}
@Implementation
protected int getRingerMode() {
return ringerMode;
}
@Implementation
protected void setRingerMode(int ringerMode) {
if (!AudioManager.isValidRingerMode(ringerMode)) {
return;
}
this.ringerMode = ringerMode;
}
@Implementation
public static boolean isValidRingerMode(int ringerMode) {
return ringerMode >= 0
&& ringerMode
<= (int) ReflectionHelpers.getStaticField(AudioManager.class, "RINGER_MODE_MAX");
}
@Implementation
protected void setMode(int mode) {
int previousMode = this.mode;
this.mode = mode;
if (RuntimeEnvironment.getApiLevel() >= S && mode != previousMode) {
dispatchModeChangedListeners(mode);
}
}
private void dispatchModeChangedListeners(int newMode) {
Object modeDispatcherStub =
reflector(ModeDispatcherStubReflector.class).newModeDispatcherStub(realAudioManager);
reflector(ModeDispatcherStubReflector.class, modeDispatcherStub)
.dispatchAudioModeChanged(newMode);
}
@Implementation
protected int getMode() {
return this.mode;
}
@ForType(className = "android.media.AudioManager$ModeDispatcherStub")
interface ModeDispatcherStubReflector {
@Constructor
Object newModeDispatcherStub(AudioManager audioManager);
void dispatchAudioModeChanged(int newMode);
}
public void setStreamMaxVolume(int streamMaxVolume) {
streamStatus.forEach((key, value) -> value.setMaxVolume(streamMaxVolume));
}
public void setStreamVolume(int streamVolume) {
streamStatus.forEach((key, value) -> value.setCurrentVolume(streamVolume));
}
@Implementation
protected void setWiredHeadsetOn(boolean on) {
wiredHeadsetOn = on;
}
@Implementation
protected boolean isWiredHeadsetOn() {
return wiredHeadsetOn;
}
@Implementation
protected void setBluetoothA2dpOn(boolean on) {
bluetoothA2dpOn = on;
}
@Implementation
protected boolean isBluetoothA2dpOn() {
return bluetoothA2dpOn;
}
@Implementation
protected void setSpeakerphoneOn(boolean on) {
isSpeakerphoneOn = on;
}
@Implementation
protected boolean isSpeakerphoneOn() {
return isSpeakerphoneOn;
}
@Implementation
protected void setMicrophoneMute(boolean on) {
isMicrophoneMuted = on;
}
@Implementation
protected boolean isMicrophoneMute() {
return isMicrophoneMuted;
}
@Implementation
protected boolean isBluetoothScoOn() {
return isBluetoothScoOn;
}
@Implementation
protected void setBluetoothScoOn(boolean isBluetoothScoOn) {
this.isBluetoothScoOn = isBluetoothScoOn;
}
@Implementation
protected boolean isMusicActive() {
return isMusicActive;
}
@Implementation(minSdk = O)
protected List<AudioPlaybackConfiguration> getActivePlaybackConfigurations() {
return new ArrayList<>(activePlaybackConfigurations);
}
@Implementation
protected void setParameters(String keyValuePairs) {
if (keyValuePairs.isEmpty()) {
throw new IllegalArgumentException("keyValuePairs should not be empty");
}
if (keyValuePairs.charAt(keyValuePairs.length() - 1) != ';') {
throw new IllegalArgumentException("keyValuePairs should end with a ';'");
}
String[] pairs = keyValuePairs.split(";", 0);
for (String pair : pairs) {
if (pair.isEmpty()) {
continue;
}
String[] splittedPair = pair.split("=", 0);
if (splittedPair.length != 2) {
throw new IllegalArgumentException(
"keyValuePairs: each pair should be in the format of key=value;");
}
parameters.put(splittedPair[0], splittedPair[1]);
}
}
/**
* The expected composition for keys is not well defined.
*
* <p>For testing purposes this method call always returns null.
*/
@Implementation
protected String getParameters(String keys) {
return null;
}
/** Returns a single parameter that was set via {@link #setParameters(String)}. */
public String getParameter(String key) {
return parameters.get(key);
}
/**
* Implements {@link AudioManager#adjustStreamVolume(int, int, int)}.
*
* <p>Currently supports only the directions {@link AudioManager#ADJUST_MUTE}, {@link
* AudioManager#ADJUST_UNMUTE}, {@link AudioManager#ADJUST_LOWER} and {@link
* AudioManager#ADJUST_RAISE}.
*/
@Implementation
protected void adjustStreamVolume(int streamType, int direction, int flags) {
int streamVolume = getStreamVolume(streamType);
switch (direction) {
case AudioManager.ADJUST_MUTE:
streamsMuteState.put(streamType, true);
break;
case AudioManager.ADJUST_UNMUTE:
streamsMuteState.put(streamType, false);
break;
case AudioManager.ADJUST_RAISE:
int streamMaxVolume = getStreamMaxVolume(streamType);
if (streamVolume == INVALID_VOLUME || streamMaxVolume == INVALID_VOLUME) {
return;
}
int raisedVolume = streamVolume + 1;
if (raisedVolume <= streamMaxVolume) {
setStreamVolume(raisedVolume);
}
break;
case AudioManager.ADJUST_LOWER:
if (streamVolume == INVALID_VOLUME) {
return;
}
int lowerVolume = streamVolume - 1;
if (lowerVolume >= 1) {
setStreamVolume(lowerVolume);
}
break;
default:
break;
}
}
@Implementation(minSdk = M)
protected boolean isStreamMute(int streamType) {
if (!streamsMuteState.containsKey(streamType)) {
return false;
}
return streamsMuteState.get(streamType);
}
public void setIsBluetoothScoAvailableOffCall(boolean isBluetoothScoAvailableOffCall) {
this.isBluetoothScoAvailableOffCall = isBluetoothScoAvailableOffCall;
}
public void setIsStreamMute(int streamType, boolean isMuted) {
streamsMuteState.put(streamType, isMuted);
}
/**
* Registers callback that will receive changes made to the list of active playback configurations
* by {@link setActivePlaybackConfigurationsFor}.
*/
@Implementation(minSdk = O)
protected void registerAudioPlaybackCallback(
AudioManager.AudioPlaybackCallback cb, Handler handler) {
audioPlaybackCallbacks.add(cb);
}
/** Unregisters callback listening to changes made to list of active playback configurations. */
@Implementation(minSdk = O)
protected void unregisterAudioPlaybackCallback(AudioManager.AudioPlaybackCallback cb) {
audioPlaybackCallbacks.remove(cb);
}
/**
* Returns the devices associated with the given audio stream.
*
* <p>In this shadow-implementation the devices returned are either
*
* <ol>
* <li>devices set through {@link #setDevicesForAttributes}, or
* <li>devices set through {@link #setDefaultDevicesForAttributes}, or
* <li>an empty list.
* </ol>
*/
@Implementation(minSdk = R)
@NonNull
protected List<Object> getDevicesForAttributes(@NonNull AudioAttributes attributes) {
ImmutableList<Object> devices = devicesForAttributes.get(attributes);
return devices == null ? defaultDevicesForAttributes : devices;
}
/** Sets the devices associated with the given audio stream. */
public void setDevicesForAttributes(
@NonNull AudioAttributes attributes, @NonNull ImmutableList<Object> devices) {
devicesForAttributes.put(attributes, devices);
}
/** Sets the devices to use as default for all audio streams. */
public void setDefaultDevicesForAttributes(@NonNull ImmutableList<Object> devices) {
defaultDevicesForAttributes = devices;
}
/**
* Returns the audio devices that would be used for the routing of the given audio attributes.
*
* <p>Devices can be added with {@link #setAudioDevicesForAttributes}. Note that {@link
* #setDevicesForAttributes} and {@link #setDefaultDevicesForAttributes} have no effect on the
* return value of this method.
*/
@Implementation(minSdk = TIRAMISU)
@NonNull
protected List<AudioDeviceInfo> getAudioDevicesForAttributes(
@NonNull AudioAttributes attributes) {
ImmutableList<AudioDeviceInfo> devices = audioDevicesForAttributes.get(attributes);
return devices == null ? ImmutableList.of() : devices;
}
/** Sets the audio devices returned from {@link #getAudioDevicesForAttributes}. */
public void setAudioDevicesForAttributes(
@NonNull AudioAttributes attributes, @NonNull ImmutableList<AudioDeviceInfo> devices) {
audioDevicesForAttributes.put(attributes, devices);
}
/**
* Sets the list of connected input devices represented by {@link AudioDeviceInfo}.
*
* <p>The previous list of input devices is replaced and no notifications of the list of {@link
* AudioDeviceCallback} is done.
*
* <p>To add/remove devices one by one and trigger notifications for the list of {@link
* AudioDeviceCallback} please use one of the following methods {@link
* #addInputDevice(AudioDeviceInfo, boolean)}, {@link #removeInputDevice(AudioDeviceInfo,
* boolean)}.
*/
public void setInputDevices(List<AudioDeviceInfo> inputDevices) {
this.inputDevices = new ArrayList<>(inputDevices);
}
/**
* Sets the list of connected output devices represented by {@link AudioDeviceInfo}.
*
* <p>The previous list of output devices is replaced and no notifications of the list of {@link
* AudioDeviceCallback} is done.
*
* <p>To add/remove devices one by one and trigger notifications for the list of {@link
* AudioDeviceCallback} please use one of the following methods {@link
* #addOutputDevice(AudioDeviceInfo, boolean)}, {@link #removeOutputDevice(AudioDeviceInfo,
* boolean)}.
*/
public void setOutputDevices(List<AudioDeviceInfo> outputDevices) {
this.outputDevices = new ArrayList<>(outputDevices);
}
/**
* Sets the list of available communication devices represented by {@link AudioDeviceInfo}.
*
* <p>The previous list of communication devices is replaced and no notifications of the list of
* {@link AudioDeviceCallback} is done.
*
* <p>To add/remove devices one by one and trigger notifications for the list of {@link
* AudioDeviceCallback} please use one of the following methods {@link
* #addOutputDevice(AudioDeviceInfo, boolean)}, {@link #removeOutputDevice(AudioDeviceInfo,
* boolean)}.
*/
@TargetApi(VERSION_CODES.S)
public void setAvailableCommunicationDevices(
List<AudioDeviceInfo> availableCommunicationDevices) {
this.availableCommunicationDevices = new ArrayList<>(availableCommunicationDevices);
}
/**
* Adds an input {@link AudioDeviceInfo} and notifies the list of {@link AudioDeviceCallback} if
* the device was not present before and indicated by {@code notifyAudioDeviceCallbacks}.
*/
public void addInputDevice(AudioDeviceInfo inputDevice, boolean notifyAudioDeviceCallbacks) {
boolean changed =
!this.inputDevices.contains(inputDevice) && this.inputDevices.add(inputDevice);
if (changed && notifyAudioDeviceCallbacks) {
notifyAudioDeviceCallbacks(ImmutableList.of(inputDevice), /* added= */ true);
}
}
/**
* Removes an input {@link AudioDeviceInfo} and notifies the list of {@link AudioDeviceCallback}
* if the device was present before and indicated by {@code notifyAudioDeviceCallbacks}.
*/
public void removeInputDevice(AudioDeviceInfo inputDevice, boolean notifyAudioDeviceCallbacks) {
boolean changed = this.inputDevices.remove(inputDevice);
if (changed && notifyAudioDeviceCallbacks) {
notifyAudioDeviceCallbacks(ImmutableList.of(inputDevice), /* added= */ false);
}
}
/**
* Adds an output {@link AudioDeviceInfo} and notifies the list of {@link AudioDeviceCallback} if
* the device was not present before and indicated by {@code notifyAudioDeviceCallbacks}.
*/
public void addOutputDevice(AudioDeviceInfo outputDevice, boolean notifyAudioDeviceCallbacks) {
boolean changed =
!this.outputDevices.contains(outputDevice) && this.outputDevices.add(outputDevice);
if (changed && notifyAudioDeviceCallbacks) {
notifyAudioDeviceCallbacks(ImmutableList.of(outputDevice), /* added= */ true);
}
}
/**
* Removes an output {@link AudioDeviceInfo} and notifies the list of {@link AudioDeviceCallback}
* if the device was present before and indicated by {@code notifyAudioDeviceCallbacks}.
*/
public void removeOutputDevice(AudioDeviceInfo outputDevice, boolean notifyAudioDeviceCallbacks) {
boolean changed = this.outputDevices.remove(outputDevice);
if (changed && notifyAudioDeviceCallbacks) {
notifyAudioDeviceCallbacks(ImmutableList.of(outputDevice), /* added= */ false);
}
}
/**
* Adds an available communication {@link AudioDeviceInfo} and notifies the list of {@link
* AudioDeviceCallback} if the device was not present before and indicated by {@code
* notifyAudioDeviceCallbacks}.
*/
@TargetApi(VERSION_CODES.S)
public void addAvailableCommunicationDevice(
AudioDeviceInfo communicationDevice, boolean notifyAudioDeviceCallbacks) {
boolean changed =
!this.availableCommunicationDevices.contains(communicationDevice)
&& this.availableCommunicationDevices.add(communicationDevice);
if (changed && notifyAudioDeviceCallbacks) {
notifyAudioDeviceCallbacks(ImmutableList.of(communicationDevice), /* added= */ true);
}
}
/**
* Removes an available communication {@link AudioDeviceInfo} and notifies the list of {@link
* AudioDeviceCallback} if the device was present before and indicated by {@code
* notifyAudioDeviceCallbacks}.
*/
@TargetApi(VERSION_CODES.S)
public void removeAvailableCommunicationDevice(
AudioDeviceInfo communicationDevice, boolean notifyAudioDeviceCallbacks) {
boolean changed = this.availableCommunicationDevices.remove(communicationDevice);
if (changed && notifyAudioDeviceCallbacks) {
notifyAudioDeviceCallbacks(ImmutableList.of(communicationDevice), /* added= */ false);
}
}
/**
* Registers an {@link AudioDeviceCallback} object to receive notifications of changes to the set
* of connected audio devices.
*
* <p>The {@code handler} is ignored.
*
* @see #addInputDevice(AudioDeviceInfo, boolean)
* @see #addOutputDevice(AudioDeviceInfo, boolean)
* @see #addAvailableCommunicationDevice(AudioDeviceInfo, boolean)
* @see #removeInputDevice(AudioDeviceInfo, boolean)
* @see #removeOutputDevice(AudioDeviceInfo, boolean)
* @see #removeAvailableCommunicationDevice(AudioDeviceInfo, boolean)
* @see #addOutputDeviceWithDirectProfiles(AudioDeviceInfo)
* @see #removeOutputDeviceWithDirectProfiles(AudioDeviceInfo)
*/
@Implementation(minSdk = M)
protected void registerAudioDeviceCallback(AudioDeviceCallback callback, Handler handler) {
audioDeviceCallbacks.add(callback);
// indicate currently available devices as added, similarly to MSG_DEVICES_CALLBACK_REGISTERED
callback.onAudioDevicesAdded(getDevices(AudioManager.GET_DEVICES_ALL));
}
/**
* Unregisters an {@link AudioDeviceCallback} object which has been previously registered to
* receive notifications of changes to the set of connected audio devices.
*
* @see #addInputDevice(AudioDeviceInfo, boolean)
* @see #addOutputDevice(AudioDeviceInfo, boolean)
* @see #addAvailableCommunicationDevice(AudioDeviceInfo, boolean)
* @see #removeInputDevice(AudioDeviceInfo, boolean)
* @see #removeOutputDevice(AudioDeviceInfo, boolean)
* @see #removeAvailableCommunicationDevice(AudioDeviceInfo, boolean)
* @see #addOutputDeviceWithDirectProfiles(AudioDeviceInfo)
* @see #removeOutputDeviceWithDirectProfiles(AudioDeviceInfo)
*/
@Implementation(minSdk = M)
protected void unregisterAudioDeviceCallback(AudioDeviceCallback callback) {
audioDeviceCallbacks.remove(callback);
}
private void notifyAudioDeviceCallbacks(List<AudioDeviceInfo> devices, boolean added) {
AudioDeviceInfo[] devicesArray = devices.toArray(new AudioDeviceInfo[0]);
for (AudioDeviceCallback callback : audioDeviceCallbacks) {
if (added) {
callback.onAudioDevicesAdded(devicesArray);
} else {
callback.onAudioDevicesRemoved(devicesArray);
}
}
}
private List<AudioDeviceInfo> getInputDevices() {
return inputDevices;
}
private List<AudioDeviceInfo> getOutputDevices() {
return outputDevices;
}
@Implementation(minSdk = S)
protected boolean setCommunicationDevice(AudioDeviceInfo communicationDevice) {
this.communicationDevice = communicationDevice;
return true;
}
@Implementation(minSdk = S)
protected AudioDeviceInfo getCommunicationDevice() {
return communicationDevice;
}
@Implementation(minSdk = S)
protected void clearCommunicationDevice() {
this.communicationDevice = null;
}
@Implementation(minSdk = S)
protected List<AudioDeviceInfo> getAvailableCommunicationDevices() {
return availableCommunicationDevices;
}
@Implementation(minSdk = UPSIDE_DOWN_CAKE)
protected boolean isHotwordStreamSupported(boolean lookbackAudio) {
if (lookbackAudio) {
return isHotwordStreamSupportedForLookbackAudio;
}
return isHotwordStreamSupportedWithoutLookbackAudio;
}
public void setHotwordStreamSupported(boolean lookbackAudio, boolean isSupported) {
if (lookbackAudio) {
isHotwordStreamSupportedForLookbackAudio = isSupported;
} else {
isHotwordStreamSupportedWithoutLookbackAudio = isSupported;
}
}
@Implementation(minSdk = M)
public AudioDeviceInfo[] getDevices(int flags) {
List<AudioDeviceInfo> result = new ArrayList<>();
if ((flags & AudioManager.GET_DEVICES_INPUTS) == AudioManager.GET_DEVICES_INPUTS) {
result.addAll(getInputDevices());
}
if ((flags & AudioManager.GET_DEVICES_OUTPUTS) == AudioManager.GET_DEVICES_OUTPUTS) {
result.addAll(getOutputDevices());
}
return result.toArray(new AudioDeviceInfo[0]);
}
/**
* Sets active playback configurations that will be served by {@link
* AudioManager#getActivePlaybackConfigurations}.
*
* <p>Note that there is no public {@link AudioPlaybackConfiguration} constructor, so the
* configurations returned are specified by their audio attributes only.
*/
@TargetApi(VERSION_CODES.O)
public void setActivePlaybackConfigurationsFor(List<AudioAttributes> audioAttributes) {
setActivePlaybackConfigurationsFor(audioAttributes, /* notifyCallbackListeners= */ false);
}
/**
* Same as {@link #setActivePlaybackConfigurationsFor(List)}, but also notifies callbacks if
* notifyCallbackListeners is true.
*/
@TargetApi(VERSION_CODES.O)
public void setActivePlaybackConfigurationsFor(
List<AudioAttributes> audioAttributes, boolean notifyCallbackListeners) {
if (RuntimeEnvironment.getApiLevel() < O) {
throw new UnsupportedOperationException(
"setActivePlaybackConfigurationsFor is not supported on API "
+ RuntimeEnvironment.getApiLevel());
}
activePlaybackConfigurations = new ArrayList<>(audioAttributes.size());
for (AudioAttributes audioAttribute : audioAttributes) {
AudioPlaybackConfiguration configuration = createAudioPlaybackConfiguration(audioAttribute);
activePlaybackConfigurations.add(configuration);
}
if (notifyCallbackListeners) {
for (AudioManager.AudioPlaybackCallback callback : audioPlaybackCallbacks) {
callback.onPlaybackConfigChanged(activePlaybackConfigurations);
}
}
}
protected AudioPlaybackConfiguration createAudioPlaybackConfiguration(
AudioAttributes audioAttributes) {
// use reflection to call package private APIs
if (RuntimeEnvironment.getApiLevel() >= S) {
PlayerBase.PlayerIdCard playerIdCard =
ReflectionHelpers.callConstructor(
PlayerBase.PlayerIdCard.class,
ReflectionHelpers.ClassParameter.from(int.class, 0), /* type */
ReflectionHelpers.ClassParameter.from(AudioAttributes.class, audioAttributes),
ReflectionHelpers.ClassParameter.from(IPlayer.class, null),
ReflectionHelpers.ClassParameter.from(int.class, 0) /* sessionId */);
AudioPlaybackConfiguration config =
ReflectionHelpers.callConstructor(
AudioPlaybackConfiguration.class,
ReflectionHelpers.ClassParameter.from(PlayerBase.PlayerIdCard.class, playerIdCard),
ReflectionHelpers.ClassParameter.from(int.class, 0), /* piid */
ReflectionHelpers.ClassParameter.from(int.class, 0), /* uid */
ReflectionHelpers.ClassParameter.from(int.class, 0) /* pid */);
ReflectionHelpers.setField(
config, "mPlayerState", AudioPlaybackConfiguration.PLAYER_STATE_STARTED);
return config;
} else {
PlayerBase.PlayerIdCard playerIdCard =
ReflectionHelpers.callConstructor(
PlayerBase.PlayerIdCard.class,
from(int.class, 0), /* type */
from(AudioAttributes.class, audioAttributes),
from(IPlayer.class, null));
AudioPlaybackConfiguration config =
ReflectionHelpers.callConstructor(
AudioPlaybackConfiguration.class,
from(PlayerBase.PlayerIdCard.class, playerIdCard),
from(int.class, 0), /* piid */
from(int.class, 0), /* uid */
from(int.class, 0) /* pid */);
ReflectionHelpers.setField(
config, "mPlayerState", AudioPlaybackConfiguration.PLAYER_STATE_STARTED);
return config;
}
}
public void setIsMusicActive(boolean isMusicActive) {
this.isMusicActive = isMusicActive;
}
public AudioFocusRequest getLastAudioFocusRequest() {
return lastAudioFocusRequest;
}
public void setNextFocusRequestResponse(int nextResponseValue) {
this.nextResponseValue = nextResponseValue;
}
public AudioManager.OnAudioFocusChangeListener getLastAbandonedAudioFocusListener() {
return lastAbandonedAudioFocusListener;
}
public android.media.AudioFocusRequest getLastAbandonedAudioFocusRequest() {
return lastAbandonedAudioFocusRequest;
}
/**
* Returns list of active recording configurations that was set by {@link
* #setActiveRecordingConfigurations} or empty list otherwise.
*/
@Implementation(minSdk = N)
protected List<AudioRecordingConfiguration> getActiveRecordingConfigurations() {
return activeRecordingConfigurations;
}
/**
* Registers callback that will receive changes made to the list of active recording
* configurations by {@link setActiveRecordingConfigurations}.
*/
@Implementation(minSdk = N)
protected void registerAudioRecordingCallback(
AudioManager.AudioRecordingCallback cb, Handler handler) {
audioRecordingCallbacks.add(cb);
}
/** Unregisters callback listening to changes made to list of active recording configurations. */
@Implementation(minSdk = N)
protected void unregisterAudioRecordingCallback(AudioManager.AudioRecordingCallback cb) {
audioRecordingCallbacks.remove(cb);
}
/**
* Sets active recording configurations that will be served by {@link
* AudioManager#getActiveRecordingConfigurations} and notifies callback listeners about that
* change.
*/
public void setActiveRecordingConfigurations(
List<AudioRecordingConfiguration> activeRecordingConfigurations,
boolean notifyCallbackListeners) {
this.activeRecordingConfigurations = new ArrayList<>(activeRecordingConfigurations);
if (notifyCallbackListeners) {
for (AudioManager.AudioRecordingCallback callback : audioRecordingCallbacks) {
callback.onRecordingConfigChanged(this.activeRecordingConfigurations);
}
}
}
/**
* Creates simple active recording configuration. The resulting configuration will return {@code
* null} for {@link android.media.AudioRecordingConfiguration#getAudioDevice}.
*/
public AudioRecordingConfiguration createActiveRecordingConfiguration(
int sessionId, int audioSource, String clientPackageName) {
Parcel p = Parcel.obtain();
p.writeInt(sessionId); // mSessionId
p.writeInt(audioSource); // mClientSource
writeMono16BitAudioFormatToParcel(p); // mClientFormat
writeMono16BitAudioFormatToParcel(p); // mDeviceFormat
p.writeInt(INVALID_PATCH_HANDLE); // mPatchHandle
p.writeString(clientPackageName); // mClientPackageName
p.writeInt(0); // mClientUid
p.setDataPosition(0);
AudioRecordingConfiguration configuration =
AudioRecordingConfiguration.CREATOR.createFromParcel(p);
p.recycle();
return configuration;
}
/**
* Registers an {@link AudioPolicy} to allow that policy to control audio routing and audio focus.
*
* <p>Note: this implementation does NOT ensure that we have the permissions necessary to register
* the given {@link AudioPolicy}.
*
* @return {@link AudioManager.ERROR} if the given policy has already been registered, and {@link
* AudioManager.SUCCESS} otherwise.
*/
@HiddenApi
@Implementation(minSdk = P)
@RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING)
protected int registerAudioPolicy(
@NonNull @ClassName(value = "android.media.audiopolicy.AudioPolicy") Object audioPolicy) {
Preconditions.checkNotNull(audioPolicy, "Illegal null AudioPolicy argument");
AudioPolicy policy = (AudioPolicy) audioPolicy;
String id = getIdForAudioPolicy(audioPolicy);
if (registeredAudioPolicies.containsKey(id)) {
return AudioManager.ERROR;
}
registeredAudioPolicies.put(id, policy);
policy.setRegistration(id);
return AudioManager.SUCCESS;
}
@HiddenApi
@Implementation(minSdk = Q)
protected void unregisterAudioPolicy(
@NonNull @ClassName(value = "android.media.audiopolicy.AudioPolicy") Object audioPolicy) {
Preconditions.checkNotNull(audioPolicy, "Illegal null AudioPolicy argument");
AudioPolicy policy = (AudioPolicy) audioPolicy;
registeredAudioPolicies.remove(getIdForAudioPolicy(policy));
policy.setRegistration(null);
}
/**
* Returns true if at least one audio policy is registered with this manager, and false otherwise.
*/
public boolean isAnyAudioPolicyRegistered() {
return !registeredAudioPolicies.isEmpty();
}
/**
* Returns the list of profiles supported for direct playback.
*
* <p>In this shadow-implementation the list returned are profiles set through {@link
* #addOutputDeviceWithDirectProfiles(AudioDeviceInfo)}, {@link
* #removeOutputDeviceWithDirectProfiles(AudioDeviceInfo)}.
*/
@Implementation(minSdk = TIRAMISU)
@NonNull
protected List<AudioProfile> getDirectProfilesForAttributes(@NonNull AudioAttributes attributes) {
ImmutableSet.Builder<AudioProfile> audioProfiles = new ImmutableSet.Builder<>();
for (int i = 0; i < outputDevicesWithDirectProfiles.size(); i++) {
audioProfiles.addAll(outputDevicesWithDirectProfiles.get(i).getAudioProfiles());
}
return new ArrayList<>(audioProfiles.build());
}
/**
* Adds an output {@link AudioDeviceInfo device} with direct profiles and notifies the list of
* {@link AudioDeviceCallback} if the device was not present before.
*/
public void addOutputDeviceWithDirectProfiles(AudioDeviceInfo outputDevice) {
boolean changed =
!this.outputDevicesWithDirectProfiles.contains(outputDevice)
&& this.outputDevicesWithDirectProfiles.add(outputDevice);
if (changed) {
notifyAudioDeviceCallbacks(ImmutableList.of(outputDevice), /* added= */ true);
}
}
/**
* Removes an output {@link AudioDeviceInfo device} with direct profiles and notifies the list of
* {@link AudioDeviceCallback} if the device was present before.
*/
public void removeOutputDeviceWithDirectProfiles(AudioDeviceInfo outputDevice) {
boolean changed = this.outputDevicesWithDirectProfiles.remove(outputDevice);
if (changed) {
notifyAudioDeviceCallbacks(ImmutableList.of(outputDevice), /* added= */ false);
}
}
/**
* Provides a mock like interface for the {@link AudioManager#generateAudioSessionId} method by
* returning positive distinct values, or {@link AudioManager#ERROR} if all possible values have
* already been returned.
*/
@Implementation(minSdk = LOLLIPOP)
protected int generateAudioSessionId() {
if (audioSessionIdCounter < 0) {
return AudioManager.ERROR;
}
return audioSessionIdCounter++;
}
private static String getIdForAudioPolicy(@NonNull Object audioPolicy) {
return Integer.toString(System.identityHashCode(audioPolicy));
}
private static void writeMono16BitAudioFormatToParcel(Parcel p) {
p.writeInt(
AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_ENCODING
+ AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE
+ AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK); // mPropertySetMask
p.writeInt(AudioFormat.ENCODING_PCM_16BIT); // mEncoding
p.writeInt(16000); // mSampleRate
p.writeInt(AudioFormat.CHANNEL_OUT_MONO); // mChannelMask
p.writeInt(0); // mChannelIndexMask
}
/**
* Sends a simulated key event for a media button.
*
* <p>Instead of sending the media event to the media system service, from where it would be
* routed to a media app, this shadow method only records the events to be verified through {@link
* #getDispatchedMediaKeyEvents()}.
*/
@Implementation
protected void dispatchMediaKeyEvent(KeyEvent keyEvent) {
if (keyEvent == null) {
throw new NullPointerException("keyEvent is null");
}
dispatchedMediaKeyEvents.add(keyEvent);
}