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 Hlsjs, { ErrorData, HlsConfig, Level, LevelSwitchingData, ManifestParsedData } from 'hls.js'
5 import videojs from 'video.js'
6 import { logger } from '@root-helpers/logger'
7 import { HlsjsConfigHandlerOptions, PeerTubeResolution, VideoJSTechHLS } from '../../types'
10 [ type: string ]: number
17 type HookFn = (player: videojs.Player, hljs: Hlsjs) => void
19 const registerSourceHandler = function (vjs: typeof videojs) {
20 if (!Hlsjs.isSupported()) {
21 logger.warn('Hls.js is not supported in this browser!')
25 const html5 = vjs.getTech('Html5')
28 logger.error('No Hml5 tech found in videojs')
33 (html5 as any).registerSourceHandler({
34 canHandleSource: function (source: videojs.Tech.SourceObject) {
35 const hlsTypeRE = /^application\/x-mpegURL|application\/vnd\.apple\.mpegurl$/i
36 const hlsExtRE = /\.m3u8/i
38 if (hlsTypeRE.test(source.type)) return 'probably'
39 if (hlsExtRE.test(source.src)) return 'maybe'
44 handleSource: function (source: videojs.Tech.SourceObject, tech: VideoJSTechHLS) {
45 if (tech.hlsProvider) {
46 tech.hlsProvider.dispose()
49 tech.hlsProvider = new Html5Hlsjs(vjs, source, tech)
51 return tech.hlsProvider
56 (vjs as any).Html5Hlsjs = Html5Hlsjs
59 function hlsjsConfigHandler (this: videojs.Player, options: HlsjsConfigHandlerOptions) {
64 if (!player.srOptions_) {
65 player.srOptions_ = {}
68 if (!player.srOptions_.hlsjsConfig) {
69 player.srOptions_.hlsjsConfig = options.hlsjsConfig
72 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
73 player.srOptions_.levelLabelHandler = options.levelLabelHandler
77 const registerConfigPlugin = function (vjs: typeof videojs) {
78 // Used in Brightcove since we don't pass options directly there
79 const registerVjsPlugin = vjs.registerPlugin || vjs.plugin
80 registerVjsPlugin('hlsjs', hlsjsConfigHandler)
84 private static readonly hooks: { [id: string]: HookFn[] } = {}
86 private readonly videoElement: HTMLVideoElement
87 private readonly errorCounts: ErrorCounts = {}
88 private readonly player: videojs.Player
89 private readonly tech: videojs.Tech
90 private readonly source: videojs.Tech.SourceObject
91 private readonly vjs: typeof videojs
93 private maxNetworkErrorRecovery = 5
96 private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null
98 private _duration: number = null
99 private metadata: Metadata = null
100 private isLive: boolean = null
101 private dvrDuration: number = null
102 private edgeMargin: number = null
104 private handlers: { [ id in 'play' ]: EventListener } = {
108 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
113 (this.tech as any).name_ = 'Hlsjs'
115 this.videoElement = tech.el() as HTMLVideoElement
116 this.player = vjs((tech.options_ as any).playerId)
118 this.videoElement.addEventListener('error', event => {
120 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
122 if (!mediaError) return
124 logger.info(mediaError)
125 switch (mediaError.code) {
126 case mediaError.MEDIA_ERR_ABORTED:
127 errorTxt = 'You aborted the video playback'
129 case mediaError.MEDIA_ERR_DECODE:
130 errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' +
131 'your browser did not support'
132 this._handleMediaError(mediaError)
134 case mediaError.MEDIA_ERR_NETWORK:
135 errorTxt = 'A network error caused the video download to fail part-way'
137 case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
138 errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported'
142 errorTxt = mediaError.message
145 logger.error(`MEDIA_ERROR: ${errorTxt}`)
152 if (this._duration === Infinity) return Infinity
153 if (!isNaN(this.videoElement.duration)) return this.videoElement.duration
155 return this._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)
178 // FIXME: https://github.com/video-dev/hls.js/issues/4092
179 const untypedHLS = this.hls as any
180 untypedHLS.log = untypedHLS.warn = () => {
187 static addHook (type: string, callback: HookFn) {
188 Html5Hlsjs.hooks[type] = this.hooks[type] || []
189 Html5Hlsjs.hooks[type].push(callback)
192 static removeHook (type: string, callback: HookFn) {
193 if (Html5Hlsjs.hooks[type] === undefined) return false
195 const index = Html5Hlsjs.hooks[type].indexOf(callback)
196 if (index === -1) return false
198 Html5Hlsjs.hooks[type].splice(index, 1)
203 private _executeHooksFor (type: string) {
204 if (Html5Hlsjs.hooks[type] === undefined) {
209 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
210 Html5Hlsjs.hooks[type][i](this.player, this.hls)
214 private _handleMediaError (error: any) {
215 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) {
216 logger.info('trying to recover media error')
217 this.hls.recoverMediaError()
221 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) {
222 logger.info('2nd try to recover media error (by swapping audio codec')
223 this.hls.swapAudioCodec()
224 this.hls.recoverMediaError()
228 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
229 logger.info('bubbling media error up to VIDEOJS')
231 this.tech.error = () => error
232 this.tech.trigger('error')
236 private _handleNetworkError (error: any) {
237 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= this.maxNetworkErrorRecovery) {
238 logger.info('trying to recover network error')
240 // Wait 1 second and retry
241 setTimeout(() => this.hls.startLoad(), 1000)
243 // Reset error count on success
244 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
245 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
251 logger.info('bubbling network error up to VIDEOJS')
253 this.tech.error = () => error
254 this.tech.trigger('error')
257 private _onError (_event: any, data: ErrorData) {
258 const error: { message: string, code?: number } = {
259 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
262 // increment/set error count
263 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
264 else this.errorCounts[data.type] = 1
266 if (data.fatal) logger.warn(error.message)
267 else logger.error(error.message, { data })
269 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
271 this._handleNetworkError(error)
272 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
274 this._handleMediaError(error)
275 } else if (data.fatal) {
277 logger.info('bubbling error up to VIDEOJS')
278 this.tech.error = () => error as any
279 this.tech.trigger('error')
283 private buildLevelLabel (level: Level) {
284 if (this.player.srOptions_.levelLabelHandler) {
285 return this.player.srOptions_.levelLabelHandler(level as any)
288 if (level.height) return level.height + 'p'
289 if (level.width) return Math.round(level.width * 9 / 16) + 'p'
290 if (level.bitrate) return (level.bitrate / 1000) + 'kbps'
295 private _notifyVideoQualities () {
296 if (!this.metadata) return
298 const resolutions: PeerTubeResolution[] = []
300 this.metadata.levels.forEach((level, index) => {
303 height: level.height,
305 bitrate: level.bitrate,
306 label: this.buildLevelLabel(level),
307 selected: level.id === this.hls.manualLevel,
309 selectCallback: () => {
310 this.hls.currentLevel = index
317 label: this.player.localize('Auto'),
319 selectCallback: () => this.hls.currentLevel = -1
322 this.player.peertubeResolutions().add(resolutions)
325 private _startLoad () {
326 this.hls.startLoad(-1)
327 this.videoElement.removeEventListener('play', this.handlers.play)
330 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
332 const objKeys = Object.keys(obj)
333 for (let i = 0; i < objKeys.length; i++) {
334 result[objKeys[i]] = obj[objKeys[i]]
340 private _onMetaData (_event: any, data: ManifestParsedData) {
341 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
343 this._notifyVideoQualities()
346 private _initHlsjs () {
347 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
348 const srOptions_ = this.player.srOptions_
350 const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig
351 // Hls.js will write to the reference thus change the object for later streams
352 this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {}
354 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
355 this.hlsjsConfig.autoStartLoad = false
358 // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above
359 // That's why we have a separate if block here to set the 'play' listener
360 if (this.hlsjsConfig.autoStartLoad === false) {
361 this.handlers.play = this._startLoad.bind(this)
362 this.videoElement.addEventListener('play', this.handlers.play)
365 this.hls = new Hlsjs(this.hlsjsConfig)
367 this._executeHooksFor('beforeinitialize')
369 this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data))
370 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data))
371 this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => {
372 // The DVR plugin will auto seek to "live edge" on start up
373 if (this.hlsjsConfig.liveSyncDuration) {
374 this.edgeMargin = this.hlsjsConfig.liveSyncDuration
375 } else if (this.hlsjsConfig.liveSyncDurationCount) {
376 this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration
379 this.isLive = data.details.live
380 this.dvrDuration = data.details.totalduration
382 this._duration = this.isLive ? Infinity : data.details.totalduration
384 // Increase network error recovery for lives since they can be broken (server restart, stream interruption etc)
385 if (this.isLive) this.maxNetworkErrorRecovery = 300
388 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
389 // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls`
390 // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata
391 this.tech.trigger('loadedmetadata')
394 this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => {
395 const resolutionId = this.hls.autoLevelEnabled
399 const autoResolutionChosenId = this.hls.autoLevelEnabled
403 this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true })
406 this.hls.attachMedia(this.videoElement)
408 this.hls.loadSource(this.source.src)
411 private initialize () {
418 registerSourceHandler,