1 | import videojs from 'video.js';
|
2 |
|
3 | const defaultOptions = {
|
4 | errorInterval: 30,
|
5 | getSource(next) {
|
6 | let tech = this.tech({ IWillNotUseThisInPlugins: true });
|
7 | let sourceObj = tech.currentSource_;
|
8 |
|
9 | return next(sourceObj);
|
10 | }
|
11 | };
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | const initPlugin = function(player, options) {
|
21 | let lastCalled = 0;
|
22 | let seekTo = 0;
|
23 | let localOptions = videojs.mergeOptions(defaultOptions, options);
|
24 |
|
25 | player.ready(() => {
|
26 | player.trigger({type: 'usage', name: 'hls-error-reload-initialized'});
|
27 | });
|
28 |
|
29 | |
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | const loadedMetadataHandler = function() {
|
36 | if (seekTo) {
|
37 | player.currentTime(seekTo);
|
38 | }
|
39 | };
|
40 |
|
41 | |
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 | const setSource = function(sourceObj) {
|
48 | if (sourceObj === null || sourceObj === undefined) {
|
49 | return;
|
50 | }
|
51 | seekTo = (player.duration() !== Infinity && player.currentTime()) || 0;
|
52 |
|
53 | player.one('loadedmetadata', loadedMetadataHandler);
|
54 |
|
55 | player.src(sourceObj);
|
56 | player.trigger({type: 'usage', name: 'hls-error-reload'});
|
57 | player.play();
|
58 | };
|
59 |
|
60 | |
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | const errorHandler = function() {
|
67 |
|
68 |
|
69 | if (Date.now() - lastCalled < localOptions.errorInterval * 1000) {
|
70 | player.trigger({type: 'usage', name: 'hls-error-reload-canceled'});
|
71 | return;
|
72 | }
|
73 |
|
74 | if (!localOptions.getSource ||
|
75 | typeof localOptions.getSource !== 'function') {
|
76 | videojs.log.error(
|
77 | 'ERROR: reloadSourceOnError - The option getSource must be a function!');
|
78 | return;
|
79 | }
|
80 | lastCalled = Date.now();
|
81 |
|
82 | return localOptions.getSource.call(player, setSource);
|
83 | };
|
84 |
|
85 | |
86 |
|
87 |
|
88 |
|
89 |
|
90 | const cleanupEvents = function() {
|
91 | player.off('loadedmetadata', loadedMetadataHandler);
|
92 | player.off('error', errorHandler);
|
93 | player.off('dispose', cleanupEvents);
|
94 | };
|
95 |
|
96 | |
97 |
|
98 |
|
99 |
|
100 |
|
101 |
|
102 | const reinitPlugin = function(newOptions) {
|
103 | cleanupEvents();
|
104 | initPlugin(player, newOptions);
|
105 | };
|
106 |
|
107 | player.on('error', errorHandler);
|
108 | player.on('dispose', cleanupEvents);
|
109 |
|
110 |
|
111 |
|
112 | player.reloadSourceOnError = reinitPlugin;
|
113 | };
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|
120 |
|
121 | const reloadSourceOnError = function(options) {
|
122 | initPlugin(this, options);
|
123 | };
|
124 |
|
125 | export default reloadSourceOnError;
|