-
Notifications
You must be signed in to change notification settings - Fork 28
/
PlayerContextProvider.js
1401 lines (1316 loc) · 46.5 KB
/
PlayerContextProvider.js
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
import React, { Component, Fragment, createElement } from 'react';
import PropTypes from 'prop-types';
import arrayFindIndex from 'array-find-index';
import PlayerContext from './PlayerContext';
import GroupContext from './GroupContext';
import * as PlayerPropTypes from './PlayerPropTypes';
import createCustomMediaElement from './factories/createCustomMediaElement';
import ShuffleManager from './utils/ShuffleManager';
import { getStateSnapshot, restoreStateFromSnapshot } from './utils/snapshot';
import getSourceList from './utils/getSourceList';
import getTrackSources from './utils/getTrackSources';
import getTimeRangesArray from './utils/getTimeRangesArray';
import findTrackIndexByUrl from './utils/findTrackIndexByUrl';
import isPlaylistValid from './utils/isPlaylistValid';
import getRepeatStrategy from './utils/getRepeatStrategy';
import convertToNumberWithinIntervalBounds from './utils/convertToNumberWithinIntervalBounds';
import { logError, logWarning } from './utils/console';
import getDisplayText from './utils/getDisplayText';
import getInitialDuration from './utils/getInitialDuration';
import { repeatStrategyOptions } from './constants';
function playErrorHandler(err) {
logError(err);
if (err.name === 'NotAllowedError') {
const warningMessage =
'Media playback failed at ' +
new Date().toLocaleTimeString() +
'! (Perhaps autoplay is disabled in this browser.)';
logWarning(warningMessage);
}
}
// Existing Media Session API implementations have default handlers
// for play/pause, and may yield unexpected behavior if custom
// play/pause handlers are defined - so let's leave them be.
const supportableMediaSessionActions = [
'previoustrack',
'nexttrack',
'seekbackward',
'seekforward'
];
const defaultState = {
// indicates whether media player should be paused
paused: true,
// elapsed time for active track, in seconds
currentTime: 0,
// The most recent targeted time, in seconds, for seek preview
seekPreviewTime: 0,
/* true if the user is currently dragging the mouse
* to seek a new track position
*/
seekInProgress: false,
/* true if media was playing when seek previewing began,
* it was paused, and it should be resumed on seek
* complete
*/
awaitingResumeOnSeekComplete: false,
// true if media will play once new track has loaded
awaitingPlayAfterTrackLoad: false,
// the duration in seconds of the loaded track
duration: 0,
// array describing the buffered ranges in the loaded track
bufferedRanges: [],
// array describing the already-played ranges in the loaded track
playedRanges: [],
// array describing the seekable ranges in the loaded track
seekableRanges: [],
// true if the media is currently stalled pending data buffering
stalled: false,
// true if the active track should play on the next componentDidUpdate
shouldRequestPlayOnNextUpdate: false,
/* true if an error occurs while fetching the active track media data
* or if its type is not a supported media format
*/
mediaCannotPlay: false,
// maximum currentTime since the current track has been playing
maxKnownTime: 0
};
// assumes playlist is valid
function getGoToTrackState({
prevState,
index,
track,
shouldPlay = true,
shouldForceLoad = false
}) {
const isNewTrack = prevState.activeTrackIndex !== index;
const shouldLoadAsNew = Boolean(isNewTrack || shouldForceLoad);
const currentTime = track.startingTime || 0;
return {
duration: getInitialDuration(track),
activeTrackIndex: index,
trackLoading: shouldLoadAsNew,
mediaCannotPlay: prevState.mediaCannotPlay && !shouldLoadAsNew,
currentTime: convertToNumberWithinIntervalBounds(currentTime, 0),
loop: shouldLoadAsNew ? false : prevState.loop,
shouldRequestPlayOnNextUpdate: Boolean(shouldPlay),
awaitingPlayAfterTrackLoad: Boolean(shouldPlay),
awaitingForceLoad: Boolean(shouldForceLoad),
maxKnownTime: shouldLoadAsNew ? 0 : prevState.maxKnownTime
};
}
/**
* Wraps an area which shares a common [`playerContext`](#playercontext)
*/
export class PlayerContextProvider extends Component {
constructor(props) {
super(props);
let currentTime = 0;
let activeTrackIndex = convertToNumberWithinIntervalBounds(
props.startingTrackIndex,
0
);
const playlistIsValid = isPlaylistValid(props.playlist);
if (playlistIsValid && props.playlist[activeTrackIndex]) {
currentTime = props.playlist[activeTrackIndex].startingTime || 0;
}
const { initialStateSnapshot } = props;
let restoredStateFromSnapshot = {};
if (initialStateSnapshot) {
try {
restoredStateFromSnapshot = restoreStateFromSnapshot(
initialStateSnapshot,
props
);
const {
activeTrackIndex: a,
currentTime: c
} = restoredStateFromSnapshot;
if (typeof a === 'number') {
activeTrackIndex = a;
}
if (typeof c === 'number') {
currentTime = c;
}
} catch (err) {
logWarning(err);
logWarning('Loading Cassette state from snapshot failed.');
logWarning(
`Failed snapshot:\n${JSON.stringify(initialStateSnapshot, null, 2)}`
);
}
}
this.state = {
...defaultState,
// index matching requested track (whether track has loaded or not)
activeTrackIndex,
// whether we're waiting on loading metadata for the active track
trackLoading: isPlaylistValid(props.playlist),
// the current timestamp on the active track in seconds
currentTime: convertToNumberWithinIntervalBounds(currentTime, 0),
// the latest volume of the media, between 0 and 1.
volume: convertToNumberWithinIntervalBounds(props.defaultVolume, 0, 1),
// true if the media has been muted
muted: props.defaultMuted,
// whether to loop the active track
loop: props.defaultRepeatStrategy === 'track',
// true if playlist should continue at start after completion
cycle: props.defaultRepeatStrategy === 'playlist',
// whether to randomly pick next track from playlist after one finishes
shuffle: props.defaultShuffle,
// Rate at which media should be played. 1.0 is normal speed.
playbackRate: props.defaultPlaybackRate,
// true if user is currently dragging mouse to change the volume
setVolumeInProgress: false,
// initialize shouldRequestPlayOnNextUpdate from autoplay prop
shouldRequestPlayOnNextUpdate: props.autoplay && playlistIsValid,
awaitingForceLoad: false,
// duration might be set on track object
duration: getInitialDuration(
playlistIsValid && props.playlist[activeTrackIndex]
),
// playlist prop copied to state (for getDerivedStateFromProps)
__playlist__: props.playlist,
// load overrides from previously-captured state snapshot
...restoredStateFromSnapshot
};
// volume at last time we were unmuted and not actively setting volume
this.lastStableVolume = this.state.volume;
// used to keep track of play history when we are shuffling
this.shuffler = new ShuffleManager(getSourceList(props.playlist), {
allowBackShuffle: props.allowBackShuffle
});
// html media element used for playback
this.media = null;
this.videoHostElementList = [];
this.videoHostOccupiedCallbacks = new Map();
this.videoHostVacatedCallbacks = new Map();
// bind internal methods
this.handleTrackPlaybackFailure = this.handleTrackPlaybackFailure.bind(
this
);
// bind callback methods to pass to descendant elements
this.togglePause = this.togglePause.bind(this);
this.selectTrackIndex = this.selectTrackIndex.bind(this);
this.forwardSkip = this.forwardSkip.bind(this);
this.backSkip = this.backSkip.bind(this);
this.seekPreview = this.seekPreview.bind(this);
this.seekComplete = this.seekComplete.bind(this);
this.setVolume = this.setVolume.bind(this);
this.setVolumeComplete = this.setVolumeComplete.bind(this);
this.toggleMuted = this.toggleMuted.bind(this);
this.toggleShuffle = this.toggleShuffle.bind(this);
this.setRepeatStrategy = this.setRepeatStrategy.bind(this);
this.setPlaybackRate = this.setPlaybackRate.bind(this);
this.registerVideoHostElement = this.registerVideoHostElement.bind(this);
this.renderVideoIntoHostElement = this.renderVideoIntoHostElement.bind(
this
);
this.unregisterVideoHostElement = this.unregisterVideoHostElement.bind(
this
);
this.updateVideoHostElement = this.updateVideoHostElement.bind(this);
// bind media event handlers
this.handleMediaPlay = this.handleMediaPlay.bind(this);
this.handleMediaPause = this.handleMediaPause.bind(this);
this.handleMediaSrcrequest = this.handleMediaSrcrequest.bind(this);
this.handleMediaEnded = this.handleMediaEnded.bind(this);
this.handleMediaEmptied = this.handleMediaEmptied.bind(this);
this.handleMediaStalled = this.handleMediaStalled.bind(this);
this.handleMediaCanplaythrough = this.handleMediaCanplaythrough.bind(this);
this.handleMediaCanplay = this.handleMediaCanplay.bind(this);
this.handleMediaTimeupdate = this.handleMediaTimeupdate.bind(this);
this.handleMediaLoadeddata = this.handleMediaLoadeddata.bind(this);
this.handleMediaVolumechange = this.handleMediaVolumechange.bind(this);
this.handleMediaDurationchange = this.handleMediaDurationchange.bind(this);
this.handleMediaProgress = this.handleMediaProgress.bind(this);
this.handleMediaLoopchange = this.handleMediaLoopchange.bind(this);
this.handleMediaRatechange = this.handleMediaRatechange.bind(this);
}
componentDidMount() {
const media = (this.media = createCustomMediaElement(
this.props.createMediaElement()
));
const {
defaultPlaybackRate,
crossOrigin,
playlist,
autoplayDelayInSeconds,
mediaElementRef,
getPosterImageForTrack,
getMediaTitleAttributeForTrack,
onActiveTrackUpdate
} = this.props;
const {
volume,
muted,
playbackRate,
loop,
activeTrackIndex,
shouldRequestPlayOnNextUpdate
} = this.state;
// initialize media properties
// We used to set currentTime here.. now waiting for loadeddata.
// This avoids an issue where some browsers ignore or delay currentTime
// updates when in the HAVE_NOTHING state.
media.defaultPlaybackRate = defaultPlaybackRate;
if (crossOrigin) {
media.crossOrigin = crossOrigin;
}
media.volume = volume;
media.muted = muted;
media.playbackRate = playbackRate;
media.loop = loop;
media.setAttribute('playsinline', '');
media.setAttribute('webkit-playsinline', '');
media.setAttribute('preload', 'metadata');
media.setAttribute(
'poster',
getPosterImageForTrack(playlist[activeTrackIndex])
);
media.setAttribute(
'title',
getMediaTitleAttributeForTrack(playlist[activeTrackIndex])
);
// add listeners for media events
media.addEventListener('play', this.handleMediaPlay);
media.addEventListener('pause', this.handleMediaPause);
media.addEventListener('ended', this.handleMediaEnded);
media.addEventListener('stalled', this.handleMediaStalled);
media.addEventListener('emptied', this.handleMediaEmptied);
media.addEventListener('canplay', this.handleMediaCanplay);
media.addEventListener('canplaythrough', this.handleMediaCanplaythrough);
media.addEventListener('timeupdate', this.handleMediaTimeupdate);
media.addEventListener('loadeddata', this.handleMediaLoadeddata);
media.addEventListener('volumechange', this.handleMediaVolumechange);
media.addEventListener('durationchange', this.handleMediaDurationchange);
media.addEventListener('progress', this.handleMediaProgress);
media.addEventListener('ratechange', this.handleMediaRatechange);
// add listeners for special events
media.addEventListener('srcrequest', this.handleMediaSrcrequest);
media.addEventListener('loopchange', this.handleMediaLoopchange);
// set source elements for current track
this.setMediaElementSources();
// initially mount media element in the hidden container (this may change)
this.mediaContainer.appendChild(media);
if (shouldRequestPlayOnNextUpdate) {
this.setState({
shouldRequestPlayOnNextUpdate: false
});
this.delayTimeout = setTimeout(() => {
this.togglePause(false);
}, autoplayDelayInSeconds * 1000);
}
if (mediaElementRef) {
mediaElementRef(media);
}
if (onActiveTrackUpdate) {
onActiveTrackUpdate({
track: playlist[activeTrackIndex],
trackIndex: activeTrackIndex,
previousTrack: null,
previousTrackIndex: null
});
}
}
static getDerivedStateFromProps(nextProps, prevState) {
const newPlaylist = nextProps.playlist;
if (newPlaylist === prevState.__playlist__) {
// reference comparison is equal so we'll
// assume the playlist is unchanged.
return null;
}
const baseNewState = {
__playlist__: newPlaylist
};
// check if the new playlist is invalid
if (!isPlaylistValid(newPlaylist)) {
return {
...defaultState,
...baseNewState,
activeTrackIndex: 0,
trackLoading: false
};
}
// check if the activeTrackIndex doesn't need to be updated
const prevSources = getTrackSources(
prevState.__playlist__,
prevState.activeTrackIndex
);
if (newPlaylist[prevState.activeTrackIndex]) {
// the sources if we stay on the same track index
const currentSources = getTrackSources(
newPlaylist,
prevState.activeTrackIndex
);
// non-comprehensive but probably accurate check
if (prevSources[0].src === currentSources[0].src) {
// our active track index already matches
return baseNewState;
}
}
/* if the track we're already playing is in the new playlist, update the
* activeTrackIndex.
*/
const newTrackIndex = findTrackIndexByUrl(newPlaylist, prevSources[0].src);
if (newTrackIndex !== -1) {
return {
...baseNewState,
activeTrackIndex: newTrackIndex
};
}
// if not, then load the first track in the new playlist, and pause.
return {
...baseNewState,
...getGoToTrackState({
prevState,
track: newPlaylist[0],
index: 0,
shouldPlay: false,
shouldForceLoad: true
}),
mediaCannotPlay: false,
awaitingPlayAfterTrackLoad: false
};
}
componentDidUpdate(prevProps, prevState) {
this.media.defaultPlaybackRate = this.props.defaultPlaybackRate;
this.media.crossOrigin = this.props.crossOrigin;
this.shuffler.setList(getSourceList(this.props.playlist));
this.shuffler.setOptions({
allowBackShuffle: this.props.allowBackShuffle
});
const prevSources = getTrackSources(
prevProps.playlist,
prevState.activeTrackIndex
);
const newSources = getTrackSources(
this.props.playlist,
this.state.activeTrackIndex
);
const prevTrack = prevProps.playlist[prevState.activeTrackIndex];
const newTrack = this.props.playlist[this.state.activeTrackIndex];
if (
this.state.awaitingForceLoad ||
prevSources[0].src !== newSources[0].src
) {
this.setMediaElementSources();
this.media.setAttribute(
'poster',
this.props.getPosterImageForTrack(newTrack)
);
this.media.setAttribute(
'title',
this.props.getMediaTitleAttributeForTrack(newTrack)
);
this.setState({
awaitingForceLoad: false
});
if (!this.state.shuffle) {
// after toggling off shuffle, we defer clearing the shuffle
// history until we actually change tracks - if the user quickly
// toggles shuffle off then back on again, we don't want to have
// lost our history.
this.shuffler.clear();
}
}
if (this.props.onActiveTrackUpdate && prevTrack !== newTrack) {
this.props.onActiveTrackUpdate({
track: newTrack,
trackIndex: this.state.activeTrackIndex,
previousTrack: prevTrack,
previousTrackIndex: prevState.activeTrackIndex
});
}
if (prevProps !== this.props && !this.media.paused) {
// update running media session based on new props
this.stealMediaSession();
}
if (this.state.shouldRequestPlayOnNextUpdate) {
this.setState({
shouldRequestPlayOnNextUpdate: false
});
// media.currentSrc is updated asynchronously so we should
// play async to avoid weird intermediate state issues
setTimeout(() => {
this.togglePause(false);
});
}
clearTimeout(this.snapshotUpdateTimeout);
this.snapshotUpdateTimeout = setTimeout(() => {
if (this.props.onStateSnapshot) {
this.props.onStateSnapshot(getStateSnapshot(this.state));
}
}, 100);
}
componentWillUnmount() {
const { media } = this;
// Media element creation will have failed if MutationObserver isn't
// supported by the browser. The parent might use an Error Boundary
// to display a fallback and so we try to avoid triggering *additional*
// errors while the component unmounts.
if (media) {
// remove listeners for media events
media.removeEventListener('play', this.handleMediaPlay);
media.removeEventListener('pause', this.handleMediaPause);
media.removeEventListener('ended', this.handleMediaEnded);
media.removeEventListener('stalled', this.handleMediaStalled);
media.removeEventListener('emptied', this.handleMediaEmptied);
media.removeEventListener(
'canplaythrough',
this.handleMediaCanplaythrough
);
media.removeEventListener('canplay', this.handleMediaCanplay);
media.removeEventListener('timeupdate', this.handleMediaTimeupdate);
media.removeEventListener('loadeddata', this.handleMediaLoadeddata);
media.removeEventListener('volumechange', this.handleMediaVolumechange);
media.removeEventListener(
'durationchange',
this.handleMediaDurationchange
);
media.removeEventListener('progress', this.handleMediaProgress);
media.removeEventListener('ratechange', this.handleMediaRatechange);
// remove special event listeners on the media element
media.removeEventListener('srcrequest', this.handleMediaSrcrequest);
media.removeEventListener('loopchange', this.handleMediaLoopchange);
const sourceElements = media.querySelectorAll('source');
for (const sourceElement of sourceElements) {
sourceElement.removeEventListener(
'error',
this.handleTrackPlaybackFailure
);
}
}
clearTimeout(this.gapLengthTimeout);
clearTimeout(this.delayTimeout);
}
stealMediaSession() {
if (
// eslint-disable-next-line no-undef
!(window.MediaSession && navigator.mediaSession instanceof MediaSession)
) {
return;
}
// eslint-disable-next-line no-undef
navigator.mediaSession.metadata = new MediaMetadata(
this.props.playlist[this.state.activeTrackIndex]
);
supportableMediaSessionActions
.map(action => {
if (this.props.supportedMediaSessionActions.indexOf(action) === -1) {
return null;
}
const seekLength = this.props.mediaSessionSeekLengthInSeconds;
switch (action) {
case 'play':
return this.togglePause.bind(this, false);
case 'pause':
return this.togglePause.bind(this, true);
case 'previoustrack':
return this.backSkip;
case 'nexttrack':
return this.forwardSkip;
case 'seekbackward':
return () => (this.media.currentTime -= seekLength);
case 'seekforward':
return () => (this.media.currentTime += seekLength);
default:
return undefined;
}
})
.forEach((handler, i) => {
navigator.mediaSession.setActionHandler(
supportableMediaSessionActions[i],
handler
);
});
}
setMediaElementSources() {
// remove current sources
const { playlist } = this.props;
let firstChild;
while ((firstChild = this.media.firstChild)) {
this.media.removeChild(firstChild);
}
if (isPlaylistValid(playlist)) {
const sources = getTrackSources(playlist, this.state.activeTrackIndex);
// add new sources
for (const source of sources) {
const sourceElement = document.createElement('source');
sourceElement.src = source.src;
if (source.type) {
sourceElement.type = source.type;
}
sourceElement.addEventListener(
'error',
this.handleTrackPlaybackFailure
);
this.media.appendChild(sourceElement);
}
}
// cancel playback and re-scan new sources
this.media.load();
}
handleTrackPlaybackFailure(event) {
this.setState({
mediaCannotPlay: true
});
if (this.props.onTrackPlaybackFailure) {
this.props.onTrackPlaybackFailure({
track: this.props.playlist[this.state.activeTrackIndex],
trackIndex: this.state.activeTrackIndex,
event
});
}
}
registerVideoHostElement(hostElement, { onHostOccupied, onHostVacated }) {
this.videoHostElementList = this.videoHostElementList.concat(hostElement);
this.videoHostOccupiedCallbacks.set(hostElement, onHostOccupied);
this.videoHostVacatedCallbacks.set(hostElement, onHostVacated);
}
renderVideoIntoHostElement(hostElement) {
if (this.videoHostElementList.indexOf(hostElement) === -1) {
return;
}
cancelAnimationFrame(this.videoHostUpdateRaf);
this.videoHostUpdateRaf = requestAnimationFrame(() =>
this.updateVideoHostElement(hostElement)
);
}
unregisterVideoHostElement(hostElement) {
this.videoHostElementList = this.videoHostElementList.filter(
elem => elem !== hostElement
);
this.videoHostOccupiedCallbacks.delete(hostElement);
this.videoHostVacatedCallbacks.delete(hostElement);
if (this.media.parentNode === hostElement) {
this.updateVideoHostElement();
}
}
updateVideoHostElement(hostElement) {
if (!hostElement) {
hostElement = this.videoHostElementList[0] || this.mediaContainer;
} else {
// move hostElement to front of list
this.videoHostElementList = [hostElement].concat(
this.videoHostElementList.filter(elem => elem !== hostElement)
);
}
const playing = !this.media.paused;
const oldHostElement = this.media.parentNode;
if (hostElement === oldHostElement) {
return;
}
hostElement.appendChild(this.media);
// according to the HTML spec playback should continue, but
// some browsers pause the element whenever it is moved around, so
// let's make sure playback resumes if that's the case.
if (playing && this.media.paused) {
this.media.play();
}
const onVacated = this.videoHostVacatedCallbacks.get(oldHostElement);
if (onVacated) {
onVacated(this.media);
}
const onOccupied = this.videoHostOccupiedCallbacks.get(hostElement);
if (onOccupied) {
onOccupied(this.media);
}
}
handleMediaPlay() {
this.setState(
state =>
state.paused === false && state.awaitingPlayAfterTrackLoad === false
? null
: { paused: false, awaitingPlayAfterTrackLoad: false }
);
this.stealMediaSession();
}
handleMediaPause() {
this.setState(state => (state.paused === true ? null : { paused: true }));
}
handleMediaSrcrequest(e) {
const { playlist } = this.props;
const sources = getTrackSources(playlist, this.state.activeTrackIndex);
if (arrayFindIndex(sources, s => s.src === e.srcRequested) !== -1) {
// we're good! nothing to update.
return;
}
// looks like 'src' was set from outside our component.
// let's see if we can use it.
const newTrackIndex = findTrackIndexByUrl(playlist, e.srcRequested);
if (newTrackIndex === -1) {
logError(
`Source '${e.srcRequested}' does not exist in the loaded playlist. ` +
`Make sure you've updated the 'playlist' prop to ` +
`PlayerContextProvider before you select this track!`
);
return;
}
this.selectTrackIndex(newTrackIndex);
}
handleMediaEnded() {
if (this.state.seekInProgress) {
// nothing to do if we're in the middle of a seek
// (this can happen if we're in seekMode: immediate)
return;
}
clearTimeout(this.gapLengthTimeout);
const { playlist, loadFirstTrackOnPlaylistComplete } = this.props;
if (!isPlaylistValid(playlist)) {
return;
}
const { cycle, activeTrackIndex } = this.state;
if (!cycle && activeTrackIndex + 1 >= playlist.length) {
if (loadFirstTrackOnPlaylistComplete) {
this.goToTrack({
index: 0,
track: playlist[0],
shouldPlay: false,
shouldForceLoad: true
});
}
return;
}
this.gapLengthTimeout = setTimeout(
this.forwardSkip,
this.props.gapLengthInSeconds * 1000
);
}
handleMediaStalled() {
this.setState(state => (state.stalled === true ? null : { stalled: true }));
}
handleMediaEmptied() {
this.setState(state => (state.paused === true ? null : { paused: true }));
}
handleMediaCanplay() {
this.setState(
state => (state.trackLoading === false ? null : { trackLoading: false })
);
}
handleMediaCanplaythrough() {
this.setState(
state => (state.stalled === false ? null : { stalled: false })
);
}
handleMediaTimeupdate() {
const { currentTime, played } = this.media;
const { onTimeUpdate, playlist } = this.props;
const { activeTrackIndex, trackLoading } = this.state;
if (trackLoading) {
// we'll get another time update when the track loads
// but for now this helps us avoid unnecessarily
// jumping back to currentTime: 0 in the UI while
// the track is loading.
return;
}
this.setState(state => ({
currentTime,
playedRanges: getTimeRangesArray(played),
maxKnownTime: Math.max(state.maxKnownTime, currentTime)
}));
if (onTimeUpdate) {
onTimeUpdate({
currentTime,
track: playlist[activeTrackIndex],
trackIndex: activeTrackIndex
});
}
}
handleMediaLoadeddata() {
if (this.media.currentTime !== this.state.currentTime) {
this.media.currentTime = this.state.currentTime;
}
}
handleMediaVolumechange() {
const { volume, muted } = this.media;
this.setState({ volume, muted });
}
handleMediaDurationchange() {
const { duration } = this.media;
const activeTrack = this.props.playlist[this.state.activeTrackIndex];
if (duration === Infinity) {
// This *could* be because we're consuming an unbounded stream.
// It could also be because of a weird iOS bug that we want to
// try to prevent. See https://github.com/benwiley4000/cassette/issues/355
// If we still end up with Infinity duration multiple times for
// the same track, we'll assume it's correct.
if (
activeTrack.isUnboundedStream ||
activeTrack === this.activeTrackAtLastDurationChange
) {
this.setState({
duration,
currentTime: 0
});
this.media.currentTime = 0;
} else {
const { paused } = this.state;
this.media.load();
if (!paused) {
// media.currentSrc is updated asynchronously so we should
// play async to avoid weird intermediate state issues
setTimeout(() => {
this.togglePause(false);
});
}
}
} else {
this.setState({ duration });
}
this.activeTrackAtLastDurationChange = activeTrack;
}
handleMediaProgress() {
this.setState({
bufferedRanges: getTimeRangesArray(this.media.buffered),
seekableRanges: getTimeRangesArray(this.media.seekable)
});
}
handleMediaLoopchange() {
const { loop } = this.media;
this.setState(state => (state.loop === loop ? null : { loop }));
}
handleMediaRatechange() {
const { playbackRate } = this.media;
this.setState(
state => (state.playbackRate === playbackRate ? null : { playbackRate })
);
}
togglePause(value) {
clearTimeout(this.delayTimeout);
const pause = typeof value === 'boolean' ? value : !this.state.paused;
if (pause) {
this.media.pause();
return;
}
if (!this.media.currentSrc) {
return;
}
try {
const playPromise = this.media.play();
if (playPromise && typeof playPromise.catch === 'function') {
playPromise
.catch(err => {
// AbortError is pretty much always called because we're skipping
// tracks quickly or hitting pause before a track has a chance to
// play. It's pretty safe to just ignore these error messages.
if (err.name !== 'AbortError') {
return Promise.reject(err);
}
})
.catch(playErrorHandler);
}
} catch (err) {
playErrorHandler(err);
}
}
// assumes playlist is valid - don't call without checking
goToTrack(args) {
clearTimeout(this.delayTimeout);
this.setState(prevState => getGoToTrackState({ prevState, ...args }));
}
selectTrackIndex(index) {
const { playlist } = this.props;
if (!isPlaylistValid(playlist)) {
return;
}
if (index < 0 || index > playlist.length) {
logWarning(`Playlist index ${index} is out of bounds!`);
return;
}
if (this.state.shuffle) {
this.shuffler.pickNextItem(index, this.state.activeTrackIndex);
}
this.goToTrack({ index, track: playlist[index] });
}
backSkip() {
const { playlist, stayOnBackSkipThreshold } = this.props;
const { media } = this;
const { cycle, activeTrackIndex, shuffle } = this.state;
if (
!isPlaylistValid(playlist) ||
media.currentTime >= stayOnBackSkipThreshold ||
(!cycle && activeTrackIndex < 1)
) {
media.currentTime = 0;
return;
}
let index;
if (shuffle) {
const previousItem = this.shuffler.findPreviousItem(activeTrackIndex);
if (previousItem === undefined) {
// if we aren't allowing backShuffle then we'll hit a stopping point.
media.currentTime = 0;
return;
}
index = findTrackIndexByUrl(playlist, previousItem);
} else {
index = activeTrackIndex - 1;
if (index < 0) {
index = playlist.length - 1;
}
}
this.goToTrack({ index, track: playlist[index], shouldForceLoad: true });
}
forwardSkip() {
const { playlist } = this.props;
const { cycle, activeTrackIndex, shuffle } = this.state;
if (
!isPlaylistValid(playlist) ||
(!cycle && activeTrackIndex + 1 >= playlist.length)
) {
return;
}
let index;
if (shuffle) {
index = findTrackIndexByUrl(
playlist,
this.shuffler.findNextItem(activeTrackIndex)
);
} else {
index = activeTrackIndex + 1;
if (index >= playlist.length) {
index = 0;
}
}
this.goToTrack({ index, track: playlist[index], shouldForceLoad: true });
}
seekPreview(targetTime) {
if (!isPlaylistValid(this.props.playlist)) {
return;
}
const baseStateUpdate = {
seekPreviewTime: targetTime,
seekInProgress: true
};
switch (this.props.seekMode) {
case 'paused':
this.setState(({ paused, awaitingResumeOnSeekComplete }) => ({
...baseStateUpdate,
awaitingResumeOnSeekComplete: paused
? awaitingResumeOnSeekComplete
: true,
currentTime: targetTime
}));
if (!this.state.trackLoading) {
this.media.currentTime = targetTime;
}
if (!this.state.paused) {
this.togglePause(true);
}
break;
case 'immediate':
this.setState(({ paused, awaitingResumeOnSeekComplete }) => ({
...baseStateUpdate,
awaitingResumeOnSeekComplete: paused
? awaitingResumeOnSeekComplete
: true,
currentTime: targetTime
}));
if (!this.state.trackLoading) {
this.media.currentTime = targetTime;
}
if (this.state.awaitingResumeOnSeekComplete && !this.media.ended) {
// if we earlier encountered an 'ended' state,
// un-pausing becomes necessary to resume playback
this.togglePause(false);
}
break;
case 'onrelease':
this.setState(baseStateUpdate);
break;
}
}
seekComplete(targetTime) {
const {
seekPreviewTime,
awaitingResumeOnSeekComplete,
trackLoading
} = this.state;
const baseStateUpdate = {
seekInProgress: false,
awaitingResumeOnSeekComplete: false
};