]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/p2p-media-loader/hls-plugin.ts
Migrate to @peertube/videojs-contextmenu
[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
e367da94 4import Hlsjs, { ErrorData, HlsConfig, Level, LevelSwitchingData, ManifestParsedData } from 'hls.js'
512decf3 5import videojs from 'video.js'
e367da94 6import { HlsjsConfigHandlerOptions, PeerTubeResolution, VideoJSTechHLS } from '../peertube-videojs-typings'
83fcadac
C
7
8type ErrorCounts = {
9 [ type: string ]: number
10}
11
12type Metadata = {
134006b0 13 levels: Level[]
83fcadac
C
14}
15
9df52d66
C
16type HookFn = (player: videojs.Player, hljs: Hlsjs) => void
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
83fcadac
C
71 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
72 player.srOptions_.levelLabelHandler = options.levelLabelHandler
73 }
74}
75
76const registerConfigPlugin = function (vjs: typeof videojs) {
77 // Used in Brightcove since we don't pass options directly there
78 const registerVjsPlugin = vjs.registerPlugin || vjs.plugin
79 registerVjsPlugin('hlsjs', hlsjsConfigHandler)
80}
81
82class Html5Hlsjs {
9df52d66 83 private static readonly hooks: { [id: string]: HookFn[] } = {}
83fcadac
C
84
85 private readonly videoElement: HTMLVideoElement
86 private readonly errorCounts: ErrorCounts = {}
7e37e111 87 private readonly player: videojs.Player
83fcadac
C
88 private readonly tech: videojs.Tech
89 private readonly source: videojs.Tech.SourceObject
90 private readonly vjs: typeof videojs
91
134006b0
C
92 private hls: Hlsjs
93 private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null
83fcadac
C
94
95 private _duration: number = null
96 private metadata: Metadata = null
97 private isLive: boolean = null
98 private dvrDuration: number = null
99 private edgeMargin: number = null
100
e367da94
C
101 private handlers: { [ id in 'play' ]: EventListener } = {
102 play: null
83fcadac
C
103 }
104
83fcadac
C
105 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
106 this.vjs = vjs
107 this.source = source
108
109 this.tech = tech;
110 (this.tech as any).name_ = 'Hlsjs'
111
112 this.videoElement = tech.el() as HTMLVideoElement
113 this.player = vjs((tech.options_ as any).playerId)
114
115 this.videoElement.addEventListener('error', event => {
116 let errorTxt: string
d0dd9813 117 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
83fcadac 118
d0dd9813
C
119 if (!mediaError) return
120
121 console.log(mediaError)
83fcadac
C
122 switch (mediaError.code) {
123 case mediaError.MEDIA_ERR_ABORTED:
124 errorTxt = 'You aborted the video playback'
125 break
126 case mediaError.MEDIA_ERR_DECODE:
9df52d66
C
127 errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' +
128 'your browser did not support'
83fcadac
C
129 this._handleMediaError(mediaError)
130 break
131 case mediaError.MEDIA_ERR_NETWORK:
132 errorTxt = 'A network error caused the video download to fail part-way'
133 break
134 case mediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
135 errorTxt = 'The video could not be loaded, either because the server or network failed or because the format is not supported'
136 break
137
138 default:
139 errorTxt = mediaError.message
140 }
141
142 console.error('MEDIA_ERROR: ', errorTxt)
143 })
144
145 this.initialize()
146 }
147
148 duration () {
149 return this._duration || this.videoElement.duration || 0
150 }
151
152 seekable () {
153 if (this.hls.media) {
154 if (!this.isLive) {
155 return this.vjs.createTimeRanges(0, this.hls.media.duration)
156 }
157
158 // Video.js doesn't seem to like floating point timeranges
159 const startTime = Math.round(this.hls.media.duration - this.dvrDuration)
160 const endTime = Math.round(this.hls.media.duration - this.edgeMargin)
161
162 return this.vjs.createTimeRanges(startTime, endTime)
163 }
164
165 return this.vjs.createTimeRanges()
166 }
167
168 // See comment for `initialize` method.
169 dispose () {
170 this.videoElement.removeEventListener('play', this.handlers.play)
83fcadac 171
83fcadac
C
172 this.hls.destroy()
173 }
174
9df52d66
C
175 static addHook (type: string, callback: HookFn) {
176 Html5Hlsjs.hooks[type] = this.hooks[type] || []
177 Html5Hlsjs.hooks[type].push(callback)
83fcadac
C
178 }
179
9df52d66
C
180 static removeHook (type: string, callback: HookFn) {
181 if (Html5Hlsjs.hooks[type] === undefined) return false
83fcadac 182
9df52d66 183 const index = Html5Hlsjs.hooks[type].indexOf(callback)
83fcadac
C
184 if (index === -1) return false
185
9df52d66 186 Html5Hlsjs.hooks[type].splice(index, 1)
83fcadac
C
187
188 return true
189 }
190
191 private _executeHooksFor (type: string) {
9df52d66 192 if (Html5Hlsjs.hooks[type] === undefined) {
83fcadac
C
193 return
194 }
195
196 // ES3 and IE < 9
9df52d66
C
197 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
198 Html5Hlsjs.hooks[type][i](this.player, this.hls)
83fcadac
C
199 }
200 }
201
202 private _handleMediaError (error: any) {
9df52d66 203 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) {
83fcadac
C
204 console.info('trying to recover media error')
205 this.hls.recoverMediaError()
206 return
207 }
208
9df52d66 209 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) {
83fcadac
C
210 console.info('2nd try to recover media error (by swapping audio codec')
211 this.hls.swapAudioCodec()
212 this.hls.recoverMediaError()
213 return
214 }
215
9df52d66 216 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
83fcadac 217 console.info('bubbling media error up to VIDEOJS')
adc1f09c 218 this.hls.destroy()
83fcadac
C
219 this.tech.error = () => error
220 this.tech.trigger('error')
83fcadac
C
221 }
222 }
223
2d056f66 224 private _handleNetworkError (error: any) {
9df52d66 225 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) {
2d056f66
C
226 console.info('trying to recover network error')
227
228 // Wait 1 second and retry
229 setTimeout(() => this.hls.startLoad(), 1000)
230
231 // Reset error count on success
232 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
9df52d66 233 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
2d056f66
C
234 })
235
236 return
237 }
238
239 console.info('bubbling network error up to VIDEOJS')
240 this.hls.destroy()
241 this.tech.error = () => error
242 this.tech.trigger('error')
243 }
244
134006b0 245 private _onError (_event: any, data: ErrorData) {
83fcadac
C
246 const error: { message: string, code?: number } = {
247 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
248 }
83fcadac
C
249
250 // increment/set error count
9df52d66
C
251 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
252 else this.errorCounts[data.type] = 1
83fcadac 253
3e254de8
C
254 if (data.fatal) console.warn(error.message)
255 else console.error(error.message, data)
83fcadac 256
e25f83ce 257 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
e25f83ce 258 error.code = 2
2d056f66 259 this._handleNetworkError(error)
3e254de8 260 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
e25f83ce
C
261 error.code = 3
262 this._handleMediaError(error)
3e254de8 263 } else if (data.fatal) {
e25f83ce
C
264 this.hls.destroy()
265 console.info('bubbling error up to VIDEOJS')
266 this.tech.error = () => error as any
267 this.tech.trigger('error')
83fcadac
C
268 }
269 }
270
e367da94 271 private buildLevelLabel (level: Level) {
83fcadac 272 if (this.player.srOptions_.levelLabelHandler) {
3e254de8 273 return this.player.srOptions_.levelLabelHandler(level as any)
83fcadac
C
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
e367da94 280 return '0'
83fcadac
C
281 }
282
283 private _notifyVideoQualities () {
284 if (!this.metadata) return
83fcadac 285
e367da94 286 const resolutions: PeerTubeResolution[] = []
83fcadac
C
287
288 this.metadata.levels.forEach((level, index) => {
e367da94 289 resolutions.push({
83fcadac 290 id: index,
e367da94
C
291 height: level.height,
292 width: level.width,
293 bitrate: level.bitrate,
294 label: this.buildLevelLabel(level),
295 selected: level.id === this.hls.manualLevel,
296
297 selectCallback: () => {
298 this.hls.currentLevel = index
299 }
300 })
83fcadac
C
301 })
302
e367da94
C
303 resolutions.push({
304 id: -1,
305 label: this.player.localize('Auto'),
306 selected: true,
307 selectCallback: () => this.hls.currentLevel = -1
308 })
83fcadac 309
e367da94 310 this.player.peertubeResolutions().add(resolutions)
83fcadac
C
311 }
312
313 private _startLoad () {
314 this.hls.startLoad(-1)
315 this.videoElement.removeEventListener('play', this.handlers.play)
316 }
317
9df52d66 318 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
83fcadac
C
319 const result = {}
320 const objKeys = Object.keys(obj)
321 for (let i = 0; i < objKeys.length; i++) {
9df52d66 322 result[objKeys[i]] = obj[objKeys[i]]
83fcadac
C
323 }
324
325 return result
326 }
327
e367da94 328 private _onMetaData (_event: any, data: ManifestParsedData) {
83fcadac 329 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
e367da94
C
330 this.metadata = data
331 this._notifyVideoQualities()
83fcadac
C
332 }
333
334 private _initHlsjs () {
335 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
336 const srOptions_ = this.player.srOptions_
337
9df52d66 338 const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig
83fcadac
C
339 // Hls.js will write to the reference thus change the object for later streams
340 this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {}
341
342 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
343 this.hlsjsConfig.autoStartLoad = false
344 }
345
83fcadac
C
346 // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above
347 // That's why we have a separate if block here to set the 'play' listener
348 if (this.hlsjsConfig.autoStartLoad === false) {
349 this.handlers.play = this._startLoad.bind(this)
350 this.videoElement.addEventListener('play', this.handlers.play)
351 }
352
83fcadac
C
353 this.hls = new Hlsjs(this.hlsjsConfig)
354
355 this._executeHooksFor('beforeinitialize')
356
357 this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data))
e367da94 358 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data))
83fcadac
C
359 this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => {
360 // The DVR plugin will auto seek to "live edge" on start up
361 if (this.hlsjsConfig.liveSyncDuration) {
362 this.edgeMargin = this.hlsjsConfig.liveSyncDuration
363 } else if (this.hlsjsConfig.liveSyncDurationCount) {
364 this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration
365 }
366
367 this.isLive = data.details.live
368 this.dvrDuration = data.details.totalduration
369 this._duration = this.isLive ? Infinity : data.details.totalduration
370 })
e367da94 371
83fcadac
C
372 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
373 // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls`
374 // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata
375 this.tech.trigger('loadedmetadata')
376 })
377
e367da94
C
378 this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => {
379 const resolutionId = this.hls.autoLevelEnabled
380 ? -1
381 : data.level
382
383 const autoResolutionChosenId = this.hls.autoLevelEnabled
384 ? data.level
385 : -1
386
387 this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true })
388 })
389
83fcadac
C
390 this.hls.attachMedia(this.videoElement)
391
83fcadac
C
392 this.hls.loadSource(this.source.src)
393 }
394
395 private initialize () {
396 this._initHlsjs()
397 }
398}
399
400export {
401 Html5Hlsjs,
402 registerSourceHandler,
403 registerConfigPlugin
404}