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