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 { HlsjsConfigHandlerOptions, PeerTubeResolution, VideoJSTechHLS } from '../peertube-videojs-typings'
9 [ type: string ]: number
16 type HookFn = (player: videojs.Player, hljs: Hlsjs) => void
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: videojs.Player, 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]: HookFn[] } = {}
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
97 private hlsjsConfig: Partial<HlsConfig & { 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' ]: EventListener } = {
109 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
114 (this.tech as any).name_ = 'Hlsjs'
116 this.videoElement = tech.el() as HTMLVideoElement
117 this.player = vjs((tech.options_ as any).playerId)
119 this.videoElement.addEventListener('error', event => {
121 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
123 if (!mediaError) return
125 console.log(mediaError)
126 switch (mediaError.code) {
127 case mediaError.MEDIA_ERR_ABORTED:
128 errorTxt = 'You aborted the video playback'
130 case mediaError.MEDIA_ERR_DECODE:
131 errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' +
132 'your browser did not support'
133 this._handleMediaError(mediaError)
135 case mediaError.MEDIA_ERR_NETWORK:
136 errorTxt = 'A network error caused the video download to fail part-way'
138 case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
139 errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported'
143 errorTxt = mediaError.message
146 console.error('MEDIA_ERROR: ', errorTxt)
153 return this._duration || this.videoElement.duration || 0
157 if (this.hls.media) {
159 return this.vjs.createTimeRanges(0, this.hls.media.duration)
162 // Video.js doesn't seem to like floating point timeranges
163 const startTime = Math.round(this.hls.media.duration - this.dvrDuration)
164 const endTime = Math.round(this.hls.media.duration - this.edgeMargin)
166 return this.vjs.createTimeRanges(startTime, endTime)
169 return this.vjs.createTimeRanges()
172 // See comment for `initialize` method.
174 this.videoElement.removeEventListener('play', this.handlers.play)
179 static addHook (type: string, callback: HookFn) {
180 Html5Hlsjs.hooks[type] = this.hooks[type] || []
181 Html5Hlsjs.hooks[type].push(callback)
184 static removeHook (type: string, callback: HookFn) {
185 if (Html5Hlsjs.hooks[type] === undefined) return false
187 const index = Html5Hlsjs.hooks[type].indexOf(callback)
188 if (index === -1) return false
190 Html5Hlsjs.hooks[type].splice(index, 1)
195 private _executeHooksFor (type: string) {
196 if (Html5Hlsjs.hooks[type] === undefined) {
201 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
202 Html5Hlsjs.hooks[type][i](this.player, this.hls)
206 private _handleMediaError (error: any) {
207 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) {
208 console.info('trying to recover media error')
209 this.hls.recoverMediaError()
213 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) {
214 console.info('2nd try to recover media error (by swapping audio codec')
215 this.hls.swapAudioCodec()
216 this.hls.recoverMediaError()
220 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
221 console.info('bubbling media error up to VIDEOJS')
223 this.tech.error = () => error
224 this.tech.trigger('error')
228 private _handleNetworkError (error: any) {
229 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) {
230 console.info('trying to recover network error')
232 // Wait 1 second and retry
233 setTimeout(() => this.hls.startLoad(), 1000)
235 // Reset error count on success
236 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
237 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
243 console.info('bubbling network error up to VIDEOJS')
245 this.tech.error = () => error
246 this.tech.trigger('error')
249 private _onError (_event: any, data: ErrorData) {
250 const error: { message: string, code?: number } = {
251 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
254 // increment/set error count
255 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
256 else this.errorCounts[data.type] = 1
258 if (data.fatal) console.warn(error.message)
259 else console.error(error.message, data)
261 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
263 this._handleNetworkError(error)
264 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
266 this._handleMediaError(error)
267 } else if (data.fatal) {
269 console.info('bubbling error up to VIDEOJS')
270 this.tech.error = () => error as any
271 this.tech.trigger('error')
275 private buildLevelLabel (level: Level) {
276 if (this.player.srOptions_.levelLabelHandler) {
277 return this.player.srOptions_.levelLabelHandler(level as any)
280 if (level.height) return level.height + 'p'
281 if (level.width) return Math.round(level.width * 9 / 16) + 'p'
282 if (level.bitrate) return (level.bitrate / 1000) + 'kbps'
287 private _notifyVideoQualities () {
288 if (!this.metadata) return
290 const resolutions: PeerTubeResolution[] = []
292 this.metadata.levels.forEach((level, index) => {
295 height: level.height,
297 bitrate: level.bitrate,
298 label: this.buildLevelLabel(level),
299 selected: level.id === this.hls.manualLevel,
301 selectCallback: () => {
302 this.hls.currentLevel = index
309 label: this.player.localize('Auto'),
311 selectCallback: () => this.hls.currentLevel = -1
314 this.player.peertubeResolutions().add(resolutions)
317 private _startLoad () {
318 this.hls.startLoad(-1)
319 this.videoElement.removeEventListener('play', this.handlers.play)
322 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
324 const objKeys = Object.keys(obj)
325 for (let i = 0; i < objKeys.length; i++) {
326 result[objKeys[i]] = obj[objKeys[i]]
332 private _onMetaData (_event: any, data: ManifestParsedData) {
333 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
335 this._notifyVideoQualities()
338 private _initHlsjs () {
339 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
340 const srOptions_ = this.player.srOptions_
342 const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig
343 // Hls.js will write to the reference thus change the object for later streams
344 this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {}
346 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
347 this.hlsjsConfig.autoStartLoad = false
350 // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above
351 // That's why we have a separate if block here to set the 'play' listener
352 if (this.hlsjsConfig.autoStartLoad === false) {
353 this.handlers.play = this._startLoad.bind(this)
354 this.videoElement.addEventListener('play', this.handlers.play)
357 this.hls = new Hlsjs(this.hlsjsConfig)
359 this._executeHooksFor('beforeinitialize')
361 this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data))
362 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data))
363 this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => {
364 // The DVR plugin will auto seek to "live edge" on start up
365 if (this.hlsjsConfig.liveSyncDuration) {
366 this.edgeMargin = this.hlsjsConfig.liveSyncDuration
367 } else if (this.hlsjsConfig.liveSyncDurationCount) {
368 this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration
371 this.isLive = data.details.live
372 this.dvrDuration = data.details.totalduration
373 this._duration = this.isLive ? Infinity : data.details.totalduration
376 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
377 // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls`
378 // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata
379 this.tech.trigger('loadedmetadata')
382 this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => {
383 const resolutionId = this.hls.autoLevelEnabled
387 const autoResolutionChosenId = this.hls.autoLevelEnabled
391 this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true })
394 this.hls.attachMedia(this.videoElement)
396 this.hls.loadSource(this.source.src)
399 private initialize () {
406 registerSourceHandler,