/
ExoPlayerImplInternal.java
3366 lines (3148 loc) · 139 KB
/
ExoPlayerImplInternal.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) 2016 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 com.google.android.exoplayer2;
import static com.google.android.exoplayer2.Renderer.STATE_DISABLED;
import static com.google.android.exoplayer2.Renderer.STATE_ENABLED;
import static com.google.android.exoplayer2.Renderer.STATE_STARTED;
import static com.google.android.exoplayer2.audio.AudioSink.OFFLOAD_MODE_DISABLED;
import static com.google.android.exoplayer2.util.Assertions.checkNotNull;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import static com.google.android.exoplayer2.util.Util.msToUs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.util.Pair;
import androidx.annotation.CheckResult;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.DefaultMediaClock.PlaybackParametersListener;
import com.google.android.exoplayer2.PlaybackException.ErrorCode;
import com.google.android.exoplayer2.Player.DiscontinuityReason;
import com.google.android.exoplayer2.Player.PlayWhenReadyChangeReason;
import com.google.android.exoplayer2.Player.PlaybackSuppressionReason;
import com.google.android.exoplayer2.Player.RepeatMode;
import com.google.android.exoplayer2.analytics.AnalyticsCollector;
import com.google.android.exoplayer2.analytics.PlayerId;
import com.google.android.exoplayer2.drm.DrmSession;
import com.google.android.exoplayer2.metadata.Metadata;
import com.google.android.exoplayer2.metadata.MetadataRenderer;
import com.google.android.exoplayer2.source.BehindLiveWindowException;
import com.google.android.exoplayer2.source.MediaPeriod;
import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId;
import com.google.android.exoplayer2.source.SampleStream;
import com.google.android.exoplayer2.source.ShuffleOrder;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.source.ads.AdPlaybackState;
import com.google.android.exoplayer2.text.TextRenderer;
import com.google.android.exoplayer2.trackselection.ExoTrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectorResult;
import com.google.android.exoplayer2.upstream.BandwidthMeter;
import com.google.android.exoplayer2.upstream.DataSourceException;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Clock;
import com.google.android.exoplayer2.util.HandlerWrapper;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Implements the internal behavior of {@link ExoPlayerImpl}.
*
* @deprecated com.google.android.exoplayer2 is deprecated. Please migrate to androidx.media3 (which
* contains the same ExoPlayer code). See <a
* href="https://developer.android.com/guide/topics/media/media3/getting-started/migration-guide">the
* migration guide</a> for more details, including a script to help with the migration.
*/
@Deprecated
/* package */ final class ExoPlayerImplInternal
implements Handler.Callback,
MediaPeriod.Callback,
TrackSelector.InvalidationListener,
MediaSourceList.MediaSourceListInfoRefreshListener,
PlaybackParametersListener,
PlayerMessage.Sender {
private static final String TAG = "ExoPlayerImplInternal";
public static final class PlaybackInfoUpdate {
private boolean hasPendingChange;
public PlaybackInfo playbackInfo;
public int operationAcks;
public boolean positionDiscontinuity;
public @DiscontinuityReason int discontinuityReason;
public boolean hasPlayWhenReadyChangeReason;
public @PlayWhenReadyChangeReason int playWhenReadyChangeReason;
public PlaybackInfoUpdate(PlaybackInfo playbackInfo) {
this.playbackInfo = playbackInfo;
}
public void incrementPendingOperationAcks(int operationAcks) {
hasPendingChange |= operationAcks > 0;
this.operationAcks += operationAcks;
}
public void setPlaybackInfo(PlaybackInfo playbackInfo) {
hasPendingChange |= this.playbackInfo != playbackInfo;
this.playbackInfo = playbackInfo;
}
public void setPositionDiscontinuity(@DiscontinuityReason int discontinuityReason) {
if (positionDiscontinuity
&& this.discontinuityReason != Player.DISCONTINUITY_REASON_INTERNAL) {
// We always prefer non-internal discontinuity reasons. We also assume that we won't report
// more than one non-internal discontinuity per message iteration.
Assertions.checkArgument(discontinuityReason == Player.DISCONTINUITY_REASON_INTERNAL);
return;
}
hasPendingChange = true;
positionDiscontinuity = true;
this.discontinuityReason = discontinuityReason;
}
public void setPlayWhenReadyChangeReason(
@PlayWhenReadyChangeReason int playWhenReadyChangeReason) {
hasPendingChange = true;
this.hasPlayWhenReadyChangeReason = true;
this.playWhenReadyChangeReason = playWhenReadyChangeReason;
}
}
public interface PlaybackInfoUpdateListener {
void onPlaybackInfoUpdate(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfo);
}
// Internal messages
private static final int MSG_PREPARE = 0;
private static final int MSG_SET_PLAY_WHEN_READY = 1;
private static final int MSG_DO_SOME_WORK = 2;
private static final int MSG_SEEK_TO = 3;
private static final int MSG_SET_PLAYBACK_PARAMETERS = 4;
private static final int MSG_SET_SEEK_PARAMETERS = 5;
private static final int MSG_STOP = 6;
private static final int MSG_RELEASE = 7;
private static final int MSG_PERIOD_PREPARED = 8;
private static final int MSG_SOURCE_CONTINUE_LOADING_REQUESTED = 9;
private static final int MSG_TRACK_SELECTION_INVALIDATED = 10;
private static final int MSG_SET_REPEAT_MODE = 11;
private static final int MSG_SET_SHUFFLE_ENABLED = 12;
private static final int MSG_SET_FOREGROUND_MODE = 13;
private static final int MSG_SEND_MESSAGE = 14;
private static final int MSG_SEND_MESSAGE_TO_TARGET_THREAD = 15;
private static final int MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL = 16;
private static final int MSG_SET_MEDIA_SOURCES = 17;
private static final int MSG_ADD_MEDIA_SOURCES = 18;
private static final int MSG_MOVE_MEDIA_SOURCES = 19;
private static final int MSG_REMOVE_MEDIA_SOURCES = 20;
private static final int MSG_SET_SHUFFLE_ORDER = 21;
private static final int MSG_PLAYLIST_UPDATE_REQUESTED = 22;
private static final int MSG_SET_PAUSE_AT_END_OF_WINDOW = 23;
private static final int MSG_ATTEMPT_RENDERER_ERROR_RECOVERY = 25;
private static final int MSG_RENDERER_CAPABILITIES_CHANGED = 26;
private static final int MSG_UPDATE_MEDIA_SOURCES_WITH_MEDIA_ITEMS = 27;
private static final int ACTIVE_INTERVAL_MS = 10;
private static final int IDLE_INTERVAL_MS = 1000;
/**
* Duration for which the player needs to appear stuck before the playback is failed on the
* assumption that no further progress will be made. To appear stuck, the player's renderers must
* not be ready, there must be more media available to load, and the LoadControl must be refusing
* to load it.
*/
private static final long PLAYBACK_STUCK_AFTER_MS = 4000;
/**
* Threshold under which a buffered duration is assumed to be empty. We cannot use zero to account
* for buffers currently hold but not played by the renderer.
*/
private static final long PLAYBACK_BUFFER_EMPTY_THRESHOLD_US = 500_000;
private final Renderer[] renderers;
private final Set<Renderer> renderersToReset;
private final RendererCapabilities[] rendererCapabilities;
private final TrackSelector trackSelector;
private final TrackSelectorResult emptyTrackSelectorResult;
private final LoadControl loadControl;
private final BandwidthMeter bandwidthMeter;
private final HandlerWrapper handler;
@Nullable private final HandlerThread internalPlaybackThread;
private final Looper playbackLooper;
private final Timeline.Window window;
private final Timeline.Period period;
private final long backBufferDurationUs;
private final boolean retainBackBufferFromKeyframe;
private final DefaultMediaClock mediaClock;
private final ArrayList<PendingMessageInfo> pendingMessages;
private final Clock clock;
private final PlaybackInfoUpdateListener playbackInfoUpdateListener;
private final MediaPeriodQueue queue;
private final MediaSourceList mediaSourceList;
private final LivePlaybackSpeedControl livePlaybackSpeedControl;
private final long releaseTimeoutMs;
private final PlayerId playerId;
@SuppressWarnings("unused")
private SeekParameters seekParameters;
private PlaybackInfo playbackInfo;
private PlaybackInfoUpdate playbackInfoUpdate;
private boolean released;
private boolean pauseAtEndOfWindow;
private boolean pendingPauseAtEndOfPeriod;
private boolean isRebuffering;
private long lastRebufferRealtimeMs;
private boolean shouldContinueLoading;
private @Player.RepeatMode int repeatMode;
private boolean shuffleModeEnabled;
private boolean foregroundMode;
private boolean requestForRendererSleep;
private boolean offloadSchedulingEnabled;
private int enabledRendererCount;
@Nullable private SeekPosition pendingInitialSeekPosition;
private long rendererPositionUs;
private int nextPendingMessageIndexHint;
private boolean deliverPendingMessageAtStartPositionRequired;
@Nullable private ExoPlaybackException pendingRecoverableRendererError;
private long setForegroundModeTimeoutMs;
private long playbackMaybeBecameStuckAtMs;
public ExoPlayerImplInternal(
Renderer[] renderers,
TrackSelector trackSelector,
TrackSelectorResult emptyTrackSelectorResult,
LoadControl loadControl,
BandwidthMeter bandwidthMeter,
@Player.RepeatMode int repeatMode,
boolean shuffleModeEnabled,
AnalyticsCollector analyticsCollector,
SeekParameters seekParameters,
LivePlaybackSpeedControl livePlaybackSpeedControl,
long releaseTimeoutMs,
boolean pauseAtEndOfWindow,
Looper applicationLooper,
Clock clock,
PlaybackInfoUpdateListener playbackInfoUpdateListener,
PlayerId playerId,
Looper playbackLooper) {
this.playbackInfoUpdateListener = playbackInfoUpdateListener;
this.renderers = renderers;
this.trackSelector = trackSelector;
this.emptyTrackSelectorResult = emptyTrackSelectorResult;
this.loadControl = loadControl;
this.bandwidthMeter = bandwidthMeter;
this.repeatMode = repeatMode;
this.shuffleModeEnabled = shuffleModeEnabled;
this.seekParameters = seekParameters;
this.livePlaybackSpeedControl = livePlaybackSpeedControl;
this.releaseTimeoutMs = releaseTimeoutMs;
this.setForegroundModeTimeoutMs = releaseTimeoutMs;
this.pauseAtEndOfWindow = pauseAtEndOfWindow;
this.clock = clock;
this.playerId = playerId;
playbackMaybeBecameStuckAtMs = C.TIME_UNSET;
lastRebufferRealtimeMs = C.TIME_UNSET;
backBufferDurationUs = loadControl.getBackBufferDurationUs(playerId);
retainBackBufferFromKeyframe = loadControl.retainBackBufferFromKeyframe(playerId);
playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult);
playbackInfoUpdate = new PlaybackInfoUpdate(playbackInfo);
rendererCapabilities = new RendererCapabilities[renderers.length];
@Nullable
RendererCapabilities.Listener rendererCapabilitiesListener =
trackSelector.getRendererCapabilitiesListener();
for (int i = 0; i < renderers.length; i++) {
renderers[i].init(/* index= */ i, playerId, clock);
rendererCapabilities[i] = renderers[i].getCapabilities();
if (rendererCapabilitiesListener != null) {
rendererCapabilities[i].setListener(rendererCapabilitiesListener);
}
}
mediaClock = new DefaultMediaClock(this, clock);
pendingMessages = new ArrayList<>();
renderersToReset = Sets.newIdentityHashSet();
window = new Timeline.Window();
period = new Timeline.Period();
trackSelector.init(/* listener= */ this, bandwidthMeter);
deliverPendingMessageAtStartPositionRequired = true;
HandlerWrapper eventHandler = clock.createHandler(applicationLooper, /* callback= */ null);
queue = new MediaPeriodQueue(analyticsCollector, eventHandler, this::createMediaPeriodHolder);
mediaSourceList =
new MediaSourceList(/* listener= */ this, analyticsCollector, eventHandler, playerId);
if (playbackLooper != null) {
internalPlaybackThread = null;
this.playbackLooper = playbackLooper;
} else {
// Note: The documentation for Process.THREAD_PRIORITY_AUDIO that states "Applications can
// not normally change to this priority" is incorrect.
internalPlaybackThread =
new HandlerThread("ExoPlayer:Playback", Process.THREAD_PRIORITY_AUDIO);
internalPlaybackThread.start();
this.playbackLooper = internalPlaybackThread.getLooper();
}
handler = clock.createHandler(this.playbackLooper, this);
}
private MediaPeriodHolder createMediaPeriodHolder(
MediaPeriodInfo mediaPeriodInfo, long rendererPositionOffsetUs) {
return new MediaPeriodHolder(
rendererCapabilities,
rendererPositionOffsetUs,
trackSelector,
loadControl.getAllocator(),
mediaSourceList,
mediaPeriodInfo,
emptyTrackSelectorResult);
}
public void experimentalSetForegroundModeTimeoutMs(long setForegroundModeTimeoutMs) {
this.setForegroundModeTimeoutMs = setForegroundModeTimeoutMs;
}
public void prepare() {
handler.obtainMessage(MSG_PREPARE).sendToTarget();
}
public void setPlayWhenReady(
boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason) {
handler
.obtainMessage(MSG_SET_PLAY_WHEN_READY, playWhenReady ? 1 : 0, playbackSuppressionReason)
.sendToTarget();
}
public void setPauseAtEndOfWindow(boolean pauseAtEndOfWindow) {
handler
.obtainMessage(MSG_SET_PAUSE_AT_END_OF_WINDOW, pauseAtEndOfWindow ? 1 : 0, /* ignored */ 0)
.sendToTarget();
}
public void setRepeatMode(@Player.RepeatMode int repeatMode) {
handler.obtainMessage(MSG_SET_REPEAT_MODE, repeatMode, 0).sendToTarget();
}
public void setShuffleModeEnabled(boolean shuffleModeEnabled) {
handler.obtainMessage(MSG_SET_SHUFFLE_ENABLED, shuffleModeEnabled ? 1 : 0, 0).sendToTarget();
}
public void seekTo(Timeline timeline, int windowIndex, long positionUs) {
handler
.obtainMessage(MSG_SEEK_TO, new SeekPosition(timeline, windowIndex, positionUs))
.sendToTarget();
}
public void setPlaybackParameters(PlaybackParameters playbackParameters) {
handler.obtainMessage(MSG_SET_PLAYBACK_PARAMETERS, playbackParameters).sendToTarget();
}
public void setSeekParameters(SeekParameters seekParameters) {
handler.obtainMessage(MSG_SET_SEEK_PARAMETERS, seekParameters).sendToTarget();
}
public void stop() {
handler.obtainMessage(MSG_STOP).sendToTarget();
}
public void setMediaSources(
List<MediaSourceList.MediaSourceHolder> mediaSources,
int windowIndex,
long positionUs,
ShuffleOrder shuffleOrder) {
handler
.obtainMessage(
MSG_SET_MEDIA_SOURCES,
new MediaSourceListUpdateMessage(mediaSources, shuffleOrder, windowIndex, positionUs))
.sendToTarget();
}
public void addMediaSources(
int index, List<MediaSourceList.MediaSourceHolder> mediaSources, ShuffleOrder shuffleOrder) {
handler
.obtainMessage(
MSG_ADD_MEDIA_SOURCES,
index,
/* ignored */ 0,
new MediaSourceListUpdateMessage(
mediaSources,
shuffleOrder,
/* windowIndex= */ C.INDEX_UNSET,
/* positionUs= */ C.TIME_UNSET))
.sendToTarget();
}
public void removeMediaSources(int fromIndex, int toIndex, ShuffleOrder shuffleOrder) {
handler
.obtainMessage(MSG_REMOVE_MEDIA_SOURCES, fromIndex, toIndex, shuffleOrder)
.sendToTarget();
}
public void moveMediaSources(
int fromIndex, int toIndex, int newFromIndex, ShuffleOrder shuffleOrder) {
MoveMediaItemsMessage moveMediaItemsMessage =
new MoveMediaItemsMessage(fromIndex, toIndex, newFromIndex, shuffleOrder);
handler.obtainMessage(MSG_MOVE_MEDIA_SOURCES, moveMediaItemsMessage).sendToTarget();
}
public void setShuffleOrder(ShuffleOrder shuffleOrder) {
handler.obtainMessage(MSG_SET_SHUFFLE_ORDER, shuffleOrder).sendToTarget();
}
public void updateMediaSourcesWithMediaItems(
int fromIndex, int toIndex, List<MediaItem> mediaItems) {
handler
.obtainMessage(MSG_UPDATE_MEDIA_SOURCES_WITH_MEDIA_ITEMS, fromIndex, toIndex, mediaItems)
.sendToTarget();
}
@Override
public synchronized void sendMessage(PlayerMessage message) {
if (released || !playbackLooper.getThread().isAlive()) {
Log.w(TAG, "Ignoring messages sent after release.");
message.markAsProcessed(/* isDelivered= */ false);
return;
}
handler.obtainMessage(MSG_SEND_MESSAGE, message).sendToTarget();
}
/**
* Sets the foreground mode.
*
* @param foregroundMode Whether foreground mode should be enabled.
* @return Whether the operations succeeded. If false, the operation timed out.
*/
public synchronized boolean setForegroundMode(boolean foregroundMode) {
if (released || !playbackLooper.getThread().isAlive()) {
return true;
}
if (foregroundMode) {
handler.obtainMessage(MSG_SET_FOREGROUND_MODE, /* foregroundMode */ 1, 0).sendToTarget();
return true;
} else {
AtomicBoolean processedFlag = new AtomicBoolean();
handler
.obtainMessage(MSG_SET_FOREGROUND_MODE, /* foregroundMode */ 0, 0, processedFlag)
.sendToTarget();
waitUninterruptibly(/* condition= */ processedFlag::get, setForegroundModeTimeoutMs);
return processedFlag.get();
}
}
/**
* Releases the player.
*
* @return Whether the release succeeded. If false, the release timed out.
*/
public synchronized boolean release() {
if (released || !playbackLooper.getThread().isAlive()) {
return true;
}
handler.sendEmptyMessage(MSG_RELEASE);
waitUninterruptibly(/* condition= */ () -> released, releaseTimeoutMs);
return released;
}
public Looper getPlaybackLooper() {
return playbackLooper;
}
// Playlist.PlaylistInfoRefreshListener implementation.
@Override
public void onPlaylistUpdateRequested() {
handler.sendEmptyMessage(MSG_PLAYLIST_UPDATE_REQUESTED);
}
// MediaPeriod.Callback implementation.
@Override
public void onPrepared(MediaPeriod source) {
handler.obtainMessage(MSG_PERIOD_PREPARED, source).sendToTarget();
}
@Override
public void onContinueLoadingRequested(MediaPeriod source) {
handler.obtainMessage(MSG_SOURCE_CONTINUE_LOADING_REQUESTED, source).sendToTarget();
}
// TrackSelector.InvalidationListener implementation.
@Override
public void onTrackSelectionsInvalidated() {
handler.sendEmptyMessage(MSG_TRACK_SELECTION_INVALIDATED);
}
@Override
public void onRendererCapabilitiesChanged(Renderer renderer) {
handler.sendEmptyMessage(MSG_RENDERER_CAPABILITIES_CHANGED);
}
// DefaultMediaClock.PlaybackParametersListener implementation.
@Override
public void onPlaybackParametersChanged(PlaybackParameters newPlaybackParameters) {
handler
.obtainMessage(MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL, newPlaybackParameters)
.sendToTarget();
}
// Handler.Callback implementation.
@SuppressWarnings("unchecked") // Casting message payload types.
@Override
public boolean handleMessage(Message msg) {
try {
switch (msg.what) {
case MSG_PREPARE:
prepareInternal();
break;
case MSG_SET_PLAY_WHEN_READY:
setPlayWhenReadyInternal(
/* playWhenReady= */ msg.arg1 != 0,
/* playbackSuppressionReason= */ msg.arg2,
/* operationAck= */ true,
Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST);
break;
case MSG_SET_REPEAT_MODE:
setRepeatModeInternal(msg.arg1);
break;
case MSG_SET_SHUFFLE_ENABLED:
setShuffleModeEnabledInternal(msg.arg1 != 0);
break;
case MSG_DO_SOME_WORK:
doSomeWork();
break;
case MSG_SEEK_TO:
seekToInternal((SeekPosition) msg.obj);
break;
case MSG_SET_PLAYBACK_PARAMETERS:
setPlaybackParametersInternal((PlaybackParameters) msg.obj);
break;
case MSG_SET_SEEK_PARAMETERS:
setSeekParametersInternal((SeekParameters) msg.obj);
break;
case MSG_SET_FOREGROUND_MODE:
setForegroundModeInternal(
/* foregroundMode= */ msg.arg1 != 0, /* processedFlag= */ (AtomicBoolean) msg.obj);
break;
case MSG_STOP:
stopInternal(/* forceResetRenderers= */ false, /* acknowledgeStop= */ true);
break;
case MSG_PERIOD_PREPARED:
handlePeriodPrepared((MediaPeriod) msg.obj);
break;
case MSG_SOURCE_CONTINUE_LOADING_REQUESTED:
handleContinueLoadingRequested((MediaPeriod) msg.obj);
break;
case MSG_TRACK_SELECTION_INVALIDATED:
reselectTracksInternal();
break;
case MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL:
handlePlaybackParameters((PlaybackParameters) msg.obj, /* acknowledgeCommand= */ false);
break;
case MSG_SEND_MESSAGE:
sendMessageInternal((PlayerMessage) msg.obj);
break;
case MSG_SEND_MESSAGE_TO_TARGET_THREAD:
sendMessageToTargetThread((PlayerMessage) msg.obj);
break;
case MSG_SET_MEDIA_SOURCES:
setMediaItemsInternal((MediaSourceListUpdateMessage) msg.obj);
break;
case MSG_ADD_MEDIA_SOURCES:
addMediaItemsInternal((MediaSourceListUpdateMessage) msg.obj, msg.arg1);
break;
case MSG_MOVE_MEDIA_SOURCES:
moveMediaItemsInternal((MoveMediaItemsMessage) msg.obj);
break;
case MSG_REMOVE_MEDIA_SOURCES:
removeMediaItemsInternal(msg.arg1, msg.arg2, (ShuffleOrder) msg.obj);
break;
case MSG_SET_SHUFFLE_ORDER:
setShuffleOrderInternal((ShuffleOrder) msg.obj);
break;
case MSG_PLAYLIST_UPDATE_REQUESTED:
mediaSourceListUpdateRequestedInternal();
break;
case MSG_SET_PAUSE_AT_END_OF_WINDOW:
setPauseAtEndOfWindowInternal(msg.arg1 != 0);
break;
case MSG_ATTEMPT_RENDERER_ERROR_RECOVERY:
attemptRendererErrorRecovery();
break;
case MSG_RENDERER_CAPABILITIES_CHANGED:
reselectTracksInternalAndSeek();
break;
case MSG_UPDATE_MEDIA_SOURCES_WITH_MEDIA_ITEMS:
updateMediaSourcesWithMediaItemsInternal(msg.arg1, msg.arg2, (List<MediaItem>) msg.obj);
break;
case MSG_RELEASE:
releaseInternal();
// Return immediately to not send playback info updates after release.
return true;
default:
return false;
}
} catch (ExoPlaybackException e) {
if (e.type == ExoPlaybackException.TYPE_RENDERER) {
@Nullable MediaPeriodHolder readingPeriod = queue.getReadingPeriod();
if (readingPeriod != null) {
// We can assume that all renderer errors happen in the context of the reading period. See
// [internal: b/150584930#comment4] for exceptions that aren't covered by this assumption.
e = e.copyWithMediaPeriodId(readingPeriod.info.id);
}
}
if (e.isRecoverable
&& (pendingRecoverableRendererError == null
|| e.errorCode == PlaybackException.ERROR_CODE_AUDIO_TRACK_OFFLOAD_INIT_FAILED
|| e.errorCode == PlaybackException.ERROR_CODE_AUDIO_TRACK_OFFLOAD_WRITE_FAILED)) {
// If pendingRecoverableRendererError != null and error was
// ERROR_CODE_AUDIO_TRACK_OFFLOAD_WRITE_FAILED then upon retry, renderer will attempt with
// offload disabled.
Log.w(TAG, "Recoverable renderer error", e);
if (pendingRecoverableRendererError != null) {
pendingRecoverableRendererError.addSuppressed(e);
e = pendingRecoverableRendererError;
} else {
pendingRecoverableRendererError = e;
}
// Given that the player is now in an unhandled exception state, the error needs to be
// recovered or the player stopped before any other message is handled.
handler.sendMessageAtFrontOfQueue(
handler.obtainMessage(MSG_ATTEMPT_RENDERER_ERROR_RECOVERY, e));
} else {
if (pendingRecoverableRendererError != null) {
pendingRecoverableRendererError.addSuppressed(e);
e = pendingRecoverableRendererError;
}
Log.e(TAG, "Playback error", e);
if (e.type == ExoPlaybackException.TYPE_RENDERER
&& queue.getPlayingPeriod() != queue.getReadingPeriod()) {
// We encountered a renderer error while reading ahead. Force-update the playback position
// to the failing item to ensure the user-visible error is reported after the transition.
while (queue.getPlayingPeriod() != queue.getReadingPeriod()) {
queue.advancePlayingPeriod();
}
MediaPeriodHolder newPlayingPeriodHolder = checkNotNull(queue.getPlayingPeriod());
playbackInfo =
handlePositionDiscontinuity(
newPlayingPeriodHolder.info.id,
newPlayingPeriodHolder.info.startPositionUs,
newPlayingPeriodHolder.info.requestedContentPositionUs,
/* discontinuityStartPositionUs= */ newPlayingPeriodHolder.info.startPositionUs,
/* reportDiscontinuity= */ true,
Player.DISCONTINUITY_REASON_AUTO_TRANSITION);
}
stopInternal(/* forceResetRenderers= */ true, /* acknowledgeStop= */ false);
playbackInfo = playbackInfo.copyWithPlaybackError(e);
}
} catch (DrmSession.DrmSessionException e) {
handleIoException(e, e.errorCode);
} catch (ParserException e) {
@ErrorCode int errorCode;
if (e.dataType == C.DATA_TYPE_MEDIA) {
errorCode =
e.contentIsMalformed
? PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED
: PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED;
} else if (e.dataType == C.DATA_TYPE_MANIFEST) {
errorCode =
e.contentIsMalformed
? PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED
: PlaybackException.ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED;
} else {
errorCode = PlaybackException.ERROR_CODE_UNSPECIFIED;
}
handleIoException(e, errorCode);
} catch (DataSourceException e) {
handleIoException(e, e.reason);
} catch (BehindLiveWindowException e) {
handleIoException(e, PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW);
} catch (IOException e) {
handleIoException(e, PlaybackException.ERROR_CODE_IO_UNSPECIFIED);
} catch (RuntimeException e) {
@ErrorCode int errorCode;
if (e instanceof IllegalStateException || e instanceof IllegalArgumentException) {
errorCode = PlaybackException.ERROR_CODE_FAILED_RUNTIME_CHECK;
} else {
errorCode = PlaybackException.ERROR_CODE_UNSPECIFIED;
}
ExoPlaybackException error = ExoPlaybackException.createForUnexpected(e, errorCode);
Log.e(TAG, "Playback error", error);
stopInternal(/* forceResetRenderers= */ true, /* acknowledgeStop= */ false);
playbackInfo = playbackInfo.copyWithPlaybackError(error);
}
maybeNotifyPlaybackInfoChanged();
return true;
}
// Private methods.
private void handleIoException(IOException e, @ErrorCode int errorCode) {
ExoPlaybackException error = ExoPlaybackException.createForSource(e, errorCode);
@Nullable MediaPeriodHolder playingPeriod = queue.getPlayingPeriod();
if (playingPeriod != null) {
// We ensure that all IOException throwing methods are only executed for the playing period.
error = error.copyWithMediaPeriodId(playingPeriod.info.id);
}
Log.e(TAG, "Playback error", error);
stopInternal(/* forceResetRenderers= */ false, /* acknowledgeStop= */ false);
playbackInfo = playbackInfo.copyWithPlaybackError(error);
}
/**
* Blocks the current thread until a condition becomes true or the specified amount of time has
* elapsed.
*
* <p>If the current thread is interrupted while waiting for the condition to become true, this
* method will restore the interrupt <b>after</b> the condition became true or the operation times
* out.
*
* @param condition The condition.
* @param timeoutMs The time in milliseconds to wait for the condition to become true.
*/
private synchronized void waitUninterruptibly(Supplier<Boolean> condition, long timeoutMs) {
long deadlineMs = clock.elapsedRealtime() + timeoutMs;
long remainingMs = timeoutMs;
boolean wasInterrupted = false;
while (!condition.get() && remainingMs > 0) {
try {
clock.onThreadBlocked();
wait(remainingMs);
} catch (InterruptedException e) {
wasInterrupted = true;
}
remainingMs = deadlineMs - clock.elapsedRealtime();
}
if (wasInterrupted) {
// Restore the interrupted status.
Thread.currentThread().interrupt();
}
}
private void setState(int state) {
if (playbackInfo.playbackState != state) {
if (state != Player.STATE_BUFFERING) {
playbackMaybeBecameStuckAtMs = C.TIME_UNSET;
}
playbackInfo = playbackInfo.copyWithPlaybackState(state);
}
}
private void maybeNotifyPlaybackInfoChanged() {
playbackInfoUpdate.setPlaybackInfo(playbackInfo);
if (playbackInfoUpdate.hasPendingChange) {
playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate);
playbackInfoUpdate = new PlaybackInfoUpdate(playbackInfo);
}
}
private void prepareInternal() {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
resetInternal(
/* resetRenderers= */ false,
/* resetPosition= */ false,
/* releaseMediaSourceList= */ false,
/* resetError= */ true);
loadControl.onPrepared(playerId);
setState(playbackInfo.timeline.isEmpty() ? Player.STATE_ENDED : Player.STATE_BUFFERING);
mediaSourceList.prepare(bandwidthMeter.getTransferListener());
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
}
private void setMediaItemsInternal(MediaSourceListUpdateMessage mediaSourceListUpdateMessage)
throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
if (mediaSourceListUpdateMessage.windowIndex != C.INDEX_UNSET) {
pendingInitialSeekPosition =
new SeekPosition(
new PlaylistTimeline(
mediaSourceListUpdateMessage.mediaSourceHolders,
mediaSourceListUpdateMessage.shuffleOrder),
mediaSourceListUpdateMessage.windowIndex,
mediaSourceListUpdateMessage.positionUs);
}
Timeline timeline =
mediaSourceList.setMediaSources(
mediaSourceListUpdateMessage.mediaSourceHolders,
mediaSourceListUpdateMessage.shuffleOrder);
handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false);
}
private void addMediaItemsInternal(MediaSourceListUpdateMessage addMessage, int insertionIndex)
throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
Timeline timeline =
mediaSourceList.addMediaSources(
insertionIndex == C.INDEX_UNSET ? mediaSourceList.getSize() : insertionIndex,
addMessage.mediaSourceHolders,
addMessage.shuffleOrder);
handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false);
}
private void moveMediaItemsInternal(MoveMediaItemsMessage moveMediaItemsMessage)
throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
Timeline timeline =
mediaSourceList.moveMediaSourceRange(
moveMediaItemsMessage.fromIndex,
moveMediaItemsMessage.toIndex,
moveMediaItemsMessage.newFromIndex,
moveMediaItemsMessage.shuffleOrder);
handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false);
}
private void removeMediaItemsInternal(int fromIndex, int toIndex, ShuffleOrder shuffleOrder)
throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
Timeline timeline = mediaSourceList.removeMediaSourceRange(fromIndex, toIndex, shuffleOrder);
handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false);
}
private void mediaSourceListUpdateRequestedInternal() throws ExoPlaybackException {
handleMediaSourceListInfoRefreshed(
mediaSourceList.createTimeline(), /* isSourceRefresh= */ true);
}
private void setShuffleOrderInternal(ShuffleOrder shuffleOrder) throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
Timeline timeline = mediaSourceList.setShuffleOrder(shuffleOrder);
handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false);
}
private void updateMediaSourcesWithMediaItemsInternal(
int fromIndex, int toIndex, List<MediaItem> mediaItems) throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1);
Timeline timeline =
mediaSourceList.updateMediaSourcesWithMediaItems(fromIndex, toIndex, mediaItems);
handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false);
}
private void notifyTrackSelectionPlayWhenReadyChanged(boolean playWhenReady) {
MediaPeriodHolder periodHolder = queue.getPlayingPeriod();
while (periodHolder != null) {
for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) {
if (trackSelection != null) {
trackSelection.onPlayWhenReadyChanged(playWhenReady);
}
}
periodHolder = periodHolder.getNext();
}
}
private void setPlayWhenReadyInternal(
boolean playWhenReady,
@PlaybackSuppressionReason int playbackSuppressionReason,
boolean operationAck,
@Player.PlayWhenReadyChangeReason int reason)
throws ExoPlaybackException {
playbackInfoUpdate.incrementPendingOperationAcks(operationAck ? 1 : 0);
playbackInfoUpdate.setPlayWhenReadyChangeReason(reason);
playbackInfo = playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason);
updateRebufferingState(/* isRebuffering= */ false, /* resetLastRebufferRealtimeMs= */ false);
notifyTrackSelectionPlayWhenReadyChanged(playWhenReady);
if (!shouldPlayWhenReady()) {
stopRenderers();
updatePlaybackPositions();
} else {
if (playbackInfo.playbackState == Player.STATE_READY) {
updateRebufferingState(
/* isRebuffering= */ false, /* resetLastRebufferRealtimeMs= */ false);
mediaClock.start();
startRenderers();
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
} else if (playbackInfo.playbackState == Player.STATE_BUFFERING) {
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
}
}
}
private void setPauseAtEndOfWindowInternal(boolean pauseAtEndOfWindow)
throws ExoPlaybackException {
this.pauseAtEndOfWindow = pauseAtEndOfWindow;
resetPendingPauseAtEndOfPeriod();
if (pendingPauseAtEndOfPeriod && queue.getReadingPeriod() != queue.getPlayingPeriod()) {
// When pausing is required, we need to set the streams of the playing period final. If we
// already started reading the next period, we need to flush the renderers.
seekToCurrentPosition(/* sendDiscontinuity= */ true);
handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false);
}
}
private void setOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) {
if (offloadSchedulingEnabled == this.offloadSchedulingEnabled) {
return;
}
this.offloadSchedulingEnabled = offloadSchedulingEnabled;
if (!offloadSchedulingEnabled && playbackInfo.sleepingForOffload) {
// We need to wake the player up if offload scheduling is disabled and we are sleeping.
handler.sendEmptyMessage(MSG_DO_SOME_WORK);
}
}
private void setRepeatModeInternal(@Player.RepeatMode int repeatMode)
throws ExoPlaybackException {
this.repeatMode = repeatMode;
if (!queue.updateRepeatMode(playbackInfo.timeline, repeatMode)) {
seekToCurrentPosition(/* sendDiscontinuity= */ true);
}
handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false);
}
private void setShuffleModeEnabledInternal(boolean shuffleModeEnabled)
throws ExoPlaybackException {
this.shuffleModeEnabled = shuffleModeEnabled;
if (!queue.updateShuffleModeEnabled(playbackInfo.timeline, shuffleModeEnabled)) {
seekToCurrentPosition(/* sendDiscontinuity= */ true);
}
handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false);
}
private void seekToCurrentPosition(boolean sendDiscontinuity) throws ExoPlaybackException {
// Renderers may have read from a period that's been removed. Seek back to the current
// position of the playing period to make sure none of the removed period is played.
MediaPeriodId periodId = queue.getPlayingPeriod().info.id;
long newPositionUs =
seekToPeriodPosition(
periodId,
playbackInfo.positionUs,
/* forceDisableRenderers= */ true,
/* forceBufferingState= */ false);
if (newPositionUs != playbackInfo.positionUs) {
playbackInfo =
handlePositionDiscontinuity(
periodId,
newPositionUs,
playbackInfo.requestedContentPositionUs,
playbackInfo.discontinuityStartPositionUs,
sendDiscontinuity,
Player.DISCONTINUITY_REASON_INTERNAL);
}
}
private void startRenderers() throws ExoPlaybackException {
MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod();
if (playingPeriodHolder == null) {
return;
}
TrackSelectorResult trackSelectorResult = playingPeriodHolder.getTrackSelectorResult();
for (int i = 0; i < renderers.length; i++) {
if (trackSelectorResult.isRendererEnabled(i) && renderers[i].getState() == STATE_ENABLED) {
renderers[i].start();
}
}
}
private void stopRenderers() throws ExoPlaybackException {
mediaClock.stop();
for (Renderer renderer : renderers) {
if (isRendererEnabled(renderer)) {
ensureStopped(renderer);
}
}
}
private void attemptRendererErrorRecovery() throws ExoPlaybackException {
reselectTracksInternalAndSeek();
}
private void updatePlaybackPositions() throws ExoPlaybackException {
MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod();
if (playingPeriodHolder == null) {
return;
}
// Update the playback position.
long discontinuityPositionUs =
playingPeriodHolder.prepared
? playingPeriodHolder.mediaPeriod.readDiscontinuity()
: C.TIME_UNSET;
if (discontinuityPositionUs != C.TIME_UNSET) {
if (!playingPeriodHolder.isFullyBuffered()) {
// The discontinuity caused the period to not be fully buffered. Continue loading from this
// period again and discard all other periods we already started loading.
queue.removeAfter(playingPeriodHolder);
handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false);
maybeContinueLoading();
}
resetRendererPosition(discontinuityPositionUs);