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