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