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
4 import * as Hlsjs from 'hls.js/dist/hls.light.js'
5 import videojs, { VideoJsPlayer } from 'video.js'
6 import { HlsjsConfigHandlerOptions, QualityLevelRepresentation, QualityLevels, VideoJSTechHLS } from '../peertube-videojs-typings'
9 [ type: string ]: number
16 type CustomAudioTrack = AudioTrack & { name?: string, lang?: string }
18 const registerSourceHandler = function (vjs: typeof videojs) {
19 if (!Hlsjs.isSupported()) {
20 console.warn('Hls.js is not supported in this browser!')
24 const html5 = vjs.getTech('Html5')
27 console.error('Not supported version if video.js')
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
37 if (hlsTypeRE.test(source.type)) return 'probably'
38 if (hlsExtRE.test(source.src)) return 'maybe'
43 handleSource: function (source: videojs.Tech.SourceObject, tech: VideoJSTechHLS) {
44 if (tech.hlsProvider) {
45 tech.hlsProvider.dispose()
48 tech.hlsProvider = new Html5Hlsjs(vjs, source, tech)
50 return tech.hlsProvider
55 (vjs as any).Html5Hlsjs = Html5Hlsjs
58 function hlsjsConfigHandler (this: VideoJsPlayer, options: HlsjsConfigHandlerOptions) {
63 if (!player.srOptions_) {
64 player.srOptions_ = {}
67 if (!player.srOptions_.hlsjsConfig) {
68 player.srOptions_.hlsjsConfig = options.hlsjsConfig
71 if (!player.srOptions_.captionConfig) {
72 player.srOptions_.captionConfig = options.captionConfig
75 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
76 player.srOptions_.levelLabelHandler = options.levelLabelHandler
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)
87 private static readonly hooks: { [id: string]: Function[] } = {}
89 private readonly videoElement: HTMLVideoElement
90 private readonly errorCounts: ErrorCounts = {}
91 private readonly player: VideoJsPlayer
92 private readonly tech: videojs.Tech
93 private readonly source: videojs.Tech.SourceObject
94 private readonly vjs: typeof videojs
96 private hls: Hlsjs & { manualLevel?: number, audioTrack?: any, audioTracks?: CustomAudioTrack[] } // FIXME: typings
97 private hlsjsConfig: Partial<Hlsjs.Config & { cueHandler: any }> = null
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
105 private handlers: { [ id in 'play' | 'addtrack' | 'playing' | 'textTracksChange' | 'audioTracksChange' ]: EventListener } = {
109 textTracksChange: null,
110 audioTracksChange: null
113 private uiTextTrackHandled = false
115 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
120 (this.tech as any).name_ = 'Hlsjs'
122 this.videoElement = tech.el() as HTMLVideoElement
123 this.player = vjs((tech.options_ as any).playerId)
125 this.videoElement.addEventListener('error', event => {
127 const mediaError = (event.currentTarget as HTMLVideoElement).error
129 switch (mediaError.code) {
130 case mediaError.MEDIA_ERR_ABORTED:
131 errorTxt = 'You aborted the video playback'
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)
137 case mediaError.MEDIA_ERR_NETWORK:
138 errorTxt = 'A network error caused the video download to fail part-way'
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'
145 errorTxt = mediaError.message
148 console.error('MEDIA_ERROR: ', errorTxt)
155 return this._duration || this.videoElement.duration || 0
159 if (this.hls.media) {
161 return this.vjs.createTimeRanges(0, this.hls.media.duration)
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)
168 return this.vjs.createTimeRanges(startTime, endTime)
171 return this.vjs.createTimeRanges()
174 // See comment for `initialize` method.
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)
180 this.player.textTracks().removeEventListener('change', this.handlers.textTracksChange)
181 this.uiTextTrackHandled = false
183 this.player.audioTracks().removeEventListener('change', this.handlers.audioTracksChange)
188 static addHook (type: string, callback: Function) {
189 Html5Hlsjs.hooks[ type ] = this.hooks[ type ] || []
190 Html5Hlsjs.hooks[ type ].push(callback)
193 static removeHook (type: string, callback: Function) {
194 if (Html5Hlsjs.hooks[ type ] === undefined) return false
196 const index = Html5Hlsjs.hooks[ type ].indexOf(callback)
197 if (index === -1) return false
199 Html5Hlsjs.hooks[ type ].splice(index, 1)
204 private _executeHooksFor (type: string) {
205 if (Html5Hlsjs.hooks[ type ] === undefined) {
210 for (let i = 0; i < Html5Hlsjs.hooks[ type ].length; i++) {
211 Html5Hlsjs.hooks[ type ][ i ](this.player, this.hls)
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()
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()
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')
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}`
241 console.error(error.message)
243 // increment/set error count
244 if (this.errorCounts[ data.type ]) this.errorCounts[ data.type ] += 1
245 else this.errorCounts[ data.type ] = 1
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
251 case Hlsjs.ErrorTypes.NETWORK_ERROR:
252 console.info('bubbling network error up to VIDEOJS')
254 this.tech.error = () => error as any
255 this.tech.trigger('error')
258 case Hlsjs.ErrorTypes.MEDIA_ERROR:
260 this._handleMediaError(error)
266 console.info('bubbling error up to VIDEOJS')
267 this.tech.error = () => error as any
268 this.tech.trigger('error')
274 private switchQuality (qualityId: number) {
275 this.hls.nextLevel = qualityId
278 private _levelLabel (level: Hlsjs.Level) {
279 if (this.player.srOptions_.levelLabelHandler) {
280 return this.player.srOptions_.levelLabelHandler(level)
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'
290 private _relayQualityChange (qualityLevels: QualityLevels) {
291 // Determine if it is "Auto" (all tracks enabled)
294 for (let i = 0; i < qualityLevels.length; i++) {
295 if (!qualityLevels[ i ]._enabled) {
303 this.hls.currentLevel = -1
307 // Find ID of highest enabled track
308 let selectedTrack: number
310 for (selectedTrack = qualityLevels.length - 1; selectedTrack >= 0; selectedTrack--) {
311 if (qualityLevels[ selectedTrack ]._enabled) {
316 this.hls.currentLevel = selectedTrack
319 private _handleQualityLevels () {
320 if (!this.metadata) return
322 const qualityLevels = this.player.qualityLevels && this.player.qualityLevels()
323 if (!qualityLevels) return
325 for (let i = 0; i < this.metadata.levels.length; i++) {
326 const details = this.metadata.levels[ i ]
327 const representation: QualityLevelRepresentation = {
329 width: details.width,
330 height: details.height,
331 bandwidth: details.bitrate,
332 bitrate: details.bitrate,
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)
344 return this[ level ]._enabled
347 qualityLevels.addQualityLevel(representation)
351 private _notifyVideoQualities () {
352 if (!this.metadata) return
353 const cleanTracklist = []
355 if (this.metadata.levels.length > 1) {
359 selected: this.hls.manualLevel === -1
361 cleanTracklist.push(autoLevel)
364 this.metadata.levels.forEach((level, index) => {
365 // Don't write in level (shared reference with Hls.js)
368 selected: index === this.hls.manualLevel,
369 label: this._levelLabel(level)
372 cleanTracklist.push(quality)
376 qualityData: { video: cleanTracklist },
377 qualitySwitchCallback: this.switchQuality.bind(this)
380 this.tech.trigger('loadedqualitydata', payload)
382 // Self-de-register so we don't raise the payload multiple times
383 this.videoElement.removeEventListener('playing', this.handlers.playing)
386 private _updateSelectedAudioTrack () {
387 const playerAudioTracks = this.tech.audioTracks()
388 for (let j = 0; j < playerAudioTracks.length; j++) {
390 if ((playerAudioTracks[ j ] as any).enabled) {
391 this.hls.audioTrack = j
397 private _onAudioTracks () {
398 const hlsAudioTracks = this.hls.audioTracks
399 const playerAudioTracks = this.tech.audioTracks()
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({
407 label: hlsAudioTracks[ i ].name || hlsAudioTracks[ i ].lang,
408 language: hlsAudioTracks[ i ].lang,
409 enabled: i === this.hls.audioTrack
413 // Handle audio track change event
414 this.handlers.audioTracksChange = this._updateSelectedAudioTrack.bind(this)
415 playerAudioTracks.addEventListener('change', this.handlers.audioTracksChange)
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
424 private _isSameTextTrack (track1: TextTrack, track2: TextTrack) {
425 return this._getTextTrackLabel(track1) === this._getTextTrackLabel(track2)
426 && track1.kind === track2.kind
429 private _updateSelectedTextTrack () {
430 const playerTextTracks = this.player.textTracks()
431 let activeTrack: TextTrack = null
433 for (let j = 0; j < playerTextTracks.length; j++) {
434 if (playerTextTracks[ j ].mode === 'showing') {
435 activeTrack = playerTextTracks[ j ]
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)
450 private _startLoad () {
451 this.hls.startLoad(-1)
452 this.videoElement.removeEventListener('play', this.handlers.play)
455 private _oneLevelObjClone (obj: object) {
457 const objKeys = Object.keys(obj)
458 for (let i = 0; i < objKeys.length; i++) {
459 result[ objKeys[ i ] ] = obj[ objKeys[ i ] ]
465 private _filterDisplayableTextTracks (textTracks: TextTrackList) {
466 const displayableTracks = []
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 ])
475 return displayableTracks
478 private _updateTextTrackList () {
479 const displayableTracks = this._filterDisplayableTextTracks(this.videoElement.textTracks)
480 const playerTextTracks = this.player.textTracks()
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++) {
487 for (let jdx = 0; jdx < playerTextTracks.length; jdx++) {
488 if (this._isSameTextTrack(displayableTracks[ idx ], playerTextTracks[ jdx ])) {
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
505 // Handle UI switching
506 this._updateSelectedTextTrack()
508 if (!this.uiTextTrackHandled) {
509 this.handlers.textTracksChange = this._updateSelectedTextTrack.bind(this)
510 playerTextTracks.addEventListener('change', this.handlers.textTracksChange)
512 this.uiTextTrackHandled = true
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()
522 private _createCueHandler (captionConfig: any) {
524 newCue: (track: any, startTime: number, endTime: number, captionScreen: { rows: any[] }) => {
528 const VTTCue = (window as any).VTTCue || (window as any).TextTrackCue
530 for (let r = 0; r < captionScreen.rows.length; r++) {
531 row = captionScreen.rows[ r ]
534 if (!row.isEmpty()) {
535 for (let c = 0; c < row.chars.length; c++) {
536 text += row.chars[ c ].ucharj
539 cue = new VTTCue(startTime, endTime, text.trim())
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)
546 for (let k = 0; k < configKeys.length; k++) {
547 cue[ configKeys[ k ] ] = captionConfig[ configKeys[ k ] ]
551 if (endTime === startTime) track.addCue(new VTTCue(endTime + 5, ''))
558 private _initHlsjs () {
559 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
560 const srOptions_ = this.player.srOptions_
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) : {}
566 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
567 this.hlsjsConfig.autoStartLoad = false
570 const captionConfig = srOptions_ && srOptions_.captionConfig || techOptions.captionConfig
572 this.hlsjsConfig.cueHandler = this._createCueHandler(captionConfig)
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)
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)
586 this.hls = new Hlsjs(this.hlsjsConfig)
588 this._executeHooksFor('beforeinitialize')
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
601 this.isLive = data.details.live
602 this.dvrDuration = data.details.totalduration
603 this._duration = this.isLive ? Infinity : data.details.totalduration
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')
611 this.hls.attachMedia(this.videoElement)
613 this.handlers.addtrack = this._updateTextTrackList.bind(this)
614 this.videoElement.textTracks.addEventListener('addtrack', this.handlers.addtrack)
616 this.hls.loadSource(this.source.src)
619 private initialize () {
626 registerSourceHandler,