]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/p2p-media-loader/hls-plugin.ts
Fix webpack config
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / p2p-media-loader / hls-plugin.ts
CommitLineData
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
134006b0 4import Hlsjs, { ErrorData, HlsConfig, Level, ManifestLoadedData } from 'hls.js'
512decf3 5import videojs from 'video.js'
83fcadac
C
6import { HlsjsConfigHandlerOptions, QualityLevelRepresentation, QualityLevels, VideoJSTechHLS } from '../peertube-videojs-typings'
7
8type ErrorCounts = {
9 [ type: string ]: number
10}
11
12type Metadata = {
134006b0 13 levels: Level[]
83fcadac
C
14}
15
16const registerSourceHandler = function (vjs: typeof videojs) {
17 if (!Hlsjs.isSupported()) {
18 console.warn('Hls.js is not supported in this browser!')
19 return
20 }
21
22 const html5 = vjs.getTech('Html5')
23
24 if (!html5) {
25 console.error('Not supported version if video.js')
26 return
27 }
28
29 // FIXME: typings
30 (html5 as any).registerSourceHandler({
31 canHandleSource: function (source: videojs.Tech.SourceObject) {
32 const hlsTypeRE = /^application\/x-mpegURL|application\/vnd\.apple\.mpegurl$/i
33 const hlsExtRE = /\.m3u8/i
34
35 if (hlsTypeRE.test(source.type)) return 'probably'
36 if (hlsExtRE.test(source.src)) return 'maybe'
37
38 return ''
39 },
40
41 handleSource: function (source: videojs.Tech.SourceObject, tech: VideoJSTechHLS) {
42 if (tech.hlsProvider) {
43 tech.hlsProvider.dispose()
44 }
45
46 tech.hlsProvider = new Html5Hlsjs(vjs, source, tech)
47
48 return tech.hlsProvider
49 }
50 }, 0);
51
52 // FIXME: typings
53 (vjs as any).Html5Hlsjs = Html5Hlsjs
54}
55
7e37e111 56function hlsjsConfigHandler (this: videojs.Player, options: HlsjsConfigHandlerOptions) {
83fcadac
C
57 const player = this
58
59 if (!options) return
60
61 if (!player.srOptions_) {
62 player.srOptions_ = {}
63 }
64
65 if (!player.srOptions_.hlsjsConfig) {
66 player.srOptions_.hlsjsConfig = options.hlsjsConfig
67 }
68
69 if (!player.srOptions_.captionConfig) {
70 player.srOptions_.captionConfig = options.captionConfig
71 }
72
73 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
74 player.srOptions_.levelLabelHandler = options.levelLabelHandler
75 }
76}
77
78const registerConfigPlugin = function (vjs: typeof videojs) {
79 // Used in Brightcove since we don't pass options directly there
80 const registerVjsPlugin = vjs.registerPlugin || vjs.plugin
81 registerVjsPlugin('hlsjs', hlsjsConfigHandler)
82}
83
84class Html5Hlsjs {
85 private static readonly hooks: { [id: string]: Function[] } = {}
86
87 private readonly videoElement: HTMLVideoElement
88 private readonly errorCounts: ErrorCounts = {}
7e37e111 89 private readonly player: videojs.Player
83fcadac
C
90 private readonly tech: videojs.Tech
91 private readonly source: videojs.Tech.SourceObject
92 private readonly vjs: typeof videojs
93
134006b0
C
94 private hls: Hlsjs
95 private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null
83fcadac
C
96
97 private _duration: number = null
98 private metadata: Metadata = null
99 private isLive: boolean = null
100 private dvrDuration: number = null
101 private edgeMargin: number = null
102
e84203f2 103 private handlers: { [ id in 'play' | 'playing' | 'textTracksChange' | 'audioTracksChange' ]: EventListener } = {
83fcadac 104 play: null,
83fcadac
C
105 playing: null,
106 textTracksChange: null,
107 audioTracksChange: null
108 }
109
110 private uiTextTrackHandled = false
111
112 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
113 this.vjs = vjs
114 this.source = source
115
116 this.tech = tech;
117 (this.tech as any).name_ = 'Hlsjs'
118
119 this.videoElement = tech.el() as HTMLVideoElement
120 this.player = vjs((tech.options_ as any).playerId)
121
122 this.videoElement.addEventListener('error', event => {
123 let errorTxt: string
d0dd9813 124 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
83fcadac 125
d0dd9813
C
126 if (!mediaError) return
127
128 console.log(mediaError)
83fcadac
C
129 switch (mediaError.code) {
130 case mediaError.MEDIA_ERR_ABORTED:
131 errorTxt = 'You aborted the video playback'
132 break
133 case mediaError.MEDIA_ERR_DECODE:
134 errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features your browser did not support'
135 this._handleMediaError(mediaError)
136 break
137 case mediaError.MEDIA_ERR_NETWORK:
138 errorTxt = 'A network error caused the video download to fail part-way'
139 break
140 case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
141 errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported'
142 break
143
144 default:
145 errorTxt = mediaError.message
146 }
147
148 console.error('MEDIA_ERROR: ', errorTxt)
149 })
150
151 this.initialize()
152 }
153
154 duration () {
155 return this._duration || this.videoElement.duration || 0
156 }
157
158 seekable () {
159 if (this.hls.media) {
160 if (!this.isLive) {
161 return this.vjs.createTimeRanges(0, this.hls.media.duration)
162 }
163
164 // Video.js doesn't seem to like floating point timeranges
165 const startTime = Math.round(this.hls.media.duration - this.dvrDuration)
166 const endTime = Math.round(this.hls.media.duration - this.edgeMargin)
167
168 return this.vjs.createTimeRanges(startTime, endTime)
169 }
170
171 return this.vjs.createTimeRanges()
172 }
173
174 // See comment for `initialize` method.
175 dispose () {
176 this.videoElement.removeEventListener('play', this.handlers.play)
83fcadac
C
177 this.videoElement.removeEventListener('playing', this.handlers.playing)
178
179 this.player.textTracks().removeEventListener('change', this.handlers.textTracksChange)
180 this.uiTextTrackHandled = false
181
83fcadac
C
182 this.hls.destroy()
183 }
184
185 static addHook (type: string, callback: Function) {
186 Html5Hlsjs.hooks[ type ] = this.hooks[ type ] || []
187 Html5Hlsjs.hooks[ type ].push(callback)
188 }
189
190 static removeHook (type: string, callback: Function) {
191 if (Html5Hlsjs.hooks[ type ] === undefined) return false
192
193 const index = Html5Hlsjs.hooks[ type ].indexOf(callback)
194 if (index === -1) return false
195
196 Html5Hlsjs.hooks[ type ].splice(index, 1)
197
198 return true
199 }
200
201 private _executeHooksFor (type: string) {
202 if (Html5Hlsjs.hooks[ type ] === undefined) {
203 return
204 }
205
206 // ES3 and IE < 9
207 for (let i = 0; i < Html5Hlsjs.hooks[ type ].length; i++) {
208 Html5Hlsjs.hooks[ type ][ i ](this.player, this.hls)
209 }
210 }
211
212 private _handleMediaError (error: any) {
213 if (this.errorCounts[ Hlsjs.ErrorTypes.MEDIA_ERROR ] === 1) {
214 console.info('trying to recover media error')
215 this.hls.recoverMediaError()
216 return
217 }
218
219 if (this.errorCounts[ Hlsjs.ErrorTypes.MEDIA_ERROR ] === 2) {
220 console.info('2nd try to recover media error (by swapping audio codec')
221 this.hls.swapAudioCodec()
222 this.hls.recoverMediaError()
223 return
224 }
225
226 if (this.errorCounts[ Hlsjs.ErrorTypes.MEDIA_ERROR ] > 2) {
227 console.info('bubbling media error up to VIDEOJS')
adc1f09c 228 this.hls.destroy()
83fcadac
C
229 this.tech.error = () => error
230 this.tech.trigger('error')
231 return
232 }
233 }
234
2d056f66
C
235 private _handleNetworkError (error: any) {
236 if (this.errorCounts[ Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) {
237 console.info('trying to recover network error')
238
239 // Wait 1 second and retry
240 setTimeout(() => this.hls.startLoad(), 1000)
241
242 // Reset error count on success
243 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
244 this.errorCounts[ Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
245 })
246
247 return
248 }
249
250 console.info('bubbling network error up to VIDEOJS')
251 this.hls.destroy()
252 this.tech.error = () => error
253 this.tech.trigger('error')
254 }
255
134006b0 256 private _onError (_event: any, data: ErrorData) {
83fcadac
C
257 const error: { message: string, code?: number } = {
258 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
259 }
83fcadac
C
260
261 // increment/set error count
262 if (this.errorCounts[ data.type ]) this.errorCounts[ data.type ] += 1
263 else this.errorCounts[ data.type ] = 1
264
3e254de8
C
265 if (data.fatal) console.warn(error.message)
266 else console.error(error.message, data)
83fcadac 267
e25f83ce 268 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
e25f83ce 269 error.code = 2
2d056f66 270 this._handleNetworkError(error)
3e254de8 271 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
e25f83ce
C
272 error.code = 3
273 this._handleMediaError(error)
3e254de8 274 } else if (data.fatal) {
e25f83ce
C
275 this.hls.destroy()
276 console.info('bubbling error up to VIDEOJS')
277 this.tech.error = () => error as any
278 this.tech.trigger('error')
83fcadac
C
279 }
280 }
281
282 private switchQuality (qualityId: number) {
3e254de8 283 this.hls.currentLevel = qualityId
83fcadac
C
284 }
285
134006b0 286 private _levelLabel (level: Level) {
83fcadac 287 if (this.player.srOptions_.levelLabelHandler) {
3e254de8 288 return this.player.srOptions_.levelLabelHandler(level as any)
83fcadac
C
289 }
290
291 if (level.height) return level.height + 'p'
292 if (level.width) return Math.round(level.width * 9 / 16) + 'p'
293 if (level.bitrate) return (level.bitrate / 1000) + 'kbps'
294
295 return 0
296 }
297
298 private _relayQualityChange (qualityLevels: QualityLevels) {
299 // Determine if it is "Auto" (all tracks enabled)
300 let isAuto = true
301
302 for (let i = 0; i < qualityLevels.length; i++) {
303 if (!qualityLevels[ i ]._enabled) {
304 isAuto = false
305 break
306 }
307 }
308
309 // Interact with ME
310 if (isAuto) {
311 this.hls.currentLevel = -1
312 return
313 }
314
315 // Find ID of highest enabled track
316 let selectedTrack: number
317
318 for (selectedTrack = qualityLevels.length - 1; selectedTrack >= 0; selectedTrack--) {
319 if (qualityLevels[ selectedTrack ]._enabled) {
320 break
321 }
322 }
323
324 this.hls.currentLevel = selectedTrack
325 }
326
327 private _handleQualityLevels () {
328 if (!this.metadata) return
329
330 const qualityLevels = this.player.qualityLevels && this.player.qualityLevels()
331 if (!qualityLevels) return
332
333 for (let i = 0; i < this.metadata.levels.length; i++) {
334 const details = this.metadata.levels[ i ]
335 const representation: QualityLevelRepresentation = {
336 id: i,
337 width: details.width,
338 height: details.height,
339 bandwidth: details.bitrate,
340 bitrate: details.bitrate,
341 _enabled: true
342 }
343
344 const self = this
345 representation.enabled = function (this: QualityLevels, level: number, toggle?: boolean) {
346 // Brightcove switcher works TextTracks-style (enable tracks that it wants to ABR on)
347 if (typeof toggle === 'boolean') {
348 this[ level ]._enabled = toggle
349 self._relayQualityChange(this)
350 }
351
352 return this[ level ]._enabled
353 }
354
355 qualityLevels.addQualityLevel(representation)
356 }
357 }
358
359 private _notifyVideoQualities () {
360 if (!this.metadata) return
361 const cleanTracklist = []
362
363 if (this.metadata.levels.length > 1) {
364 const autoLevel = {
365 id: -1,
366 label: 'auto',
367 selected: this.hls.manualLevel === -1
368 }
369 cleanTracklist.push(autoLevel)
370 }
371
372 this.metadata.levels.forEach((level, index) => {
373 // Don't write in level (shared reference with Hls.js)
374 const quality = {
375 id: index,
376 selected: index === this.hls.manualLevel,
377 label: this._levelLabel(level)
378 }
379
380 cleanTracklist.push(quality)
381 })
382
383 const payload = {
384 qualityData: { video: cleanTracklist },
385 qualitySwitchCallback: this.switchQuality.bind(this)
386 }
387
388 this.tech.trigger('loadedqualitydata', payload)
389
390 // Self-de-register so we don't raise the payload multiple times
391 this.videoElement.removeEventListener('playing', this.handlers.playing)
392 }
393
394 private _updateSelectedAudioTrack () {
395 const playerAudioTracks = this.tech.audioTracks()
396 for (let j = 0; j < playerAudioTracks.length; j++) {
397 // FIXME: typings
398 if ((playerAudioTracks[ j ] as any).enabled) {
399 this.hls.audioTrack = j
400 break
401 }
402 }
403 }
404
405 private _onAudioTracks () {
4adebd51 406 const hlsAudioTracks = this.hls.audioTracks
83fcadac
C
407 const playerAudioTracks = this.tech.audioTracks()
408
409 if (hlsAudioTracks.length > 1 && playerAudioTracks.length === 0) {
410 // Add Hls.js audio tracks if not added yet
411 for (let i = 0; i < hlsAudioTracks.length; i++) {
412 playerAudioTracks.addTrack(new this.vjs.AudioTrack({
413 id: i.toString(),
414 kind: 'alternative',
415 label: hlsAudioTracks[ i ].name || hlsAudioTracks[ i ].lang,
416 language: hlsAudioTracks[ i ].lang,
417 enabled: i === this.hls.audioTrack
418 }))
419 }
420
421 // Handle audio track change event
422 this.handlers.audioTracksChange = this._updateSelectedAudioTrack.bind(this)
423 playerAudioTracks.addEventListener('change', this.handlers.audioTracksChange)
424 }
425 }
426
427 private _getTextTrackLabel (textTrack: TextTrack) {
428 // Label here is readable label and is optional (used in the UI so if it is there it should be different)
429 return textTrack.label ? textTrack.label : textTrack.language
430 }
431
432 private _isSameTextTrack (track1: TextTrack, track2: TextTrack) {
433 return this._getTextTrackLabel(track1) === this._getTextTrackLabel(track2)
434 && track1.kind === track2.kind
435 }
436
437 private _updateSelectedTextTrack () {
438 const playerTextTracks = this.player.textTracks()
439 let activeTrack: TextTrack = null
440
441 for (let j = 0; j < playerTextTracks.length; j++) {
442 if (playerTextTracks[ j ].mode === 'showing') {
443 activeTrack = playerTextTracks[ j ]
444 break
445 }
446 }
447
448 const hlsjsTracks = this.videoElement.textTracks
449 for (let k = 0; k < hlsjsTracks.length; k++) {
450 if (hlsjsTracks[ k ].kind === 'subtitles' || hlsjsTracks[ k ].kind === 'captions') {
451 hlsjsTracks[ k ].mode = activeTrack && this._isSameTextTrack(hlsjsTracks[ k ], activeTrack)
452 ? 'showing'
453 : 'disabled'
454 }
455 }
456 }
457
458 private _startLoad () {
459 this.hls.startLoad(-1)
460 this.videoElement.removeEventListener('play', this.handlers.play)
461 }
462
463 private _oneLevelObjClone (obj: object) {
464 const result = {}
465 const objKeys = Object.keys(obj)
466 for (let i = 0; i < objKeys.length; i++) {
467 result[ objKeys[ i ] ] = obj[ objKeys[ i ] ]
468 }
469
470 return result
471 }
472
473 private _filterDisplayableTextTracks (textTracks: TextTrackList) {
474 const displayableTracks = []
475
476 // Filter out tracks that is displayable (captions or subtitles)
477 for (let idx = 0; idx < textTracks.length; idx++) {
478 if (textTracks[ idx ].kind === 'subtitles' || textTracks[ idx ].kind === 'captions') {
479 displayableTracks.push(textTracks[ idx ])
480 }
481 }
482
483 return displayableTracks
484 }
485
486 private _updateTextTrackList () {
487 const displayableTracks = this._filterDisplayableTextTracks(this.videoElement.textTracks)
488 const playerTextTracks = this.player.textTracks()
489
490 // Add stubs to make the caption switcher shows up
491 // Adding the Hls.js text track in will make us have double captions
492 for (let idx = 0; idx < displayableTracks.length; idx++) {
493 let isAdded = false
494
495 for (let jdx = 0; jdx < playerTextTracks.length; jdx++) {
496 if (this._isSameTextTrack(displayableTracks[ idx ], playerTextTracks[ jdx ])) {
497 isAdded = true
498 break
499 }
500 }
501
502 if (!isAdded) {
503 const hlsjsTextTrack = displayableTracks[ idx ]
504 this.player.addRemoteTextTrack({
505 kind: hlsjsTextTrack.kind as videojs.TextTrack.Kind,
506 label: this._getTextTrackLabel(hlsjsTextTrack),
507 language: hlsjsTextTrack.language,
508 srclang: hlsjsTextTrack.language
509 }, false)
510 }
511 }
512
513 // Handle UI switching
514 this._updateSelectedTextTrack()
515
516 if (!this.uiTextTrackHandled) {
517 this.handlers.textTracksChange = this._updateSelectedTextTrack.bind(this)
518 playerTextTracks.addEventListener('change', this.handlers.textTracksChange)
519
520 this.uiTextTrackHandled = true
521 }
522 }
523
134006b0 524 private _onMetaData (_event: any, data: ManifestLoadedData) {
83fcadac
C
525 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
526 this.metadata = data as any
527 this._handleQualityLevels()
528 }
529
530 private _createCueHandler (captionConfig: any) {
531 return {
532 newCue: (track: any, startTime: number, endTime: number, captionScreen: { rows: any[] }) => {
533 let row: any
534 let cue: VTTCue
535 let text: string
536 const VTTCue = (window as any).VTTCue || (window as any).TextTrackCue
537
538 for (let r = 0; r < captionScreen.rows.length; r++) {
539 row = captionScreen.rows[ r ]
540 text = ''
541
542 if (!row.isEmpty()) {
543 for (let c = 0; c < row.chars.length; c++) {
544 text += row.chars[ c ].ucharj
545 }
546
547 cue = new VTTCue(startTime, endTime, text.trim())
548
549 // typeof null === 'object'
550 if (captionConfig != null && typeof captionConfig === 'object') {
551 // Copy client overridden property into the cue object
552 const configKeys = Object.keys(captionConfig)
553
554 for (let k = 0; k < configKeys.length; k++) {
555 cue[ configKeys[ k ] ] = captionConfig[ configKeys[ k ] ]
556 }
557 }
558 track.addCue(cue)
559 if (endTime === startTime) track.addCue(new VTTCue(endTime + 5, ''))
560 }
561 }
562 }
563 }
564 }
565
566 private _initHlsjs () {
567 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
568 const srOptions_ = this.player.srOptions_
569
570 const hlsjsConfigRef = srOptions_ && srOptions_.hlsjsConfig || techOptions.hlsjsConfig
571 // Hls.js will write to the reference thus change the object for later streams
572 this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {}
573
574 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
575 this.hlsjsConfig.autoStartLoad = false
576 }
577
578 const captionConfig = srOptions_ && srOptions_.captionConfig || techOptions.captionConfig
579 if (captionConfig) {
580 this.hlsjsConfig.cueHandler = this._createCueHandler(captionConfig)
581 }
582
583 // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above
584 // That's why we have a separate if block here to set the 'play' listener
585 if (this.hlsjsConfig.autoStartLoad === false) {
586 this.handlers.play = this._startLoad.bind(this)
587 this.videoElement.addEventListener('play', this.handlers.play)
588 }
589
590 // _notifyVideoQualities sometimes runs before the quality picker event handler is registered -> no video switcher
591 this.handlers.playing = this._notifyVideoQualities.bind(this)
592 this.videoElement.addEventListener('playing', this.handlers.playing)
593
594 this.hls = new Hlsjs(this.hlsjsConfig)
595
596 this._executeHooksFor('beforeinitialize')
597
598 this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data))
599 this.hls.on(Hlsjs.Events.AUDIO_TRACKS_UPDATED, () => this._onAudioTracks())
600 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data as any)) // FIXME: typings
601 this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => {
602 // The DVR plugin will auto seek to "live edge" on start up
603 if (this.hlsjsConfig.liveSyncDuration) {
604 this.edgeMargin = this.hlsjsConfig.liveSyncDuration
605 } else if (this.hlsjsConfig.liveSyncDurationCount) {
606 this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration
607 }
608
609 this.isLive = data.details.live
610 this.dvrDuration = data.details.totalduration
611 this._duration = this.isLive ? Infinity : data.details.totalduration
612 })
613 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
614 // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls`
615 // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata
616 this.tech.trigger('loadedmetadata')
617 })
618
619 this.hls.attachMedia(this.videoElement)
620
83fcadac
C
621 this.hls.loadSource(this.source.src)
622 }
623
624 private initialize () {
625 this._initHlsjs()
626 }
627}
628
629export {
630 Html5Hlsjs,
631 registerSourceHandler,
632 registerConfigPlugin
633}