]>
Commit | Line | Data |
---|---|---|
83fcadac C |
1 | // Thanks https://github.com/streamroot/videojs-hlsjs-plugin |
2 | // We duplicated this plugin to choose the hls.js version we want, because streamroot only provide a bundled file | |
3 | ||
e367da94 | 4 | import Hlsjs, { ErrorData, HlsConfig, Level, LevelSwitchingData, ManifestParsedData } from 'hls.js' |
512decf3 | 5 | import videojs from 'video.js' |
e367da94 | 6 | import { HlsjsConfigHandlerOptions, PeerTubeResolution, VideoJSTechHLS } from '../peertube-videojs-typings' |
83fcadac C |
7 | |
8 | type ErrorCounts = { | |
9 | [ type: string ]: number | |
10 | } | |
11 | ||
12 | type Metadata = { | |
134006b0 | 13 | levels: Level[] |
83fcadac C |
14 | } |
15 | ||
9df52d66 C |
16 | type HookFn = (player: videojs.Player, hljs: Hlsjs) => void |
17 | ||
83fcadac C |
18 | const registerSourceHandler = function (vjs: typeof videojs) { |
19 | if (!Hlsjs.isSupported()) { | |
20 | console.warn('Hls.js is not supported in this browser!') | |
21 | return | |
22 | } | |
23 | ||
24 | const html5 = vjs.getTech('Html5') | |
25 | ||
26 | if (!html5) { | |
27 | console.error('Not supported version if video.js') | |
28 | return | |
29 | } | |
30 | ||
31 | // FIXME: typings | |
32 | (html5 as any).registerSourceHandler({ | |
33 | canHandleSource: function (source: videojs.Tech.SourceObject) { | |
34 | const hlsTypeRE = /^application\/x-mpegURL|application\/vnd\.apple\.mpegurl$/i | |
35 | const hlsExtRE = /\.m3u8/i | |
36 | ||
37 | if (hlsTypeRE.test(source.type)) return 'probably' | |
38 | if (hlsExtRE.test(source.src)) return 'maybe' | |
39 | ||
40 | return '' | |
41 | }, | |
42 | ||
43 | handleSource: function (source: videojs.Tech.SourceObject, tech: VideoJSTechHLS) { | |
44 | if (tech.hlsProvider) { | |
45 | tech.hlsProvider.dispose() | |
46 | } | |
47 | ||
48 | tech.hlsProvider = new Html5Hlsjs(vjs, source, tech) | |
49 | ||
50 | return tech.hlsProvider | |
51 | } | |
52 | }, 0); | |
53 | ||
54 | // FIXME: typings | |
55 | (vjs as any).Html5Hlsjs = Html5Hlsjs | |
56 | } | |
57 | ||
7e37e111 | 58 | function hlsjsConfigHandler (this: videojs.Player, options: HlsjsConfigHandlerOptions) { |
83fcadac C |
59 | const player = this |
60 | ||
61 | if (!options) return | |
62 | ||
63 | if (!player.srOptions_) { | |
64 | player.srOptions_ = {} | |
65 | } | |
66 | ||
67 | if (!player.srOptions_.hlsjsConfig) { | |
68 | player.srOptions_.hlsjsConfig = options.hlsjsConfig | |
69 | } | |
70 | ||
83fcadac C |
71 | if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) { |
72 | player.srOptions_.levelLabelHandler = options.levelLabelHandler | |
73 | } | |
74 | } | |
75 | ||
76 | const registerConfigPlugin = function (vjs: typeof videojs) { | |
77 | // Used in Brightcove since we don't pass options directly there | |
78 | const registerVjsPlugin = vjs.registerPlugin || vjs.plugin | |
79 | registerVjsPlugin('hlsjs', hlsjsConfigHandler) | |
80 | } | |
81 | ||
82 | class Html5Hlsjs { | |
9df52d66 | 83 | private static readonly hooks: { [id: string]: HookFn[] } = {} |
83fcadac C |
84 | |
85 | private readonly videoElement: HTMLVideoElement | |
86 | private readonly errorCounts: ErrorCounts = {} | |
7e37e111 | 87 | private readonly player: videojs.Player |
83fcadac C |
88 | private readonly tech: videojs.Tech |
89 | private readonly source: videojs.Tech.SourceObject | |
90 | private readonly vjs: typeof videojs | |
91 | ||
134006b0 C |
92 | private hls: Hlsjs |
93 | private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null | |
83fcadac C |
94 | |
95 | private _duration: number = null | |
96 | private metadata: Metadata = null | |
97 | private isLive: boolean = null | |
98 | private dvrDuration: number = null | |
99 | private edgeMargin: number = null | |
100 | ||
e367da94 C |
101 | private handlers: { [ id in 'play' ]: EventListener } = { |
102 | play: null | |
83fcadac C |
103 | } |
104 | ||
83fcadac C |
105 | constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) { |
106 | this.vjs = vjs | |
107 | this.source = source | |
108 | ||
109 | this.tech = tech; | |
110 | (this.tech as any).name_ = 'Hlsjs' | |
111 | ||
112 | this.videoElement = tech.el() as HTMLVideoElement | |
113 | this.player = vjs((tech.options_ as any).playerId) | |
114 | ||
115 | this.videoElement.addEventListener('error', event => { | |
116 | let errorTxt: string | |
d0dd9813 | 117 | const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error |
83fcadac | 118 | |
d0dd9813 C |
119 | if (!mediaError) return |
120 | ||
121 | console.log(mediaError) | |
83fcadac C |
122 | switch (mediaError.code) { |
123 | case mediaError.MEDIA_ERR_ABORTED: | |
124 | errorTxt = 'You aborted the video playback' | |
125 | break | |
126 | case mediaError.MEDIA_ERR_DECODE: | |
9df52d66 C |
127 | errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' + |
128 | 'your browser did not support' | |
83fcadac C |
129 | this._handleMediaError(mediaError) |
130 | break | |
131 | case mediaError.MEDIA_ERR_NETWORK: | |
132 | errorTxt = 'A network error caused the video download to fail part-way' | |
133 | break | |
134 | case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED: | |
135 | errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported' | |
136 | break | |
137 | ||
138 | default: | |
139 | errorTxt = mediaError.message | |
140 | } | |
141 | ||
142 | console.error('MEDIA_ERROR: ', errorTxt) | |
143 | }) | |
144 | ||
145 | this.initialize() | |
146 | } | |
147 | ||
148 | duration () { | |
51d81175 | 149 | if (this._duration === Infinity) return Infinity |
22f25c74 C |
150 | if (!isNaN(this.videoElement.duration)) return this.videoElement.duration |
151 | ||
152 | return this._duration || 0 | |
83fcadac C |
153 | } |
154 | ||
155 | seekable () { | |
156 | if (this.hls.media) { | |
157 | if (!this.isLive) { | |
158 | return this.vjs.createTimeRanges(0, this.hls.media.duration) | |
159 | } | |
160 | ||
161 | // Video.js doesn't seem to like floating point timeranges | |
162 | const startTime = Math.round(this.hls.media.duration - this.dvrDuration) | |
163 | const endTime = Math.round(this.hls.media.duration - this.edgeMargin) | |
164 | ||
165 | return this.vjs.createTimeRanges(startTime, endTime) | |
166 | } | |
167 | ||
168 | return this.vjs.createTimeRanges() | |
169 | } | |
170 | ||
171 | // See comment for `initialize` method. | |
172 | dispose () { | |
173 | this.videoElement.removeEventListener('play', this.handlers.play) | |
83fcadac | 174 | |
83fcadac C |
175 | this.hls.destroy() |
176 | } | |
177 | ||
9df52d66 C |
178 | static addHook (type: string, callback: HookFn) { |
179 | Html5Hlsjs.hooks[type] = this.hooks[type] || [] | |
180 | Html5Hlsjs.hooks[type].push(callback) | |
83fcadac C |
181 | } |
182 | ||
9df52d66 C |
183 | static removeHook (type: string, callback: HookFn) { |
184 | if (Html5Hlsjs.hooks[type] === undefined) return false | |
83fcadac | 185 | |
9df52d66 | 186 | const index = Html5Hlsjs.hooks[type].indexOf(callback) |
83fcadac C |
187 | if (index === -1) return false |
188 | ||
9df52d66 | 189 | Html5Hlsjs.hooks[type].splice(index, 1) |
83fcadac C |
190 | |
191 | return true | |
192 | } | |
193 | ||
194 | private _executeHooksFor (type: string) { | |
9df52d66 | 195 | if (Html5Hlsjs.hooks[type] === undefined) { |
83fcadac C |
196 | return |
197 | } | |
198 | ||
199 | // ES3 and IE < 9 | |
9df52d66 C |
200 | for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) { |
201 | Html5Hlsjs.hooks[type][i](this.player, this.hls) | |
83fcadac C |
202 | } |
203 | } | |
204 | ||
205 | private _handleMediaError (error: any) { | |
9df52d66 | 206 | if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) { |
83fcadac C |
207 | console.info('trying to recover media error') |
208 | this.hls.recoverMediaError() | |
209 | return | |
210 | } | |
211 | ||
9df52d66 | 212 | if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) { |
83fcadac C |
213 | console.info('2nd try to recover media error (by swapping audio codec') |
214 | this.hls.swapAudioCodec() | |
215 | this.hls.recoverMediaError() | |
216 | return | |
217 | } | |
218 | ||
9df52d66 | 219 | if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) { |
83fcadac | 220 | console.info('bubbling media error up to VIDEOJS') |
adc1f09c | 221 | this.hls.destroy() |
83fcadac C |
222 | this.tech.error = () => error |
223 | this.tech.trigger('error') | |
83fcadac C |
224 | } |
225 | } | |
226 | ||
2d056f66 | 227 | private _handleNetworkError (error: any) { |
9df52d66 | 228 | if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) { |
2d056f66 C |
229 | console.info('trying to recover network error') |
230 | ||
231 | // Wait 1 second and retry | |
232 | setTimeout(() => this.hls.startLoad(), 1000) | |
233 | ||
234 | // Reset error count on success | |
235 | this.hls.once(Hlsjs.Events.FRAG_LOADED, () => { | |
9df52d66 | 236 | this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0 |
2d056f66 C |
237 | }) |
238 | ||
239 | return | |
240 | } | |
241 | ||
242 | console.info('bubbling network error up to VIDEOJS') | |
243 | this.hls.destroy() | |
244 | this.tech.error = () => error | |
245 | this.tech.trigger('error') | |
246 | } | |
247 | ||
134006b0 | 248 | private _onError (_event: any, data: ErrorData) { |
83fcadac C |
249 | const error: { message: string, code?: number } = { |
250 | message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}` | |
251 | } | |
83fcadac C |
252 | |
253 | // increment/set error count | |
9df52d66 C |
254 | if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1 |
255 | else this.errorCounts[data.type] = 1 | |
83fcadac | 256 | |
3e254de8 C |
257 | if (data.fatal) console.warn(error.message) |
258 | else console.error(error.message, data) | |
83fcadac | 259 | |
e25f83ce | 260 | if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) { |
e25f83ce | 261 | error.code = 2 |
2d056f66 | 262 | this._handleNetworkError(error) |
3e254de8 | 263 | } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') { |
e25f83ce C |
264 | error.code = 3 |
265 | this._handleMediaError(error) | |
3e254de8 | 266 | } else if (data.fatal) { |
e25f83ce C |
267 | this.hls.destroy() |
268 | console.info('bubbling error up to VIDEOJS') | |
269 | this.tech.error = () => error as any | |
270 | this.tech.trigger('error') | |
83fcadac C |
271 | } |
272 | } | |
273 | ||
e367da94 | 274 | private buildLevelLabel (level: Level) { |
83fcadac | 275 | if (this.player.srOptions_.levelLabelHandler) { |
3e254de8 | 276 | return this.player.srOptions_.levelLabelHandler(level as any) |
83fcadac C |
277 | } |
278 | ||
279 | if (level.height) return level.height + 'p' | |
280 | if (level.width) return Math.round(level.width * 9 / 16) + 'p' | |
281 | if (level.bitrate) return (level.bitrate / 1000) + 'kbps' | |
282 | ||
e367da94 | 283 | return '0' |
83fcadac C |
284 | } |
285 | ||
286 | private _notifyVideoQualities () { | |
287 | if (!this.metadata) return | |
83fcadac | 288 | |
e367da94 | 289 | const resolutions: PeerTubeResolution[] = [] |
83fcadac C |
290 | |
291 | this.metadata.levels.forEach((level, index) => { | |
e367da94 | 292 | resolutions.push({ |
83fcadac | 293 | id: index, |
e367da94 C |
294 | height: level.height, |
295 | width: level.width, | |
296 | bitrate: level.bitrate, | |
297 | label: this.buildLevelLabel(level), | |
298 | selected: level.id === this.hls.manualLevel, | |
299 | ||
300 | selectCallback: () => { | |
301 | this.hls.currentLevel = index | |
302 | } | |
303 | }) | |
83fcadac C |
304 | }) |
305 | ||
e367da94 C |
306 | resolutions.push({ |
307 | id: -1, | |
308 | label: this.player.localize('Auto'), | |
309 | selected: true, | |
310 | selectCallback: () => this.hls.currentLevel = -1 | |
311 | }) | |
83fcadac | 312 | |
e367da94 | 313 | this.player.peertubeResolutions().add(resolutions) |
83fcadac C |
314 | } |
315 | ||
316 | private _startLoad () { | |
317 | this.hls.startLoad(-1) | |
318 | this.videoElement.removeEventListener('play', this.handlers.play) | |
319 | } | |
320 | ||
9df52d66 | 321 | private _oneLevelObjClone (obj: { [ id: string ]: any }) { |
83fcadac C |
322 | const result = {} |
323 | const objKeys = Object.keys(obj) | |
324 | for (let i = 0; i < objKeys.length; i++) { | |
9df52d66 | 325 | result[objKeys[i]] = obj[objKeys[i]] |
83fcadac C |
326 | } |
327 | ||
328 | return result | |
329 | } | |
330 | ||
e367da94 | 331 | private _onMetaData (_event: any, data: ManifestParsedData) { |
83fcadac | 332 | // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later |
e367da94 C |
333 | this.metadata = data |
334 | this._notifyVideoQualities() | |
83fcadac C |
335 | } |
336 | ||
337 | private _initHlsjs () { | |
338 | const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions | |
339 | const srOptions_ = this.player.srOptions_ | |
340 | ||
9df52d66 | 341 | const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig |
83fcadac C |
342 | // Hls.js will write to the reference thus change the object for later streams |
343 | this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {} | |
344 | ||
345 | if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) { | |
346 | this.hlsjsConfig.autoStartLoad = false | |
347 | } | |
348 | ||
83fcadac C |
349 | // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above |
350 | // That's why we have a separate if block here to set the 'play' listener | |
351 | if (this.hlsjsConfig.autoStartLoad === false) { | |
352 | this.handlers.play = this._startLoad.bind(this) | |
353 | this.videoElement.addEventListener('play', this.handlers.play) | |
354 | } | |
355 | ||
83fcadac C |
356 | this.hls = new Hlsjs(this.hlsjsConfig) |
357 | ||
358 | this._executeHooksFor('beforeinitialize') | |
359 | ||
360 | this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data)) | |
e367da94 | 361 | this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data)) |
83fcadac C |
362 | this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => { |
363 | // The DVR plugin will auto seek to "live edge" on start up | |
364 | if (this.hlsjsConfig.liveSyncDuration) { | |
365 | this.edgeMargin = this.hlsjsConfig.liveSyncDuration | |
366 | } else if (this.hlsjsConfig.liveSyncDurationCount) { | |
367 | this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration | |
368 | } | |
369 | ||
370 | this.isLive = data.details.live | |
371 | this.dvrDuration = data.details.totalduration | |
22f25c74 | 372 | |
83fcadac C |
373 | this._duration = this.isLive ? Infinity : data.details.totalduration |
374 | }) | |
e367da94 | 375 | |
83fcadac C |
376 | this.hls.once(Hlsjs.Events.FRAG_LOADED, () => { |
377 | // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls` | |
378 | // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata | |
379 | this.tech.trigger('loadedmetadata') | |
380 | }) | |
381 | ||
e367da94 C |
382 | this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => { |
383 | const resolutionId = this.hls.autoLevelEnabled | |
384 | ? -1 | |
385 | : data.level | |
386 | ||
387 | const autoResolutionChosenId = this.hls.autoLevelEnabled | |
388 | ? data.level | |
389 | : -1 | |
390 | ||
391 | this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true }) | |
392 | }) | |
393 | ||
83fcadac C |
394 | this.hls.attachMedia(this.videoElement) |
395 | ||
83fcadac C |
396 | this.hls.loadSource(this.source.src) |
397 | } | |
398 | ||
399 | private initialize () { | |
400 | this._initHlsjs() | |
401 | } | |
402 | } | |
403 | ||
404 | export { | |
405 | Html5Hlsjs, | |
406 | registerSourceHandler, | |
407 | registerConfigPlugin | |
408 | } |