-
Notifications
You must be signed in to change notification settings - Fork 299
/
SimpleBasePlayer.java
3948 lines (3696 loc) · 157 KB
/
SimpleBasePlayer.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 2022 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 androidx.annotation.VisibleForTesting.PROTECTED;
import static androidx.media3.common.util.Assertions.checkArgument;
import static androidx.media3.common.util.Assertions.checkNotNull;
import static androidx.media3.common.util.Util.castNonNull;
import static androidx.media3.common.util.Util.msToUs;
import static androidx.media3.common.util.Util.usToMs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.graphics.Rect;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Pair;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import androidx.annotation.FloatRange;
import androidx.annotation.IntRange;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.media3.common.text.CueGroup;
import androidx.media3.common.util.Clock;
import androidx.media3.common.util.HandlerWrapper;
import androidx.media3.common.util.ListenerSet;
import androidx.media3.common.util.Size;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.common.util.Util;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.ForOverride;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import org.checkerframework.checker.nullness.qual.EnsuresNonNull;
import org.checkerframework.checker.nullness.qual.MonotonicNonNull;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
/**
* A base implementation for {@link Player} that reduces the number of methods to implement to a
* minimum.
*
* <p>Implementation notes:
*
* <ul>
* <li>Subclasses must override {@link #getState()} to populate the current player state on
* request.
* <li>The {@link State} should set the {@linkplain State.Builder#setAvailableCommands available
* commands} to indicate which {@link Player} methods are supported.
* <li>All setter-like player methods (for example, {@link #setPlayWhenReady}) forward to
* overridable methods (for example, {@link #handleSetPlayWhenReady}) that can be used to
* handle these requests. These methods return a {@link ListenableFuture} to indicate when the
* request has been handled and is fully reflected in the values returned from {@link
* #getState}. This class will automatically request a state update once the request is done.
* If the state changes can be handled synchronously, these methods can return Guava's {@link
* Futures#immediateVoidFuture()}.
* <li>Subclasses can manually trigger state updates with {@link #invalidateState}, for example if
* something changes independent of {@link Player} method calls.
* </ul>
*
* This base class handles various aspects of the player implementation to simplify the subclass:
*
* <ul>
* <li>The {@link State} can only be created with allowed combinations of state values, avoiding
* any invalid player states.
* <li>Only functionality that is declared as {@linkplain Player.Command available} needs to be
* implemented. Other methods are automatically ignored.
* <li>Listener handling and informing listeners of state changes is handled automatically.
* <li>The base class provides a framework for asynchronous handling of method calls. It changes
* the visible playback state immediately to the most likely outcome to ensure the
* user-visible state changes look like synchronous operations. The state is then updated
* again once the asynchronous method calls have been fully handled.
* </ul>
*/
@UnstableApi
public abstract class SimpleBasePlayer extends BasePlayer {
/** An immutable state description of the player. */
protected static final class State {
/** A builder for {@link State} objects. */
public static final class Builder {
private Commands availableCommands;
private boolean playWhenReady;
private @PlayWhenReadyChangeReason int playWhenReadyChangeReason;
private @Player.State int playbackState;
private @PlaybackSuppressionReason int playbackSuppressionReason;
@Nullable private PlaybackException playerError;
private @RepeatMode int repeatMode;
private boolean shuffleModeEnabled;
private boolean isLoading;
private long seekBackIncrementMs;
private long seekForwardIncrementMs;
private long maxSeekToPreviousPositionMs;
private PlaybackParameters playbackParameters;
private TrackSelectionParameters trackSelectionParameters;
private AudioAttributes audioAttributes;
private float volume;
private VideoSize videoSize;
private CueGroup currentCues;
private DeviceInfo deviceInfo;
private int deviceVolume;
private boolean isDeviceMuted;
private Size surfaceSize;
private boolean newlyRenderedFirstFrame;
private Metadata timedMetadata;
private ImmutableList<MediaItemData> playlist;
private Timeline timeline;
private MediaMetadata playlistMetadata;
private int currentMediaItemIndex;
private int currentAdGroupIndex;
private int currentAdIndexInAdGroup;
@Nullable private Long contentPositionMs;
private PositionSupplier contentPositionMsSupplier;
@Nullable private Long adPositionMs;
private PositionSupplier adPositionMsSupplier;
private PositionSupplier contentBufferedPositionMsSupplier;
private PositionSupplier adBufferedPositionMsSupplier;
private PositionSupplier totalBufferedDurationMsSupplier;
private boolean hasPositionDiscontinuity;
private @Player.DiscontinuityReason int positionDiscontinuityReason;
private long discontinuityPositionMs;
/** Creates the builder. */
public Builder() {
availableCommands = Commands.EMPTY;
playWhenReady = false;
playWhenReadyChangeReason = Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST;
playbackState = Player.STATE_IDLE;
playbackSuppressionReason = Player.PLAYBACK_SUPPRESSION_REASON_NONE;
playerError = null;
repeatMode = Player.REPEAT_MODE_OFF;
shuffleModeEnabled = false;
isLoading = false;
seekBackIncrementMs = C.DEFAULT_SEEK_BACK_INCREMENT_MS;
seekForwardIncrementMs = C.DEFAULT_SEEK_FORWARD_INCREMENT_MS;
maxSeekToPreviousPositionMs = C.DEFAULT_MAX_SEEK_TO_PREVIOUS_POSITION_MS;
playbackParameters = PlaybackParameters.DEFAULT;
trackSelectionParameters = TrackSelectionParameters.DEFAULT_WITHOUT_CONTEXT;
audioAttributes = AudioAttributes.DEFAULT;
volume = 1f;
videoSize = VideoSize.UNKNOWN;
currentCues = CueGroup.EMPTY_TIME_ZERO;
deviceInfo = DeviceInfo.UNKNOWN;
deviceVolume = 0;
isDeviceMuted = false;
surfaceSize = Size.UNKNOWN;
newlyRenderedFirstFrame = false;
timedMetadata = new Metadata(/* presentationTimeUs= */ C.TIME_UNSET);
playlist = ImmutableList.of();
timeline = Timeline.EMPTY;
playlistMetadata = MediaMetadata.EMPTY;
currentMediaItemIndex = C.INDEX_UNSET;
currentAdGroupIndex = C.INDEX_UNSET;
currentAdIndexInAdGroup = C.INDEX_UNSET;
contentPositionMs = null;
contentPositionMsSupplier = PositionSupplier.getConstant(C.TIME_UNSET);
adPositionMs = null;
adPositionMsSupplier = PositionSupplier.ZERO;
contentBufferedPositionMsSupplier = PositionSupplier.getConstant(C.TIME_UNSET);
adBufferedPositionMsSupplier = PositionSupplier.ZERO;
totalBufferedDurationMsSupplier = PositionSupplier.ZERO;
hasPositionDiscontinuity = false;
positionDiscontinuityReason = Player.DISCONTINUITY_REASON_INTERNAL;
discontinuityPositionMs = 0;
}
private Builder(State state) {
this.availableCommands = state.availableCommands;
this.playWhenReady = state.playWhenReady;
this.playWhenReadyChangeReason = state.playWhenReadyChangeReason;
this.playbackState = state.playbackState;
this.playbackSuppressionReason = state.playbackSuppressionReason;
this.playerError = state.playerError;
this.repeatMode = state.repeatMode;
this.shuffleModeEnabled = state.shuffleModeEnabled;
this.isLoading = state.isLoading;
this.seekBackIncrementMs = state.seekBackIncrementMs;
this.seekForwardIncrementMs = state.seekForwardIncrementMs;
this.maxSeekToPreviousPositionMs = state.maxSeekToPreviousPositionMs;
this.playbackParameters = state.playbackParameters;
this.trackSelectionParameters = state.trackSelectionParameters;
this.audioAttributes = state.audioAttributes;
this.volume = state.volume;
this.videoSize = state.videoSize;
this.currentCues = state.currentCues;
this.deviceInfo = state.deviceInfo;
this.deviceVolume = state.deviceVolume;
this.isDeviceMuted = state.isDeviceMuted;
this.surfaceSize = state.surfaceSize;
this.newlyRenderedFirstFrame = state.newlyRenderedFirstFrame;
this.timedMetadata = state.timedMetadata;
this.playlist = state.playlist;
this.timeline = state.timeline;
this.playlistMetadata = state.playlistMetadata;
this.currentMediaItemIndex = state.currentMediaItemIndex;
this.currentAdGroupIndex = state.currentAdGroupIndex;
this.currentAdIndexInAdGroup = state.currentAdIndexInAdGroup;
this.contentPositionMs = null;
this.contentPositionMsSupplier = state.contentPositionMsSupplier;
this.adPositionMs = null;
this.adPositionMsSupplier = state.adPositionMsSupplier;
this.contentBufferedPositionMsSupplier = state.contentBufferedPositionMsSupplier;
this.adBufferedPositionMsSupplier = state.adBufferedPositionMsSupplier;
this.totalBufferedDurationMsSupplier = state.totalBufferedDurationMsSupplier;
this.hasPositionDiscontinuity = state.hasPositionDiscontinuity;
this.positionDiscontinuityReason = state.positionDiscontinuityReason;
this.discontinuityPositionMs = state.discontinuityPositionMs;
}
/**
* Sets the available {@link Commands}.
*
* @param availableCommands The available {@link Commands}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setAvailableCommands(Commands availableCommands) {
this.availableCommands = availableCommands;
return this;
}
/**
* Sets whether playback should proceed when ready and not suppressed.
*
* @param playWhenReady Whether playback should proceed when ready and not suppressed.
* @param playWhenReadyChangeReason The {@linkplain PlayWhenReadyChangeReason reason} for
* changing the value.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlayWhenReady(
boolean playWhenReady, @PlayWhenReadyChangeReason int playWhenReadyChangeReason) {
this.playWhenReady = playWhenReady;
this.playWhenReadyChangeReason = playWhenReadyChangeReason;
return this;
}
/**
* Sets the {@linkplain Player.State state} of the player.
*
* <p>If the {@linkplain #setPlaylist playlist} is empty, the state must be either {@link
* Player#STATE_IDLE} or {@link Player#STATE_ENDED}.
*
* @param playbackState The {@linkplain Player.State state} of the player.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlaybackState(@Player.State int playbackState) {
this.playbackState = playbackState;
return this;
}
/**
* Sets the reason why playback is suppressed even if {@link #getPlayWhenReady()} is true.
*
* @param playbackSuppressionReason The {@link Player.PlaybackSuppressionReason} why playback
* is suppressed even if {@link #getPlayWhenReady()} is true.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlaybackSuppressionReason(
@Player.PlaybackSuppressionReason int playbackSuppressionReason) {
this.playbackSuppressionReason = playbackSuppressionReason;
return this;
}
/**
* Sets last error that caused playback to fail, or null if there was no error.
*
* <p>The {@linkplain #setPlaybackState playback state} must be set to {@link
* Player#STATE_IDLE} while an error is set.
*
* @param playerError The last error that caused playback to fail, or null if there was no
* error.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlayerError(@Nullable PlaybackException playerError) {
this.playerError = playerError;
return this;
}
/**
* Sets the {@link RepeatMode} used for playback.
*
* @param repeatMode The {@link RepeatMode} used for playback.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setRepeatMode(@Player.RepeatMode int repeatMode) {
this.repeatMode = repeatMode;
return this;
}
/**
* Sets whether shuffling of media items is enabled.
*
* @param shuffleModeEnabled Whether shuffling of media items is enabled.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setShuffleModeEnabled(boolean shuffleModeEnabled) {
this.shuffleModeEnabled = shuffleModeEnabled;
return this;
}
/**
* Sets whether the player is currently loading its source.
*
* <p>The player can not be marked as loading if the {@linkplain #setPlaybackState state} is
* {@link Player#STATE_IDLE} or {@link Player#STATE_ENDED}.
*
* @param isLoading Whether the player is currently loading its source.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setIsLoading(boolean isLoading) {
this.isLoading = isLoading;
return this;
}
/**
* Sets the {@link Player#seekBack()} increment in milliseconds.
*
* @param seekBackIncrementMs The {@link Player#seekBack()} increment in milliseconds.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setSeekBackIncrementMs(long seekBackIncrementMs) {
this.seekBackIncrementMs = seekBackIncrementMs;
return this;
}
/**
* Sets the {@link Player#seekForward()} increment in milliseconds.
*
* @param seekForwardIncrementMs The {@link Player#seekForward()} increment in milliseconds.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setSeekForwardIncrementMs(long seekForwardIncrementMs) {
this.seekForwardIncrementMs = seekForwardIncrementMs;
return this;
}
/**
* Sets the maximum position for which {@link #seekToPrevious()} seeks to the previous item,
* in milliseconds.
*
* @param maxSeekToPreviousPositionMs The maximum position for which {@link #seekToPrevious()}
* seeks to the previous item, in milliseconds.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setMaxSeekToPreviousPositionMs(long maxSeekToPreviousPositionMs) {
this.maxSeekToPreviousPositionMs = maxSeekToPreviousPositionMs;
return this;
}
/**
* Sets the currently active {@link PlaybackParameters}.
*
* @param playbackParameters The currently active {@link PlaybackParameters}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlaybackParameters(PlaybackParameters playbackParameters) {
this.playbackParameters = playbackParameters;
return this;
}
/**
* Sets the currently active {@link TrackSelectionParameters}.
*
* @param trackSelectionParameters The currently active {@link TrackSelectionParameters}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setTrackSelectionParameters(
TrackSelectionParameters trackSelectionParameters) {
this.trackSelectionParameters = trackSelectionParameters;
return this;
}
/**
* Sets the current {@link AudioAttributes}.
*
* @param audioAttributes The current {@link AudioAttributes}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setAudioAttributes(AudioAttributes audioAttributes) {
this.audioAttributes = audioAttributes;
return this;
}
/**
* Sets the current audio volume, with 0 being silence and 1 being unity gain (signal
* unchanged).
*
* @param volume The current audio volume, with 0 being silence and 1 being unity gain (signal
* unchanged).
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setVolume(@FloatRange(from = 0, to = 1.0) float volume) {
checkArgument(volume >= 0.0f && volume <= 1.0f);
this.volume = volume;
return this;
}
/**
* Sets the current video size.
*
* @param videoSize The current video size.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setVideoSize(VideoSize videoSize) {
this.videoSize = videoSize;
return this;
}
/**
* Sets the current {@linkplain CueGroup cues}.
*
* @param currentCues The current {@linkplain CueGroup cues}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setCurrentCues(CueGroup currentCues) {
this.currentCues = currentCues;
return this;
}
/**
* Sets the {@link DeviceInfo}.
*
* @param deviceInfo The {@link DeviceInfo}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setDeviceInfo(DeviceInfo deviceInfo) {
this.deviceInfo = deviceInfo;
return this;
}
/**
* Sets the current device volume.
*
* @param deviceVolume The current device volume.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setDeviceVolume(@IntRange(from = 0) int deviceVolume) {
checkArgument(deviceVolume >= 0);
this.deviceVolume = deviceVolume;
return this;
}
/**
* Sets whether the device is muted.
*
* @param isDeviceMuted Whether the device is muted.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setIsDeviceMuted(boolean isDeviceMuted) {
this.isDeviceMuted = isDeviceMuted;
return this;
}
/**
* Sets the size of the surface onto which the video is being rendered.
*
* @param surfaceSize The surface size. Dimensions may be {@link C#LENGTH_UNSET} if unknown,
* or 0 if the video is not rendered onto a surface.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setSurfaceSize(Size surfaceSize) {
this.surfaceSize = surfaceSize;
return this;
}
/**
* Sets whether a frame has been rendered for the first time since setting the surface, a
* rendering reset, or since the stream being rendered was changed.
*
* <p>Note: As this will trigger a {@link Listener#onRenderedFirstFrame()} event, the flag
* should only be set for the first {@link State} update after the first frame was rendered.
*
* @param newlyRenderedFirstFrame Whether the first frame was newly rendered.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setNewlyRenderedFirstFrame(boolean newlyRenderedFirstFrame) {
this.newlyRenderedFirstFrame = newlyRenderedFirstFrame;
return this;
}
/**
* Sets the most recent timed {@link Metadata}.
*
* <p>Metadata with a {@link Metadata#presentationTimeUs} of {@link C#TIME_UNSET} will not be
* forwarded to listeners.
*
* @param timedMetadata The most recent timed {@link Metadata}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setTimedMetadata(Metadata timedMetadata) {
this.timedMetadata = timedMetadata;
return this;
}
/**
* Sets the list of {@link MediaItemData media items} in the playlist.
*
* <p>All items must have unique {@linkplain MediaItemData.Builder#setUid UIDs}.
*
* @param playlist The list of {@link MediaItemData media items} in the playlist.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlaylist(List<MediaItemData> playlist) {
HashSet<Object> uids = new HashSet<>();
for (int i = 0; i < playlist.size(); i++) {
checkArgument(uids.add(playlist.get(i).uid), "Duplicate MediaItemData UID in playlist");
}
this.playlist = ImmutableList.copyOf(playlist);
this.timeline = new PlaylistTimeline(this.playlist);
return this;
}
/**
* Sets the playlist {@link MediaMetadata}.
*
* @param playlistMetadata The playlist {@link MediaMetadata}.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setPlaylistMetadata(MediaMetadata playlistMetadata) {
this.playlistMetadata = playlistMetadata;
return this;
}
/**
* Sets the current media item index.
*
* <p>The media item index must be less than the number of {@linkplain #setPlaylist media
* items in the playlist}, if set.
*
* @param currentMediaItemIndex The current media item index, or {@link C#INDEX_UNSET} to
* assume the default first item in the playlist.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setCurrentMediaItemIndex(int currentMediaItemIndex) {
this.currentMediaItemIndex = currentMediaItemIndex;
return this;
}
/**
* Sets the current ad indices, or {@link C#INDEX_UNSET} if no ad is playing.
*
* <p>Either both indices need to be {@link C#INDEX_UNSET} or both are not {@link
* C#INDEX_UNSET}.
*
* <p>Ads indices can only be set if there is a corresponding {@link AdPlaybackState} defined
* in the current {@linkplain MediaItemData.Builder#setPeriods period}.
*
* @param adGroupIndex The current ad group index, or {@link C#INDEX_UNSET} if no ad is
* playing.
* @param adIndexInAdGroup The current ad index in the ad group, or {@link C#INDEX_UNSET} if
* no ad is playing.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setCurrentAd(int adGroupIndex, int adIndexInAdGroup) {
checkArgument((adGroupIndex == C.INDEX_UNSET) == (adIndexInAdGroup == C.INDEX_UNSET));
this.currentAdGroupIndex = adGroupIndex;
this.currentAdIndexInAdGroup = adIndexInAdGroup;
return this;
}
/**
* Sets the current content playback position in milliseconds.
*
* <p>This position will be converted to an advancing {@link PositionSupplier} if the overall
* state indicates an advancing playback position.
*
* <p>This method overrides any other {@link PositionSupplier} set via {@link
* #setContentPositionMs(PositionSupplier)}.
*
* @param positionMs The current content playback position in milliseconds, or {@link
* C#TIME_UNSET} to indicate the default start position.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setContentPositionMs(long positionMs) {
this.contentPositionMs = positionMs;
return this;
}
/**
* Sets the {@link PositionSupplier} for the current content playback position in
* milliseconds.
*
* <p>The supplier is expected to return the updated position on every call if the playback is
* advancing, for example by using {@link PositionSupplier#getExtrapolating}.
*
* <p>This method overrides any other position set via {@link #setContentPositionMs(long)}.
*
* @param contentPositionMsSupplier The {@link PositionSupplier} for the current content
* playback position in milliseconds, or {@link C#TIME_UNSET} to indicate the default
* start position.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setContentPositionMs(PositionSupplier contentPositionMsSupplier) {
this.contentPositionMs = null;
this.contentPositionMsSupplier = contentPositionMsSupplier;
return this;
}
/**
* Sets the current ad playback position in milliseconds. The value is unused if no ad is
* playing.
*
* <p>This position will be converted to an advancing {@link PositionSupplier} if the overall
* state indicates an advancing ad playback position.
*
* <p>This method overrides any other {@link PositionSupplier} set via {@link
* #setAdPositionMs(PositionSupplier)}.
*
* @param positionMs The current ad playback position in milliseconds.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setAdPositionMs(long positionMs) {
this.adPositionMs = positionMs;
return this;
}
/**
* Sets the {@link PositionSupplier} for the current ad playback position in milliseconds. The
* value is unused if no ad is playing.
*
* <p>The supplier is expected to return the updated position on every call if the playback is
* advancing, for example by using {@link PositionSupplier#getExtrapolating}.
*
* <p>This method overrides any other position set via {@link #setAdPositionMs(long)}.
*
* @param adPositionMsSupplier The {@link PositionSupplier} for the current ad playback
* position in milliseconds. The value is unused if no ad is playing.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setAdPositionMs(PositionSupplier adPositionMsSupplier) {
this.adPositionMs = null;
this.adPositionMsSupplier = adPositionMsSupplier;
return this;
}
/**
* Sets the {@link PositionSupplier} for the estimated position up to which the currently
* playing content is buffered, in milliseconds.
*
* @param contentBufferedPositionMsSupplier The {@link PositionSupplier} for the estimated
* position up to which the currently playing content is buffered, in milliseconds, or
* {@link C#TIME_UNSET} to indicate the default start position.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setContentBufferedPositionMs(
PositionSupplier contentBufferedPositionMsSupplier) {
this.contentBufferedPositionMsSupplier = contentBufferedPositionMsSupplier;
return this;
}
/**
* Sets the {@link PositionSupplier} for the estimated position up to which the currently
* playing ad is buffered, in milliseconds. The value is unused if no ad is playing.
*
* @param adBufferedPositionMsSupplier The {@link PositionSupplier} for the estimated position
* up to which the currently playing ad is buffered, in milliseconds. The value is unused
* if no ad is playing.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setAdBufferedPositionMs(PositionSupplier adBufferedPositionMsSupplier) {
this.adBufferedPositionMsSupplier = adBufferedPositionMsSupplier;
return this;
}
/**
* Sets the {@link PositionSupplier} for the estimated total buffered duration in
* milliseconds.
*
* @param totalBufferedDurationMsSupplier The {@link PositionSupplier} for the estimated total
* buffered duration in milliseconds.
* @return This builder.
*/
@CanIgnoreReturnValue
public Builder setTotalBufferedDurationMs(PositionSupplier totalBufferedDurationMsSupplier) {
this.totalBufferedDurationMsSupplier = totalBufferedDurationMsSupplier;
return this;
}
/**
* Signals that a position discontinuity happened since the last player update and sets the
* reason for it.
*
* @param positionDiscontinuityReason The {@linkplain Player.DiscontinuityReason reason} for
* the discontinuity.
* @param discontinuityPositionMs The position, in milliseconds, in the current content or ad
* from which playback continues after the discontinuity.
* @return This builder.
* @see #clearPositionDiscontinuity
*/
@CanIgnoreReturnValue
public Builder setPositionDiscontinuity(
@Player.DiscontinuityReason int positionDiscontinuityReason,
long discontinuityPositionMs) {
this.hasPositionDiscontinuity = true;
this.positionDiscontinuityReason = positionDiscontinuityReason;
this.discontinuityPositionMs = discontinuityPositionMs;
return this;
}
/**
* Clears a previously set position discontinuity signal.
*
* @return This builder.
* @see #hasPositionDiscontinuity
*/
@CanIgnoreReturnValue
public Builder clearPositionDiscontinuity() {
this.hasPositionDiscontinuity = false;
return this;
}
/** Builds the {@link State}. */
public State build() {
return new State(this);
}
}
/** The available {@link Commands}. */
public final Commands availableCommands;
/** Whether playback should proceed when ready and not suppressed. */
public final boolean playWhenReady;
/** The last reason for changing {@link #playWhenReady}. */
public final @PlayWhenReadyChangeReason int playWhenReadyChangeReason;
/** The {@linkplain Player.State state} of the player. */
public final @Player.State int playbackState;
/** The reason why playback is suppressed even if {@link #getPlayWhenReady()} is true. */
public final @PlaybackSuppressionReason int playbackSuppressionReason;
/** The last error that caused playback to fail, or null if there was no error. */
@Nullable public final PlaybackException playerError;
/** The {@link RepeatMode} used for playback. */
public final @RepeatMode int repeatMode;
/** Whether shuffling of media items is enabled. */
public final boolean shuffleModeEnabled;
/** Whether the player is currently loading its source. */
public final boolean isLoading;
/** The {@link Player#seekBack()} increment in milliseconds. */
public final long seekBackIncrementMs;
/** The {@link Player#seekForward()} increment in milliseconds. */
public final long seekForwardIncrementMs;
/**
* The maximum position for which {@link #seekToPrevious()} seeks to the previous item, in
* milliseconds.
*/
public final long maxSeekToPreviousPositionMs;
/** The currently active {@link PlaybackParameters}. */
public final PlaybackParameters playbackParameters;
/** The currently active {@link TrackSelectionParameters}. */
public final TrackSelectionParameters trackSelectionParameters;
/** The current {@link AudioAttributes}. */
public final AudioAttributes audioAttributes;
/** The current audio volume, with 0 being silence and 1 being unity gain (signal unchanged). */
@FloatRange(from = 0, to = 1.0)
public final float volume;
/** The current video size. */
public final VideoSize videoSize;
/** The current {@linkplain CueGroup cues}. */
public final CueGroup currentCues;
/** The {@link DeviceInfo}. */
public final DeviceInfo deviceInfo;
/** The current device volume. */
@IntRange(from = 0)
public final int deviceVolume;
/** Whether the device is muted. */
public final boolean isDeviceMuted;
/** The size of the surface onto which the video is being rendered. */
public final Size surfaceSize;
/**
* Whether a frame has been rendered for the first time since setting the surface, a rendering
* reset, or since the stream being rendered was changed.
*/
public final boolean newlyRenderedFirstFrame;
/** The most recent timed metadata. */
public final Metadata timedMetadata;
/** The media items in the playlist. */
public final ImmutableList<MediaItemData> playlist;
/** The {@link Timeline} derived from the {@link #playlist}. */
public final Timeline timeline;
/** The playlist {@link MediaMetadata}. */
public final MediaMetadata playlistMetadata;
/**
* The current media item index, or {@link C#INDEX_UNSET} to assume the default first item of
* the playlist is played.
*/
public final int currentMediaItemIndex;
/** The current ad group index, or {@link C#INDEX_UNSET} if no ad is playing. */
public final int currentAdGroupIndex;
/** The current ad index in the ad group, or {@link C#INDEX_UNSET} if no ad is playing. */
public final int currentAdIndexInAdGroup;
/**
* The {@link PositionSupplier} for the current content playback position in milliseconds, or
* {@link C#TIME_UNSET} to indicate the default start position.
*/
public final PositionSupplier contentPositionMsSupplier;
/**
* The {@link PositionSupplier} for the current ad playback position in milliseconds. The value
* is unused if no ad is playing.
*/
public final PositionSupplier adPositionMsSupplier;
/**
* The {@link PositionSupplier} for the estimated position up to which the currently playing
* content is buffered, in milliseconds, or {@link C#TIME_UNSET} to indicate the default start
* position.
*/
public final PositionSupplier contentBufferedPositionMsSupplier;
/**
* The {@link PositionSupplier} for the estimated position up to which the currently playing ad
* is buffered, in milliseconds. The value is unused if no ad is playing.
*/
public final PositionSupplier adBufferedPositionMsSupplier;
/** The {@link PositionSupplier} for the estimated total buffered duration in milliseconds. */
public final PositionSupplier totalBufferedDurationMsSupplier;
/** Signals that a position discontinuity happened since the last update to the player. */
public final boolean hasPositionDiscontinuity;
/**
* The {@linkplain Player.DiscontinuityReason reason} for the last position discontinuity. The
* value is unused if {@link #hasPositionDiscontinuity} is {@code false}.
*/
public final @Player.DiscontinuityReason int positionDiscontinuityReason;
/**
* The position, in milliseconds, in the current content or ad from which playback continued
* after the discontinuity. The value is unused if {@link #hasPositionDiscontinuity} is {@code
* false}.
*/
public final long discontinuityPositionMs;
private State(Builder builder) {
if (builder.timeline.isEmpty()) {
checkArgument(
builder.playbackState == Player.STATE_IDLE
|| builder.playbackState == Player.STATE_ENDED,
"Empty playlist only allowed in STATE_IDLE or STATE_ENDED");
checkArgument(
builder.currentAdGroupIndex == C.INDEX_UNSET
&& builder.currentAdIndexInAdGroup == C.INDEX_UNSET,
"Ads not allowed if playlist is empty");
} else {
int mediaItemIndex = builder.currentMediaItemIndex;
if (mediaItemIndex == C.INDEX_UNSET) {
mediaItemIndex = 0; // TODO: Use shuffle order to find first index.
} else {
checkArgument(
builder.currentMediaItemIndex < builder.timeline.getWindowCount(),
"currentMediaItemIndex must be less than playlist.size()");
}
if (builder.currentAdGroupIndex != C.INDEX_UNSET) {
Timeline.Period period = new Timeline.Period();
Timeline.Window window = new Timeline.Window();
long contentPositionMs =
builder.contentPositionMs != null
? builder.contentPositionMs
: builder.contentPositionMsSupplier.get();
int periodIndex =
getPeriodIndexFromWindowPosition(
builder.timeline, mediaItemIndex, contentPositionMs, window, period);
builder.timeline.getPeriod(periodIndex, period);
checkArgument(
builder.currentAdGroupIndex < period.getAdGroupCount(),
"PeriodData has less ad groups than adGroupIndex");
int adCountInGroup = period.getAdCountInAdGroup(builder.currentAdGroupIndex);
if (adCountInGroup != C.LENGTH_UNSET) {
checkArgument(
builder.currentAdIndexInAdGroup < adCountInGroup,
"Ad group has less ads than adIndexInGroupIndex");
}
}
}
if (builder.playerError != null) {
checkArgument(
builder.playbackState == Player.STATE_IDLE, "Player error only allowed in STATE_IDLE");
}
if (builder.playbackState == Player.STATE_IDLE
|| builder.playbackState == Player.STATE_ENDED) {
checkArgument(
!builder.isLoading, "isLoading only allowed when not in STATE_IDLE or STATE_ENDED");
}
PositionSupplier contentPositionMsSupplier = builder.contentPositionMsSupplier;
if (builder.contentPositionMs != null) {
if (builder.currentAdGroupIndex == C.INDEX_UNSET
&& builder.playWhenReady
&& builder.playbackState == Player.STATE_READY
&& builder.playbackSuppressionReason == Player.PLAYBACK_SUPPRESSION_REASON_NONE
&& builder.contentPositionMs != C.TIME_UNSET) {
contentPositionMsSupplier =
PositionSupplier.getExtrapolating(
builder.contentPositionMs, builder.playbackParameters.speed);
} else {
contentPositionMsSupplier = PositionSupplier.getConstant(builder.contentPositionMs);
}
}
PositionSupplier adPositionMsSupplier = builder.adPositionMsSupplier;
if (builder.adPositionMs != null) {
if (builder.currentAdGroupIndex != C.INDEX_UNSET
&& builder.playWhenReady
&& builder.playbackState == Player.STATE_READY
&& builder.playbackSuppressionReason == Player.PLAYBACK_SUPPRESSION_REASON_NONE) {
adPositionMsSupplier =
PositionSupplier.getExtrapolating(builder.adPositionMs, /* playbackSpeed= */ 1f);
} else {
adPositionMsSupplier = PositionSupplier.getConstant(builder.adPositionMs);
}
}
this.availableCommands = builder.availableCommands;
this.playWhenReady = builder.playWhenReady;
this.playWhenReadyChangeReason = builder.playWhenReadyChangeReason;
this.playbackState = builder.playbackState;
this.playbackSuppressionReason = builder.playbackSuppressionReason;
this.playerError = builder.playerError;
this.repeatMode = builder.repeatMode;
this.shuffleModeEnabled = builder.shuffleModeEnabled;
this.isLoading = builder.isLoading;
this.seekBackIncrementMs = builder.seekBackIncrementMs;
this.seekForwardIncrementMs = builder.seekForwardIncrementMs;
this.maxSeekToPreviousPositionMs = builder.maxSeekToPreviousPositionMs;
this.playbackParameters = builder.playbackParameters;
this.trackSelectionParameters = builder.trackSelectionParameters;
this.audioAttributes = builder.audioAttributes;
this.volume = builder.volume;
this.videoSize = builder.videoSize;
this.currentCues = builder.currentCues;
this.deviceInfo = builder.deviceInfo;
this.deviceVolume = builder.deviceVolume;
this.isDeviceMuted = builder.isDeviceMuted;
this.surfaceSize = builder.surfaceSize;
this.newlyRenderedFirstFrame = builder.newlyRenderedFirstFrame;
this.timedMetadata = builder.timedMetadata;
this.playlist = builder.playlist;
this.timeline = builder.timeline;
this.playlistMetadata = builder.playlistMetadata;
this.currentMediaItemIndex = builder.currentMediaItemIndex;
this.currentAdGroupIndex = builder.currentAdGroupIndex;
this.currentAdIndexInAdGroup = builder.currentAdIndexInAdGroup;
this.contentPositionMsSupplier = contentPositionMsSupplier;
this.adPositionMsSupplier = adPositionMsSupplier;
this.contentBufferedPositionMsSupplier = builder.contentBufferedPositionMsSupplier;
this.adBufferedPositionMsSupplier = builder.adBufferedPositionMsSupplier;
this.totalBufferedDurationMsSupplier = builder.totalBufferedDurationMsSupplier;
this.hasPositionDiscontinuity = builder.hasPositionDiscontinuity;
this.positionDiscontinuityReason = builder.positionDiscontinuityReason;
this.discontinuityPositionMs = builder.discontinuityPositionMs;
}
/** Returns a {@link Builder} pre-populated with the current state values. */
public Builder buildUpon() {
return new Builder(this);
}