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