-
Notifications
You must be signed in to change notification settings - Fork 124
/
public_api.ts
2983 lines (2692 loc) · 97.7 KB
/
public_api.ts
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 2015 CANAL+ Group
*
* 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.
*/
/**
* This file defines the public API for the RxPlayer.
* It also starts the different sub-parts of the player on various API calls.
*/
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
concat as observableConcat,
connectable,
EMPTY,
merge as observableMerge,
Observable,
of as observableOf,
ReplaySubject,
Subject,
Subscription,
} from "rxjs";
// RxJS forgot to make that one more accessible it seems
import { ConnectableObservableLike } from "rxjs/internal/observable/connectable";
import {
distinctUntilChanged,
filter,
map,
mapTo,
mergeMap,
mergeMapTo,
share,
shareReplay,
skipWhile,
startWith,
switchMapTo,
take,
takeUntil,
} from "rxjs/operators";
import {
events,
exitFullscreen,
isFullscreen,
requestFullscreen,
} from "../../compat";
/* eslint-disable-next-line max-len */
import canRelyOnVideoVisibilityAndSize from "../../compat/can_rely_on_video_visibility_and_size";
import config from "../../config";
import {
ErrorCodes,
ErrorTypes,
formatError,
ICustomError,
IErrorCode,
IErrorType,
MediaError,
} from "../../errors";
import features from "../../features";
import log from "../../log";
import Manifest, {
Adaptation,
Period,
Representation,
} from "../../manifest";
import { IBifThumbnail } from "../../parsers/images/bif";
import areArraysOfNumbersEqual from "../../utils/are_arrays_of_numbers_equal";
import EventEmitter, {
fromEvent,
} from "../../utils/event_emitter";
import isNullOrUndefined from "../../utils/is_null_or_undefined";
import Logger from "../../utils/logger";
import noop from "../../utils/noop";
import objectAssign from "../../utils/object_assign";
import PPromise from "../../utils/promise";
import {
getLeftSizeOfRange,
getPlayedSizeOfRange,
getSizeOfRange,
} from "../../utils/ranges";
import warnOnce from "../../utils/warn_once";
import {
clearEMESession,
disposeEME,
getCurrentKeySystem,
} from "../eme";
import {
IManifestFetcherParsedResult,
IManifestFetcherWarningEvent,
ManifestFetcher,
SegmentFetcherCreator,
} from "../fetchers";
import initializeMediaSourcePlayback, {
IInitEvent,
ILoadedEvent,
IReloadingMediaSourceEvent,
IStalledEvent,
} from "../init";
import { IStreamEventData } from "../init/stream_events_emitter";
import SegmentBuffersStore, {
IBufferedChunk,
IBufferType,
} from "../segment_buffers";
import { IInbandEvent } from "../stream";
import createClock, {
IClockTick,
} from "./clock";
import emitSeekEvents from "./emit_seek_events";
import getPlayerState, {
IPlayerState,
PLAYER_STATES,
} from "./get_player_state";
import MediaElementTrackChoiceManager from "./media_element_track_choice_manager";
import {
checkReloadOptions,
IConstructorOptions,
ILoadVideoOptions,
IParsedLoadVideoOptions,
parseConstructorOptions,
parseLoadVideoOptions,
} from "./option_utils";
import TrackChoiceManager, {
IAudioTrackPreference,
ITextTrackPreference,
ITMAudioTrack,
ITMAudioTrackListItem,
ITMTextTrack,
ITMTextTrackListItem,
ITMVideoTrack,
ITMVideoTrackListItem,
IVideoTrackPreference,
} from "./track_choice_manager";
/* eslint-disable @typescript-eslint/naming-convention */
const { DEFAULT_UNMUTED_VOLUME } = config;
const { isActive,
isVideoVisible,
onEnded$,
onFullscreenChange$,
onPlayPause$,
onPictureInPictureEvent$,
onSeeking$,
onTextTrackChanges$,
videoWidth$ } = events;
/** Payload emitted with a `positionUpdate` event. */
interface IPositionUpdateItem {
/** current position the player is in, in seconds. */
position : number;
/** Last position set for the current media currently, in seconds. */
duration : number;
/** Playback rate (i.e. speed) at which the current media is played. */
playbackRate : number;
/** Amount of buffer available for now in front of the current position, in seconds. */
bufferGap : number;
/** Current maximum seekable position. */
maximumBufferTime? : number;
wallClockTime? : number;
/**
* Only for live contents. Difference between the "live edge" and the current
* position, in seconds.
*/
liveGap? : number;
}
/** Payload emitted with a `bitrateEstimationChange` event. */
interface IBitrateEstimate {
/** The type of buffer this estimate was done for (e.g. "audio). */
type : IBufferType;
/** The calculated bitrate, in bits per seconds. */
bitrate : number | undefined;
}
export type IStreamEvent = { data: IStreamEventData;
start: number;
end: number;
onExit?: () => void; } |
{ data: IStreamEventData;
start: number; };
/** Every events sent by the RxPlayer's public API. */
interface IPublicAPIEvent {
playerStateChange : string;
positionUpdate : IPositionUpdateItem;
audioTrackChange : ITMAudioTrack | null;
textTrackChange : ITMTextTrack | null;
videoTrackChange : ITMVideoTrack | null;
audioBitrateChange : number;
videoBitrateChange : number;
imageTrackUpdate : { data: IBifThumbnail[] };
fullscreenChange : boolean;
bitrateEstimationChange : IBitrateEstimate;
volumeChange : number;
error : ICustomError | Error;
warning : ICustomError | Error;
nativeTextTracksChange : TextTrack[];
periodChange : Period;
availableAudioBitratesChange : number[];
availableVideoBitratesChange : number[];
availableAudioTracksChange : ITMAudioTrackListItem[];
availableTextTracksChange : ITMTextTrackListItem[];
availableVideoTracksChange : ITMVideoTrackListItem[];
decipherabilityUpdate : Array<{ manifest : Manifest;
period : Period;
adaptation : Adaptation;
representation : Representation; }>;
seeking : null;
seeked : null;
streamEvent : IStreamEvent;
streamEventSkip : IStreamEvent;
inbandEvents : IInbandEvent[];
}
/**
* @class Player
* @extends EventEmitter
*/
class Player extends EventEmitter<IPublicAPIEvent> {
/** Current version of the RxPlayer. */
public static version : string;
/** Current version of the RxPlayer. */
public readonly version : string;
/** Media element attached to the RxPlayer. */
public videoElement : HTMLMediaElement|null; // null on dispose
/** Logger the RxPlayer uses. */
public readonly log : Logger;
/**
* Current state of the RxPlayer.
* Please use `getPlayerState()` instead.
*/
public state : IPlayerState;
/**
* Emit when the the RxPlayer is not needed anymore and thus all resources
* used for its normal functionment can be freed.
* The player will be unusable after that.
*/
private readonly _priv_destroy$ : Subject<void>;
/**
* Emit true when the previous content is cleaning-up, false when it's done.
* A new content cannot be launched until it emits false.
*/
private readonly _priv_contentLock$ : BehaviorSubject<boolean>;
/**
* Changes on "play" and "pause" events from the media elements.
* Switches to ``true`` whent the "play" event was the last received.
* Switches to ``false`` whent the "pause" event was the last received.
* ``false`` if no such event was received for the current loaded content.
*/
private readonly _priv_playing$ : ReplaySubject<boolean>;
/**
* The speed that should be applied to playback.
* Used instead of videoElement.playbackRate to allow more flexibility.
*/
private readonly _priv_speed$ : BehaviorSubject<number>;
/** Store buffer-related options used needed when initializing a content. */
private readonly _priv_bufferOptions : {
/** Emit the last wanted buffer goal. */
wantedBufferAhead$ : BehaviorSubject<number>;
/** Maximum kept buffer ahead in the current position, in seconds. */
maxBufferAhead$ : BehaviorSubject<number>;
/** Maximum kept buffer behind in the current position, in seconds. */
maxBufferBehind$ : BehaviorSubject<number>;
};
/** Information on the current bitrate settings. */
private readonly _priv_bitrateInfos : {
/**
* Store last bitrates for each type for ABRManager instanciation.
* Store the initial wanted bitrates at first.
*/
lastBitrates : { audio? : number;
video? : number;
text? : number;
image? : number; };
/** Store last wanted minAutoBitrates for the next ABRManager instanciation. */
minAutoBitrates : { audio : BehaviorSubject<number>;
video : BehaviorSubject<number>; };
/** Store last wanted maxAutoBitrates for the next ABRManager instanciation. */
maxAutoBitrates : { audio : BehaviorSubject<number>;
video : BehaviorSubject<number>; };
/** Store last wanted manual bitrates for the next ABRManager instanciation. */
manualBitrates : { audio : BehaviorSubject<number>;
video : BehaviorSubject<number>; };
};
/**
* Current fatal error which STOPPED the player.
* `null` if no fatal error was received for the current or last content.
*/
private _priv_currentError : Error|null;
/**
* Information about the current content being played.
* `null` when no content is currently loading or loaded.
*/
private _priv_contentInfos : null | {
/**
* URL of the Manifest (or just of the content for DirectFile contents)
* currently being played.
*/
url? : string;
/** Subject allowing to stop playing that content. */
stop$ : Subject<void>;
/**
* `true` if the current content is in DirectFile mode.
* `false` is the current content has a transport protocol (Smooth/DASH...).
*/
isDirectFile : boolean;
/**
* Current Image Track Data associated to the content.
* `null` if the current content has no image playlist linked to it.
* @deprecated
*/
thumbnails : IBifThumbnail[]|null;
/**
* Manifest linked to the current content.
* `null` if the current content loaded has no manifest or if the content is
* not yet loaded.
*/
manifest : Manifest|null;
/**
* Current Period being played.
* `null` if no Period is being played.
*/
currentPeriod : Period|null;
/**
* Store currently considered adaptations, per active period.
* `null` if no Adaptation is active
*/
activeAdaptations : {
[periodId : string] : Partial<Record<IBufferType, Adaptation|null>>;
} | null;
/**
* Store currently considered representations, per active period.
* `null` if no Representation is active
*/
activeRepresentations : {
[periodId : string] : Partial<Record<IBufferType, Representation|null>>;
} | null;
/** Store starting audio track if one. */
initialAudioTrack : undefined|IAudioTrackPreference;
/** Store starting text track if one. */
initialTextTrack : undefined|ITextTrackPreference;
/** Keep information on the active SegmentBuffers. */
segmentBuffersStore : SegmentBuffersStore | null;
};
/** List of favorite audio tracks, in preference order. */
private _priv_preferredAudioTracks : IAudioTrackPreference[];
/** List of favorite text tracks, in preference order. */
private _priv_preferredTextTracks : ITextTrackPreference[];
/** List of favorite video tracks, in preference order. */
private _priv_preferredVideoTracks : IVideoTrackPreference[];
/** If `true` trickMode video tracks will be chosen if available. */
private _priv_preferTrickModeTracks : boolean;
/**
* TrackChoiceManager instance linked to the current content.
* `null` if no content has been loaded or if the current content loaded
* has no TrackChoiceManager.
*/
private _priv_trackChoiceManager : TrackChoiceManager|null;
/**
* MediaElementTrackChoiceManager instance linked to the current content.
* `null` if no content has been loaded or if the current content loaded
* has no MediaElementTrackChoiceManager.
*/
private _priv_mediaElementTrackChoiceManager : MediaElementTrackChoiceManager|null;
/** Emit last picture in picture event. */
private _priv_pictureInPictureEvent$ : ReplaySubject<events.IPictureInPictureEvent>;
/** Store wanted configuration for the `limitVideoWidth` option. */
private readonly _priv_limitVideoWidth : boolean;
/** Store wanted configuration for the `throttleWhenHidden` option. */
private readonly _priv_throttleWhenHidden : boolean;
/** Store wanted configuration for the `throttleVideoBitrateWhenHidden` option. */
private readonly _priv_throttleVideoBitrateWhenHidden : boolean;
/** Store volume when mute is called, to restore it on unmute. */
private _priv_mutedMemory : number;
/**
* Store last state of various values sent as events, to avoid re-triggering
* them multiple times in a row.
*
* All those events are linked to the content being played and can be cleaned
* on stop.
*/
private _priv_contentEventsMemory : {
[P in keyof IPublicAPIEvent]? : IPublicAPIEvent[P];
};
/** Determines whether or not the player should stop at the end of video playback. */
private readonly _priv_stopAtEnd : boolean;
/** Information about last content being played. */
private _priv_lastContentPlaybackInfos : { options?: IParsedLoadVideoOptions;
manifest?: Manifest;
lastPlaybackPosition?: number; };
/** All possible Error types emitted by the RxPlayer. */
static get ErrorTypes() : Record<IErrorType, IErrorType> {
return ErrorTypes;
}
/** All possible Error codes emitted by the RxPlayer. */
static get ErrorCodes() : Record<IErrorCode, IErrorCode> {
return ErrorCodes;
}
/**
* Current log level.
* Update current log level.
* Should be either (by verbosity ascending):
* - "NONE"
* - "ERROR"
* - "WARNING"
* - "INFO"
* - "DEBUG"
* Any other value will be translated to "NONE".
*/
static get LogLevel() : string {
return log.getLevel();
}
static set LogLevel(logLevel : string) {
log.setLevel(logLevel);
}
/**
* @constructor
* @param {Object} options
*/
constructor(options : IConstructorOptions = {}) {
super();
const { initialAudioBitrate,
initialVideoBitrate,
limitVideoWidth,
minAudioBitrate,
minVideoBitrate,
maxAudioBitrate,
maxBufferAhead,
maxBufferBehind,
maxVideoBitrate,
preferredAudioTracks,
preferredTextTracks,
preferredVideoTracks,
throttleWhenHidden,
throttleVideoBitrateWhenHidden,
videoElement,
wantedBufferAhead,
stopAtEnd } = parseConstructorOptions(options);
// Workaround to support Firefox autoplay on FF 42.
// See: https://bugzilla.mozilla.org/show_bug.cgi?id=1194624
videoElement.preload = "auto";
this.version = /* PLAYER_VERSION */"3.26.0";
this.log = log;
this.state = "STOPPED";
this.videoElement = videoElement;
this._priv_destroy$ = new Subject();
this._priv_pictureInPictureEvent$ = new ReplaySubject(1);
onPictureInPictureEvent$(videoElement)
.pipe(takeUntil(this._priv_destroy$))
.subscribe(this._priv_pictureInPictureEvent$);
/** @deprecated */
onFullscreenChange$(videoElement)
.pipe(takeUntil(this._priv_destroy$))
/* eslint-disable import/no-deprecated */
.subscribe(() => this.trigger("fullscreenChange", this.isFullscreen()));
/* eslint-enable import/no-deprecated */
/** @deprecated */
onTextTrackChanges$(videoElement.textTracks)
.pipe(
takeUntil(this._priv_destroy$),
map((evt : Event) => { // prepare TextTrack array
const target = evt.target as TextTrackList;
const arr : TextTrack[] = [];
for (let i = 0; i < target.length; i++) {
const textTrack = target[i];
arr.push(textTrack);
}
return arr;
}),
// We can have two consecutive textTrackChanges with the exact same
// payload when we perform multiple texttrack operations before the event
// loop is freed.
// In that case we only want to fire one time the observable.
distinctUntilChanged((textTracksA, textTracksB) => {
if (textTracksA.length !== textTracksB.length) {
return false;
}
for (let i = 0; i < textTracksA.length; i++) {
if (textTracksA[i] !== textTracksB[i]) {
return false;
}
}
return true;
})
)
.subscribe((x : TextTrack[]) => this._priv_onNativeTextTracksNext(x));
this._priv_playing$ = new ReplaySubject(1);
this._priv_speed$ = new BehaviorSubject(videoElement.playbackRate);
this._priv_preferTrickModeTracks = false;
this._priv_contentLock$ = new BehaviorSubject<boolean>(false);
this._priv_bufferOptions = {
wantedBufferAhead$: new BehaviorSubject(wantedBufferAhead),
maxBufferAhead$: new BehaviorSubject(maxBufferAhead),
maxBufferBehind$: new BehaviorSubject(maxBufferBehind),
};
this._priv_bitrateInfos = {
lastBitrates: { audio: initialAudioBitrate,
video: initialVideoBitrate },
minAutoBitrates: { audio: new BehaviorSubject(minAudioBitrate),
video: new BehaviorSubject(minVideoBitrate) },
maxAutoBitrates: { audio: new BehaviorSubject(maxAudioBitrate),
video: new BehaviorSubject(maxVideoBitrate) },
manualBitrates: { audio: new BehaviorSubject(-1),
video: new BehaviorSubject(-1) },
};
this._priv_throttleWhenHidden = throttleWhenHidden;
this._priv_throttleVideoBitrateWhenHidden = throttleVideoBitrateWhenHidden;
this._priv_limitVideoWidth = limitVideoWidth;
this._priv_mutedMemory = DEFAULT_UNMUTED_VOLUME;
this._priv_trackChoiceManager = null;
this._priv_mediaElementTrackChoiceManager = null;
this._priv_currentError = null;
this._priv_contentInfos = null;
this._priv_contentEventsMemory = {};
this._priv_stopAtEnd = stopAtEnd;
this._priv_setPlayerState(PLAYER_STATES.STOPPED);
this._priv_preferredAudioTracks = preferredAudioTracks;
this._priv_preferredTextTracks = preferredTextTracks;
this._priv_preferredVideoTracks = preferredVideoTracks;
this._priv_lastContentPlaybackInfos = {};
}
/**
* Stop the playback for the current content.
*/
stop() : void {
if (this._priv_contentInfos !== null) {
this._priv_contentInfos.stop$.next();
this._priv_contentInfos.stop$.complete();
}
this._priv_cleanUpCurrentContentState();
if (this.state !== PLAYER_STATES.STOPPED) {
this._priv_setPlayerState(PLAYER_STATES.STOPPED);
}
}
/**
* Free the resources used by the player.
* /!\ The player cannot be "used" anymore after this method has been called.
*/
dispose() : void {
// free resources linked to the loaded content
this.stop();
if (this.videoElement !== null) {
// free resources used for EME management
disposeEME(this.videoElement);
}
// free Observables linked to the Player instance
this._priv_destroy$.next();
this._priv_destroy$.complete();
// Complete all subjects
this._priv_playing$.complete();
this._priv_speed$.complete();
this._priv_contentLock$.complete();
this._priv_bufferOptions.wantedBufferAhead$.complete();
this._priv_bufferOptions.maxBufferAhead$.complete();
this._priv_bufferOptions.maxBufferBehind$.complete();
this._priv_pictureInPictureEvent$.complete();
this._priv_bitrateInfos.manualBitrates.video.complete();
this._priv_bitrateInfos.manualBitrates.audio.complete();
this._priv_bitrateInfos.minAutoBitrates.video.complete();
this._priv_bitrateInfos.minAutoBitrates.audio.complete();
this._priv_bitrateInfos.maxAutoBitrates.video.complete();
this._priv_bitrateInfos.maxAutoBitrates.audio.complete();
this._priv_lastContentPlaybackInfos = {};
// un-attach video element
this.videoElement = null;
}
/**
* Load a new video.
* @param {Object} opts
*/
loadVideo(opts : ILoadVideoOptions) : void {
const options = parseLoadVideoOptions(opts);
log.info("API: Calling loadvideo", options);
this._priv_lastContentPlaybackInfos = { options };
this._priv_initializeContentPlayback(options);
}
/**
* Reload last content. Init media playback without fetching again
* the manifest.
* @param {Object} reloadOpts
*/
reload(reloadOpts?: { reloadAt?: { position?: number; relative?: number } }): void {
const { options,
manifest,
lastPlaybackPosition } = this._priv_lastContentPlaybackInfos;
if (options === undefined ||
manifest === undefined ||
lastPlaybackPosition === undefined) {
throw new Error("API: Can't reload without having previously loaded a content.");
}
checkReloadOptions(reloadOpts);
let startAtPositon: number;
if (reloadOpts !== undefined &&
reloadOpts.reloadAt !== undefined &&
reloadOpts.reloadAt.position !== undefined) {
startAtPositon = reloadOpts.reloadAt.position;
} else {
let playbackPosition: number;
if (this.state === "STOPPED" || this.state === "ENDED") {
playbackPosition = lastPlaybackPosition;
} else {
if (this.videoElement === null) {
throw new Error("Can't reload when video element does not exist.");
}
playbackPosition = this.videoElement.currentTime;
}
if (reloadOpts !== undefined &&
reloadOpts.reloadAt !== undefined &&
reloadOpts.reloadAt.relative !== undefined) {
startAtPositon = reloadOpts.reloadAt.relative + playbackPosition;
} else {
startAtPositon = playbackPosition;
}
}
const newOptions = { ...options,
initialManifest: manifest };
newOptions.startAt = { position: startAtPositon };
this._priv_initializeContentPlayback(newOptions);
}
/**
* From given options, initialize content playback.
* @param {Object} options
*/
private _priv_initializeContentPlayback(options : IParsedLoadVideoOptions) : void {
const { autoPlay,
audioTrackSwitchingMode,
defaultAudioTrack,
defaultTextTrack,
enableFastSwitching,
initialManifest,
keySystems,
lowLatencyMode,
manualBitrateSwitchingMode,
minimumManifestUpdateInterval,
networkConfig,
onCodecSwitch,
startAt,
transport,
transportOptions,
url } = options;
// Perform multiple checks on the given options
if (this.videoElement === null) {
throw new Error("the attached video element is disposed");
}
const isDirectFile = transport === "directfile";
/** Subject which will emit to stop the current content. */
const stopContent$ = new Subject<void>();
/** Future `this._priv_contentInfos` related to this content. */
const contentInfos = { url,
stop$: stopContent$,
isDirectFile,
segmentBuffersStore: null,
thumbnails: null,
manifest: null,
currentPeriod: null,
activeAdaptations: null,
activeRepresentations: null,
initialAudioTrack: defaultAudioTrack,
initialTextTrack: defaultTextTrack };
const videoElement = this.videoElement;
/** Global "clock" used for content playback */
const { setCurrentTime, clock$ } = createClock(videoElement, {
withMediaSource: !isDirectFile,
lowLatencyMode,
});
/** Emit playback events. */
let playback$ : ConnectableObservableLike<IInitEvent>;
const speed$ = this._priv_speed$.pipe(distinctUntilChanged());
if (!isDirectFile) {
const transportFn = features.transports[transport];
if (typeof transportFn !== "function") {
// Stop previous content and reset its state
this.stop();
this._priv_currentError = null;
this._priv_playing$.next(false);
throw new Error(`transport "${transport}" not supported`);
}
const transportPipelines = transportFn(transportOptions);
const { offlineRetry, segmentRetry, manifestRetry } = networkConfig;
/** Interface used to load and refresh the Manifest. */
const manifestFetcher = new ManifestFetcher(url,
transportPipelines,
{ lowLatencyMode,
maxRetryRegular: manifestRetry,
maxRetryOffline: offlineRetry });
/** Interface used to download segments. */
const segmentFetcherCreator = new SegmentFetcherCreator<any>(
transportPipelines,
{ lowLatencyMode,
maxRetryOffline: offlineRetry,
maxRetryRegular: segmentRetry });
/** Observable emitting the initial Manifest */
let manifest$ : Observable<IManifestFetcherParsedResult |
IManifestFetcherWarningEvent>;
if (initialManifest instanceof Manifest) {
manifest$ = observableOf({ type: "parsed",
manifest: initialManifest });
} else if (initialManifest !== undefined) {
manifest$ = manifestFetcher.parse(initialManifest, { previousManifest: null,
unsafeMode: false });
} else {
manifest$ = manifestFetcher.fetch(url).pipe(
mergeMap((response) => response.type === "warning" ?
observableOf(response) : // bubble-up warnings
response.parse({ previousManifest: null, unsafeMode: false })));
}
// Load the Manifest right now and share it with every subscriber until
// the content is stopped
manifest$ = manifest$.pipe(takeUntil(stopContent$),
shareReplay());
manifest$.subscribe();
// now that the Manifest is loading, stop previous content and reset state
// This is done after fetching the Manifest as `stop` could technically
// take time.
this.stop();
this._priv_currentError = null;
this._priv_playing$.next(false);
this._priv_contentInfos = contentInfos;
const relyOnVideoVisibilityAndSize = canRelyOnVideoVisibilityAndSize();
const throttlers = { throttle: {},
throttleBitrate: {},
limitWidth: {} };
if (this._priv_throttleWhenHidden) {
if (!relyOnVideoVisibilityAndSize) {
log.warn("API: Can't apply throttleWhenHidden because " +
"browser can't be trusted for visibility.");
} else {
throttlers.throttle = {
video: isActive().pipe(
map(active => active ? Infinity :
0),
takeUntil(stopContent$)),
};
}
}
if (this._priv_throttleVideoBitrateWhenHidden) {
if (!relyOnVideoVisibilityAndSize) {
log.warn("API: Can't apply throttleVideoBitrateWhenHidden because " +
"browser can't be trusted for visibility.");
} else {
throttlers.throttleBitrate = {
video: isVideoVisible(this._priv_pictureInPictureEvent$).pipe(
map(active => active ? Infinity :
0),
takeUntil(stopContent$)),
};
}
}
if (this._priv_limitVideoWidth) {
if (!relyOnVideoVisibilityAndSize) {
log.warn("API: Can't apply limitVideoWidth because browser can't be " +
"trusted for video size.");
} else {
throttlers.limitWidth = {
video: videoWidth$(videoElement, this._priv_pictureInPictureEvent$)
.pipe(takeUntil(stopContent$)),
};
}
}
/** Options used by the ABR Manager. */
const adaptiveOptions = {
initialBitrates: this._priv_bitrateInfos.lastBitrates,
lowLatencyMode,
manualBitrates: this._priv_bitrateInfos.manualBitrates,
minAutoBitrates: this._priv_bitrateInfos.minAutoBitrates,
maxAutoBitrates: this._priv_bitrateInfos.maxAutoBitrates,
throttlers,
};
/** Options used by the TextTrack SegmentBuffer. */
const textTrackOptions = options.textTrackMode === "native" ?
{ textTrackMode: "native" as const,
hideNativeSubtitle: options.hideNativeSubtitle } :
{ textTrackMode: "html" as const,
textTrackElement: options.textTrackElement };
const bufferOptions = objectAssign({ audioTrackSwitchingMode,
enableFastSwitching,
manualBitrateSwitchingMode,
onCodecSwitch },
this._priv_bufferOptions);
// We've every options set up. Start everything now
const init$ = initializeMediaSourcePlayback({ adaptiveOptions,
autoPlay,
bufferOptions,
clock$,
keySystems,
lowLatencyMode,
manifest$,
manifestFetcher,
mediaElement: videoElement,
minimumManifestUpdateInterval,
segmentFetcherCreator,
setCurrentTime,
speed$,
startAt,
textTrackOptions })
.pipe(takeUntil(stopContent$));
playback$ = connectable(init$, { connector: () => new Subject(),
resetOnDisconnect: false });
} else {
// Stop previous content and reset its state
this.stop();
this._priv_currentError = null;
this._priv_playing$.next(false);
if (features.directfile === null) {
throw new Error("DirectFile feature not activated in your build.");
}
this._priv_contentInfos = contentInfos;
this._priv_mediaElementTrackChoiceManager =
new features.directfile.mediaElementTrackChoiceManager(this.videoElement);
const preferredAudioTracks = defaultAudioTrack === undefined ?
this._priv_preferredAudioTracks :
[defaultAudioTrack];
this._priv_mediaElementTrackChoiceManager
.setPreferredAudioTracks(preferredAudioTracks, true);
const preferredTextTracks = defaultTextTrack === undefined ?
this._priv_preferredTextTracks :
[defaultTextTrack];
this._priv_mediaElementTrackChoiceManager
.setPreferredTextTracks(preferredTextTracks, true);
this._priv_mediaElementTrackChoiceManager
.setPreferredVideoTracks(this._priv_preferredVideoTracks, true);
this.trigger("availableAudioTracksChange",
this._priv_mediaElementTrackChoiceManager.getAvailableAudioTracks());
this.trigger("availableVideoTracksChange",
this._priv_mediaElementTrackChoiceManager.getAvailableVideoTracks());
this.trigger("availableTextTracksChange",
this._priv_mediaElementTrackChoiceManager.getAvailableTextTracks());
this.trigger("audioTrackChange",
this._priv_mediaElementTrackChoiceManager.getChosenAudioTrack()
?? null);
this.trigger("textTrackChange",
this._priv_mediaElementTrackChoiceManager.getChosenTextTrack()
?? null);
this.trigger("videoTrackChange",
this._priv_mediaElementTrackChoiceManager.getChosenVideoTrack()
?? null);
this._priv_mediaElementTrackChoiceManager
.addEventListener("availableVideoTracksChange", (val) =>
this.trigger("availableVideoTracksChange", val));
this._priv_mediaElementTrackChoiceManager
.addEventListener("availableAudioTracksChange", (val) =>
this.trigger("availableAudioTracksChange", val));
this._priv_mediaElementTrackChoiceManager
.addEventListener("availableTextTracksChange", (val) =>
this.trigger("availableTextTracksChange", val));
this._priv_mediaElementTrackChoiceManager
.addEventListener("audioTrackChange", (val) =>
this.trigger("audioTrackChange", val));
this._priv_mediaElementTrackChoiceManager
.addEventListener("videoTrackChange", (val) =>
this.trigger("videoTrackChange", val));
this._priv_mediaElementTrackChoiceManager
.addEventListener("textTrackChange", (val) =>
this.trigger("textTrackChange", val));
const directfileInit$ =
features.directfile.initDirectFile({ autoPlay,
clock$,
keySystems,
mediaElement: videoElement,
speed$: this._priv_speed$,
startAt,
setCurrentTime,
url })
.pipe(takeUntil(stopContent$));
playback$ = connectable(directfileInit$, { connector: () => new Subject(),
resetOnDisconnect: false });
}
/** Emit an object when the player "stalls" and null when it un-stalls */
const stalled$ = playback$.pipe(
filter((evt) : evt is IStalledEvent => evt.type === "stalled" ||
evt.type === "unstalled"),
map(x => x.value),
distinctUntilChanged((wasStalled, isStalled) => {
return wasStalled === null && isStalled === null ||
(wasStalled !== null && isStalled !== null &&
wasStalled.reason === isStalled.reason);
}));
/** Emit when the content is considered "loaded". */
const loaded$ = playback$.pipe(
filter((evt) : evt is ILoadedEvent => evt.type === "loaded"),