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