-
Notifications
You must be signed in to change notification settings - Fork 378
/
Player.java
3526 lines (3190 loc) · 130 KB
/
Player.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
/*
* Copyright (C) 2017 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.
*/
package androidx.media3.common;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import android.os.Bundle;
import android.os.Looper;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import androidx.annotation.FloatRange;
import androidx.annotation.IntDef;
import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.media3.common.text.Cue;
import androidx.media3.common.text.CueGroup;
import androidx.media3.common.util.Size;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import com.google.common.base.Objects;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
/**
* A media player interface defining high-level functionality, such as the ability to play, pause,
* seek and query properties of the currently playing media.
*
* <h2>Player features and usage</h2>
*
* <p>Some important properties of media players that implement this interface are:
*
* <ul>
* <li>All methods must be called from a single {@linkplain #getApplicationLooper() application
* thread} unless indicated otherwise. Callbacks in registered listeners are called on the
* same thread.
* <li>The available functionality can be limited. Player instances provide a set of {@link
* #getAvailableCommands() available commands} to signal feature support and users of the
* interface must only call methods if the corresponding {@link Command} is available.
* <li>Users can register {@link Player.Listener} callbacks that get informed about state changes.
* <li>Player instances need to update the visible state immediately after each method call, even
* if the actual changes are handled on background threads or even other devices. This
* simplifies the usage for callers of methods as no asynchronous handling needs to be
* considered.
* <li>Player instances can provide playlist operations, like 'set', 'add', 'remove', 'move' or
* 'replace' of {@link MediaItem} instances. The player can also support {@linkplain
* RepeatMode repeat modes} and shuffling within this playlist. The player provides a {@link
* Timeline} representing the structure of the playlist and all its items, which can be
* obtained by calling {@link #getCurrentTimeline()}
* <li>Player instances can provide seeking within the currently playing item and to other items,
* using the various {@code seek...} methods.
* <li>Player instances can provide {@link Tracks} defining the currently available and selected
* tracks, which can be obtained by calling {@link #getCurrentTracks()}. Users can also modify
* track selection behavior by setting {@link TrackSelectionParameters} with {@link
* #setTrackSelectionParameters}.
* <li>Player instances can provide {@link MediaMetadata} about the currently playing item, which
* can be obtained by calling {@link #getMediaMetadata()}.
* <li>Player instances can provide information about ads in its media structure, for example via
* {@link #isPlayingAd()}.
* <li>Player instances can accept different types of video outputs, like {@link
* #setVideoSurfaceView SurfaceView} or {@link #setVideoTextureView TextureView} for video
* rendering.
* <li>Player instances can handle {@linkplain #setPlaybackSpeed playback speed}, {@linkplain
* #getAudioAttributes audio attributes}, and {@linkplain #setVolume audio volume}.
* <li>Player instances can provide information about the {@linkplain #getDeviceInfo playback
* device}, which may be remote, and allow to change the device's volume.
* </ul>
*
* <h2>API stability guarantees</h2>
*
* <p>The majority of the Player interface and its related classes are part of the stable API that
* guarantees backwards-compatibility for users of the API. Only more advances use cases may need to
* rely on {@link UnstableApi} classes and methods that are subject to incompatible changes or even
* removal in a future release. Implementors of the Player interface are not covered by these API
* stability guarantees.
*
* <h2>Player state</h2>
*
* <p>Users can listen to state changes by adding a {@link Player.Listener} with {@link
* #addListener}.
*
* <p>The main elements of the overall player state are:
*
* <ul>
* <li>Playlist
* <ul>
* <li>{@link MediaItem} instances can be added with methods like {@link #setMediaItem} to
* define what the player will be playing.
* <li>The current playlist can be obtained via {@link #getCurrentTimeline} and convenience
* methods like {@link #getMediaItemCount} or {@link #getCurrentMediaItem}.
* <li>With an empty playlist, the player can only be in {@link #STATE_IDLE} or {@link
* #STATE_ENDED}.
* </ul>
* <li>Playback state
* <ul>
* <li>{@link #STATE_IDLE}: This is the initial state, the state when the player is
* {@linkplain #stop stopped}, and when playback {@linkplain #getPlayerError failed}.
* The player will hold only limited resources in this state. {@link #prepare} must be
* called to transition away from this state.
* <li>{@link #STATE_BUFFERING}: The player is not able to immediately play from its current
* position. This mostly happens because more data needs to be loaded.
* <li>{@link #STATE_READY}: The player is able to immediately play from its current
* position.
* <li>{@link #STATE_ENDED}: The player finished playing all media, or there is no media to
* play.
* </ul>
* <li>Play/Pause, playback suppression and isPlaying
* <ul>
* <li>{@linkplain #getPlayWhenReady() playWhenReady}: Indicates the user intention to play.
* It can be set with {@link #play} or {@link #pause}.
* <li>{@linkplain #getPlaybackSuppressionReason() playback suppression}: Defines a reason
* for which playback will be suppressed even if {@linkplain #getPlayWhenReady()
* playWhenReady} is {@code true}.
* <li>{@link #isPlaying()}: Whether the player is playing (that is, its position is
* advancing and media is being presented). This will only be {@code true} if playback
* state is {@link #STATE_READY}, {@linkplain #getPlayWhenReady() playWhenReady} is
* {@code true}, and playback is not suppressed.
* </ul>
* <li>Playback position
* <ul>
* <li>{@linkplain #getCurrentMediaItemIndex() media item index}: The index in the playlist.
* <li>{@linkplain #isPlayingAd() ad insertion}: Whether an inserted ad is playing and which
* {@linkplain #getCurrentAdGroupIndex() ad group index} and {@linkplain
* #getCurrentAdIndexInAdGroup() ad index in the group} it belongs to
* <li>{@linkplain #getCurrentPosition() current position}: The current position of the
* playback. This is the same as the {@linkplain #getContentPosition() content position}
* unless an ad is playing, where this indicates the position in the inserted ad.
* </ul>
* </ul>
*
* <p>Note that there are no callbacks for normal playback progression, only for {@linkplain
* Listener#onMediaItemTransition transitions between media items} and other {@linkplain
* Listener#onPositionDiscontinuity position discontinuities}. Code that needs to monitor playback
* progress (for example, an UI progress bar) should query the current position in appropriate
* intervals.
*
* <h2>Implementing the Player interface</h2>
*
* <p>Implementing the Player interface is complex, as the interface includes many convenience
* methods that need to provide a consistent state and behavior, requires correct handling of
* listeners and available commands, and expects immediate state changes even if methods are
* internally handled asynchronously. For this reason, implementations are advised to inherit {@link
* SimpleBasePlayer} that handles all of these complexities and provides a simpler integration point
* for implementors of the interface.
*/
public interface Player {
/** A set of {@linkplain Event events}. */
final class Events {
private final FlagSet flags;
/**
* Creates an instance.
*
* @param flags The {@link FlagSet} containing the {@linkplain Event events}.
*/
@UnstableApi
public Events(FlagSet flags) {
this.flags = flags;
}
/**
* Returns whether the given {@link Event} occurred.
*
* @param event The {@link Event}.
* @return Whether the {@link Event} occurred.
*/
public boolean contains(@Event int event) {
return flags.contains(event);
}
/**
* Returns whether any of the given {@linkplain Event events} occurred.
*
* @param events The {@linkplain Event events}.
* @return Whether any of the {@linkplain Event events} occurred.
*/
public boolean containsAny(@Event int... events) {
return flags.containsAny(events);
}
/** Returns the number of events in the set. */
public int size() {
return flags.size();
}
/**
* Returns the {@link Event} at the given index.
*
* <p>Although index-based access is possible, it doesn't imply a particular order of these
* events.
*
* @param index The index. Must be between 0 (inclusive) and {@link #size()} (exclusive).
* @return The {@link Event} at the given index.
* @throws IndexOutOfBoundsException If index is outside the allowed range.
*/
public @Event int get(int index) {
return flags.get(index);
}
@Override
public int hashCode() {
return flags.hashCode();
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Events)) {
return false;
}
Events other = (Events) obj;
return flags.equals(other.flags);
}
}
/** Position info describing a playback position involved in a discontinuity. */
final class PositionInfo {
/**
* The UID of the window, or {@code null} if the timeline is {@link Timeline#isEmpty() empty}.
*/
@Nullable public final Object windowUid;
/**
* @deprecated Use {@link #mediaItemIndex} instead.
*/
@UnstableApi @Deprecated public final int windowIndex;
/** The media item index. */
public final int mediaItemIndex;
/** The media item, or {@code null} if the timeline is {@link Timeline#isEmpty() empty}. */
@UnstableApi @Nullable public final MediaItem mediaItem;
/**
* The UID of the period, or {@code null} if the timeline is {@link Timeline#isEmpty() empty}.
*/
@Nullable public final Object periodUid;
/** The period index. */
public final int periodIndex;
/** The playback position, in milliseconds. */
public final long positionMs;
/**
* The content position, in milliseconds.
*
* <p>If {@link #adGroupIndex} is {@link C#INDEX_UNSET}, this is the same as {@link
* #positionMs}.
*/
public final long contentPositionMs;
/**
* The ad group index if the playback position is within an ad, {@link C#INDEX_UNSET} otherwise.
*/
public final int adGroupIndex;
/**
* The index of the ad within the ad group if the playback position is within an ad, {@link
* C#INDEX_UNSET} otherwise.
*/
public final int adIndexInAdGroup;
/**
* @deprecated Use {@link #PositionInfo(Object, int, MediaItem, Object, int, long, long, int,
* int)} instead.
*/
@Deprecated
@UnstableApi
public PositionInfo(
@Nullable Object windowUid,
int mediaItemIndex,
@Nullable Object periodUid,
int periodIndex,
long positionMs,
long contentPositionMs,
int adGroupIndex,
int adIndexInAdGroup) {
this(
windowUid,
mediaItemIndex,
MediaItem.EMPTY,
periodUid,
periodIndex,
positionMs,
contentPositionMs,
adGroupIndex,
adIndexInAdGroup);
}
/** Creates an instance. */
@UnstableApi
@SuppressWarnings("deprecation") // Setting deprecated windowIndex field
public PositionInfo(
@Nullable Object windowUid,
int mediaItemIndex,
@Nullable MediaItem mediaItem,
@Nullable Object periodUid,
int periodIndex,
long positionMs,
long contentPositionMs,
int adGroupIndex,
int adIndexInAdGroup) {
this.windowUid = windowUid;
this.windowIndex = mediaItemIndex;
this.mediaItemIndex = mediaItemIndex;
this.mediaItem = mediaItem;
this.periodUid = periodUid;
this.periodIndex = periodIndex;
this.positionMs = positionMs;
this.contentPositionMs = contentPositionMs;
this.adGroupIndex = adGroupIndex;
this.adIndexInAdGroup = adIndexInAdGroup;
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PositionInfo that = (PositionInfo) o;
return equalsForBundling(that)
&& Objects.equal(windowUid, that.windowUid)
&& Objects.equal(periodUid, that.periodUid);
}
@Override
public int hashCode() {
return Objects.hashCode(
windowUid,
mediaItemIndex,
mediaItem,
periodUid,
periodIndex,
positionMs,
contentPositionMs,
adGroupIndex,
adIndexInAdGroup);
}
/**
* Returns whether this position info and the other position info would result in the same
* {@link #toBundle() Bundle}.
*/
@UnstableApi
public boolean equalsForBundling(PositionInfo other) {
return mediaItemIndex == other.mediaItemIndex
&& periodIndex == other.periodIndex
&& positionMs == other.positionMs
&& contentPositionMs == other.contentPositionMs
&& adGroupIndex == other.adGroupIndex
&& adIndexInAdGroup == other.adIndexInAdGroup
&& Objects.equal(mediaItem, other.mediaItem);
}
@VisibleForTesting static final String FIELD_MEDIA_ITEM_INDEX = Util.intToStringMaxRadix(0);
private static final String FIELD_MEDIA_ITEM = Util.intToStringMaxRadix(1);
@VisibleForTesting static final String FIELD_PERIOD_INDEX = Util.intToStringMaxRadix(2);
@VisibleForTesting static final String FIELD_POSITION_MS = Util.intToStringMaxRadix(3);
@VisibleForTesting static final String FIELD_CONTENT_POSITION_MS = Util.intToStringMaxRadix(4);
private static final String FIELD_AD_GROUP_INDEX = Util.intToStringMaxRadix(5);
private static final String FIELD_AD_INDEX_IN_AD_GROUP = Util.intToStringMaxRadix(6);
/**
* Returns a copy of this position info, filtered by the specified available commands.
*
* <p>The filtered fields are reset to their default values.
*
* <p>The return value may be the same object if nothing is filtered.
*
* @param canAccessCurrentMediaItem Whether {@link Player#COMMAND_GET_CURRENT_MEDIA_ITEM} is
* available.
* @param canAccessTimeline Whether {@link Player#COMMAND_GET_TIMELINE} is available.
* @return The filtered position info.
*/
@UnstableApi
public PositionInfo filterByAvailableCommands(
boolean canAccessCurrentMediaItem, boolean canAccessTimeline) {
if (canAccessCurrentMediaItem && canAccessTimeline) {
return this;
}
return new PositionInfo(
windowUid,
canAccessTimeline ? mediaItemIndex : 0,
canAccessCurrentMediaItem ? mediaItem : null,
periodUid,
canAccessTimeline ? periodIndex : 0,
canAccessCurrentMediaItem ? positionMs : 0,
canAccessCurrentMediaItem ? contentPositionMs : 0,
canAccessCurrentMediaItem ? adGroupIndex : C.INDEX_UNSET,
canAccessCurrentMediaItem ? adIndexInAdGroup : C.INDEX_UNSET);
}
/**
* Returns a {@link Bundle} representing the information stored in this object.
*
* <p>It omits the {@link #windowUid} and {@link #periodUid} fields. The {@link #windowUid} and
* {@link #periodUid} of an instance restored by {@link #fromBundle(Bundle)} will always be
* {@code null}.
*
* @param controllerInterfaceVersion The interface version of the media controller this Bundle
* will be sent to.
*/
@UnstableApi
public Bundle toBundle(int controllerInterfaceVersion) {
Bundle bundle = new Bundle();
if (controllerInterfaceVersion < 3 || mediaItemIndex != 0) {
bundle.putInt(FIELD_MEDIA_ITEM_INDEX, mediaItemIndex);
}
if (mediaItem != null) {
bundle.putBundle(FIELD_MEDIA_ITEM, mediaItem.toBundle());
}
if (controllerInterfaceVersion < 3 || periodIndex != 0) {
bundle.putInt(FIELD_PERIOD_INDEX, periodIndex);
}
if (controllerInterfaceVersion < 3 || positionMs != 0) {
bundle.putLong(FIELD_POSITION_MS, positionMs);
}
if (controllerInterfaceVersion < 3 || contentPositionMs != 0) {
bundle.putLong(FIELD_CONTENT_POSITION_MS, contentPositionMs);
}
if (adGroupIndex != C.INDEX_UNSET) {
bundle.putInt(FIELD_AD_GROUP_INDEX, adGroupIndex);
}
if (adIndexInAdGroup != C.INDEX_UNSET) {
bundle.putInt(FIELD_AD_INDEX_IN_AD_GROUP, adIndexInAdGroup);
}
return bundle;
}
/**
* @deprecated Use {@link #toBundle(int)} instead.
*/
@UnstableApi
@Deprecated
public Bundle toBundle() {
return toBundle(Integer.MAX_VALUE);
}
/** Restores a {@code PositionInfo} from a {@link Bundle}. */
@UnstableApi
public static PositionInfo fromBundle(Bundle bundle) {
int mediaItemIndex = bundle.getInt(FIELD_MEDIA_ITEM_INDEX, /* defaultValue= */ 0);
@Nullable Bundle mediaItemBundle = bundle.getBundle(FIELD_MEDIA_ITEM);
@Nullable
MediaItem mediaItem = mediaItemBundle == null ? null : MediaItem.fromBundle(mediaItemBundle);
int periodIndex = bundle.getInt(FIELD_PERIOD_INDEX, /* defaultValue= */ 0);
long positionMs = bundle.getLong(FIELD_POSITION_MS, /* defaultValue= */ 0);
long contentPositionMs = bundle.getLong(FIELD_CONTENT_POSITION_MS, /* defaultValue= */ 0);
int adGroupIndex = bundle.getInt(FIELD_AD_GROUP_INDEX, /* defaultValue= */ C.INDEX_UNSET);
int adIndexInAdGroup =
bundle.getInt(FIELD_AD_INDEX_IN_AD_GROUP, /* defaultValue= */ C.INDEX_UNSET);
return new PositionInfo(
/* windowUid= */ null,
mediaItemIndex,
mediaItem,
/* periodUid= */ null,
periodIndex,
positionMs,
contentPositionMs,
adGroupIndex,
adIndexInAdGroup);
}
}
/**
* A set of {@linkplain Command commands}.
*
* <p>Instances are immutable.
*/
final class Commands {
/** A builder for {@link Commands} instances. */
@UnstableApi
public static final class Builder {
@SuppressWarnings("deprecation") // Includes deprecated commands
private static final @Command int[] SUPPORTED_COMMANDS = {
COMMAND_PLAY_PAUSE,
COMMAND_PREPARE,
COMMAND_STOP,
COMMAND_SEEK_TO_DEFAULT_POSITION,
COMMAND_SEEK_IN_CURRENT_MEDIA_ITEM,
COMMAND_SEEK_TO_PREVIOUS_MEDIA_ITEM,
COMMAND_SEEK_TO_PREVIOUS,
COMMAND_SEEK_TO_NEXT_MEDIA_ITEM,
COMMAND_SEEK_TO_NEXT,
COMMAND_SEEK_TO_MEDIA_ITEM,
COMMAND_SEEK_BACK,
COMMAND_SEEK_FORWARD,
COMMAND_SET_SPEED_AND_PITCH,
COMMAND_SET_SHUFFLE_MODE,
COMMAND_SET_REPEAT_MODE,
COMMAND_GET_CURRENT_MEDIA_ITEM,
COMMAND_GET_TIMELINE,
COMMAND_GET_METADATA,
COMMAND_SET_PLAYLIST_METADATA,
COMMAND_SET_MEDIA_ITEM,
COMMAND_CHANGE_MEDIA_ITEMS,
COMMAND_GET_AUDIO_ATTRIBUTES,
COMMAND_GET_VOLUME,
COMMAND_GET_DEVICE_VOLUME,
COMMAND_SET_VOLUME,
COMMAND_SET_DEVICE_VOLUME,
COMMAND_SET_DEVICE_VOLUME_WITH_FLAGS,
COMMAND_ADJUST_DEVICE_VOLUME,
COMMAND_ADJUST_DEVICE_VOLUME_WITH_FLAGS,
COMMAND_SET_AUDIO_ATTRIBUTES,
COMMAND_SET_VIDEO_SURFACE,
COMMAND_GET_TEXT,
COMMAND_SET_TRACK_SELECTION_PARAMETERS,
COMMAND_GET_TRACKS,
COMMAND_RELEASE
};
private final FlagSet.Builder flagsBuilder;
/** Creates a builder. */
public Builder() {
flagsBuilder = new FlagSet.Builder();
}
private Builder(Commands commands) {
flagsBuilder = new FlagSet.Builder();
flagsBuilder.addAll(commands.flags);
}
/**
* Adds a {@link Command}.
*
* @param command A {@link Command}.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder add(@Command int command) {
flagsBuilder.add(command);
return this;
}
/**
* Adds a {@link Command} if the provided condition is true. Does nothing otherwise.
*
* @param command A {@link Command}.
* @param condition A condition.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder addIf(@Command int command, boolean condition) {
flagsBuilder.addIf(command, condition);
return this;
}
/**
* Adds {@linkplain Command commands}.
*
* @param commands The {@linkplain Command commands} to add.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder addAll(@Command int... commands) {
flagsBuilder.addAll(commands);
return this;
}
/**
* Adds {@link Commands}.
*
* @param commands The set of {@linkplain Command commands} to add.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder addAll(Commands commands) {
flagsBuilder.addAll(commands.flags);
return this;
}
/**
* Adds all existing {@linkplain Command commands}.
*
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder addAllCommands() {
flagsBuilder.addAll(SUPPORTED_COMMANDS);
return this;
}
/**
* Removes a {@link Command}.
*
* @param command A {@link Command}.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder remove(@Command int command) {
flagsBuilder.remove(command);
return this;
}
/**
* Removes a {@link Command} if the provided condition is true. Does nothing otherwise.
*
* @param command A {@link Command}.
* @param condition A condition.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder removeIf(@Command int command, boolean condition) {
flagsBuilder.removeIf(command, condition);
return this;
}
/**
* Removes {@linkplain Command commands}.
*
* @param commands The {@linkplain Command commands} to remove.
* @return This builder.
* @throws IllegalStateException If {@link #build()} has already been called.
*/
@CanIgnoreReturnValue
public Builder removeAll(@Command int... commands) {
flagsBuilder.removeAll(commands);
return this;
}
/**
* Builds a {@link Commands} instance.
*
* @throws IllegalStateException If this method has already been called.
*/
public Commands build() {
return new Commands(flagsBuilder.build());
}
}
/** An empty set of commands. */
public static final Commands EMPTY = new Builder().build();
private final FlagSet flags;
private Commands(FlagSet flags) {
this.flags = flags;
}
/** Returns a {@link Builder} initialized with the values of this instance. */
@UnstableApi
public Builder buildUpon() {
return new Builder(this);
}
/** Returns whether the set of commands contains the specified {@link Command}. */
public boolean contains(@Command int command) {
return flags.contains(command);
}
/** Returns whether the set of commands contains at least one of the given {@code commands}. */
public boolean containsAny(@Command int... commands) {
return flags.containsAny(commands);
}
/** Returns the number of commands in this set. */
public int size() {
return flags.size();
}
/**
* Returns the {@link Command} at the given index.
*
* @param index The index. Must be between 0 (inclusive) and {@link #size()} (exclusive).
* @return The {@link Command} at the given index.
* @throws IndexOutOfBoundsException If index is outside the allowed range.
*/
public @Command int get(int index) {
return flags.get(index);
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Commands)) {
return false;
}
Commands commands = (Commands) obj;
return flags.equals(commands.flags);
}
@Override
public int hashCode() {
return flags.hashCode();
}
private static final String FIELD_COMMANDS = Util.intToStringMaxRadix(0);
@UnstableApi
public Bundle toBundle() {
Bundle bundle = new Bundle();
ArrayList<Integer> commandsBundle = new ArrayList<>();
for (int i = 0; i < flags.size(); i++) {
commandsBundle.add(flags.get(i));
}
bundle.putIntegerArrayList(FIELD_COMMANDS, commandsBundle);
return bundle;
}
/** Restores a {@code Commands} from a {@link Bundle}. */
@UnstableApi
public static Commands fromBundle(Bundle bundle) {
@Nullable ArrayList<Integer> commands = bundle.getIntegerArrayList(FIELD_COMMANDS);
if (commands == null) {
return Commands.EMPTY;
}
Builder builder = new Builder();
for (int i = 0; i < commands.size(); i++) {
builder.add(commands.get(i));
}
return builder.build();
}
}
/**
* Listener for changes in a {@link Player}.
*
* <p>All methods have no-op default implementations to allow selective overrides.
*
* <p>If the return value of a {@link Player} getter changes due to a change in {@linkplain
* #onAvailableCommandsChanged(Commands) command availability}, the corresponding listener
* method(s) will be invoked. If the return value of a {@link Player} getter does not change
* because the corresponding command is {@linkplain #onAvailableCommandsChanged(Commands) not
* available}, the corresponding listener method will not be invoked.
*/
interface Listener {
/**
* Called when one or more player states changed.
*
* <p>State changes and events that happen within one {@link Looper} message queue iteration are
* reported together and only after all individual callbacks were triggered.
*
* <p>Listeners should prefer this method over individual callbacks in the following cases:
*
* <ul>
* <li>They intend to trigger the same logic for multiple events (e.g. when updating a UI for
* both {@link #onPlaybackStateChanged(int)} and {@link #onPlayWhenReadyChanged(boolean,
* int)}).
* <li>They need access to the {@link Player} object to trigger further events (e.g. to call
* {@link Player#seekTo(long)} after a {@link #onMediaItemTransition(MediaItem, int)}).
* <li>They intend to use multiple state values together or in combination with {@link Player}
* getter methods. For example using {@link #getCurrentMediaItemIndex()} with the {@code
* timeline} provided in {@link #onTimelineChanged(Timeline, int)} is only safe from
* within this method.
* <li>They are interested in events that logically happened together (e.g {@link
* #onPlaybackStateChanged(int)} to {@link #STATE_BUFFERING} because of {@link
* #onMediaItemTransition(MediaItem, int)}).
* </ul>
*
* @param player The {@link Player} whose state changed. Use the getters to obtain the latest
* states.
* @param events The {@link Events} that happened in this iteration, indicating which player
* states changed.
*/
default void onEvents(Player player, Events events) {}
/**
* Called when the value of {@link Player#getCurrentTimeline()} changes.
*
* <p>Note that the current {@link MediaItem} or playback position may change as a result of a
* timeline change. If playback can't continue smoothly because of this timeline change, a
* separate {@link #onPositionDiscontinuity(PositionInfo, PositionInfo, int)} callback will be
* triggered.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param timeline The latest timeline. Never null, but may be empty.
* @param reason The {@link TimelineChangeReason} responsible for this timeline change.
*/
default void onTimelineChanged(Timeline timeline, @TimelineChangeReason int reason) {}
/**
* Called when playback transitions to a media item or starts repeating a media item according
* to the current {@link #getRepeatMode() repeat mode}.
*
* <p>Note that this callback is also called when the value of {@link #getCurrentTimeline()}
* becomes non-empty or empty.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param mediaItem The {@link MediaItem}. May be null if the playlist becomes empty.
* @param reason The reason for the transition.
*/
default void onMediaItemTransition(
@Nullable MediaItem mediaItem, @MediaItemTransitionReason int reason) {}
/**
* Called when the value of {@link Player#getCurrentTracks()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param tracks The available tracks information. Never null, but may be of length zero.
*/
default void onTracksChanged(Tracks tracks) {}
/**
* Called when the value of {@link Player#getMediaMetadata()} changes.
*
* <p>This method may be called multiple times in quick succession.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param mediaMetadata The combined {@link MediaMetadata}.
*/
default void onMediaMetadataChanged(MediaMetadata mediaMetadata) {}
/**
* Called when the value of {@link Player#getPlaylistMetadata()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*/
default void onPlaylistMetadataChanged(MediaMetadata mediaMetadata) {}
/**
* Called when the player starts or stops loading the source.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param isLoading Whether the source is currently being loaded.
*/
default void onIsLoadingChanged(boolean isLoading) {}
/**
* @deprecated Use {@link #onIsLoadingChanged(boolean)} instead.
*/
@Deprecated
@UnstableApi
default void onLoadingChanged(boolean isLoading) {}
/**
* Called when the value returned from {@link #isCommandAvailable(int)} changes for at least one
* {@link Command}.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param availableCommands The available {@link Commands}.
*/
default void onAvailableCommandsChanged(Commands availableCommands) {}
/**
* Called when the value returned from {@link #getTrackSelectionParameters()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param parameters The new {@link TrackSelectionParameters}.
*/
default void onTrackSelectionParametersChanged(TrackSelectionParameters parameters) {}
/**
* @deprecated Use {@link #onPlaybackStateChanged(int)} and {@link
* #onPlayWhenReadyChanged(boolean, int)} instead.
*/
@Deprecated
@UnstableApi
default void onPlayerStateChanged(boolean playWhenReady, @State int playbackState) {}
/**
* Called when the value returned from {@link #getPlaybackState()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param playbackState The new playback {@link State}.
*/
default void onPlaybackStateChanged(@State int playbackState) {}
/**
* Called when the value returned from {@link #getPlayWhenReady()} changes.
*
* <p>The current {@code playWhenReady} value may be re-reported if the {@code reason} for this
* value changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param playWhenReady Whether playback will proceed when ready.
* @param reason The {@link PlayWhenReadyChangeReason} for the change.
*/
default void onPlayWhenReadyChanged(
boolean playWhenReady, @PlayWhenReadyChangeReason int reason) {}
/**
* Called when the value returned from {@link #getPlaybackSuppressionReason()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param playbackSuppressionReason The current {@link PlaybackSuppressionReason}.
*/
default void onPlaybackSuppressionReasonChanged(
@PlaybackSuppressionReason int playbackSuppressionReason) {}
/**
* Called when the value of {@link #isPlaying()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param isPlaying Whether the player is playing.
*/
default void onIsPlayingChanged(boolean isPlaying) {}
/**
* Called when the value of {@link #getRepeatMode()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param repeatMode The {@link RepeatMode} used for playback.
*/
default void onRepeatModeChanged(@RepeatMode int repeatMode) {}
/**
* Called when the value of {@link #getShuffleModeEnabled()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* @param shuffleModeEnabled Whether shuffling of {@linkplain MediaItem media items} is enabled.
*/
default void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {}
/**
* Called when an error occurs. The playback state will transition to {@link #STATE_IDLE}
* immediately after this method is called. The player instance can still be used, and {@link
* #release()} must still be called on the player should it no longer be required.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* <p>Implementations of Player may pass an instance of a subclass of {@link PlaybackException}
* to this method in order to include more information about the error.
*
* @param error The error.
*/
default void onPlayerError(PlaybackException error) {}
/**
* Called when the {@link PlaybackException} returned by {@link #getPlayerError()} changes.
*
* <p>{@link #onEvents(Player, Events)} will also be called to report this event along with
* other events that happen in the same {@link Looper} message queue iteration.
*
* <p>Implementations of Player may pass an instance of a subclass of {@link PlaybackException}
* to this method in order to include more information about the error.