]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/shared/p2p-media-loader/hls-plugin.ts
Add playback metric endpoint sent to OTEL
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / shared / 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'
42b40636 6import { logger } from '@root-helpers/logger'
57d65032 7import { HlsjsConfigHandlerOptions, PeerTubeResolution, VideoJSTechHLS } from '../../types'
83fcadac
C
8
9type ErrorCounts = {
10 [ type: string ]: number
11}
12
13type Metadata = {
134006b0 14 levels: Level[]
83fcadac
C
15}
16
9df52d66
C
17type HookFn = (player: videojs.Player, hljs: Hlsjs) => void
18
83fcadac
C
19const registerSourceHandler = function (vjs: typeof videojs) {
20 if (!Hlsjs.isSupported()) {
42b40636 21 logger.warn('Hls.js is not supported in this browser!')
83fcadac
C
22 return
23 }
24
25 const html5 = vjs.getTech('Html5')
26
27 if (!html5) {
42b40636 28 logger.error('No Hml5 tech found in videojs')
83fcadac
C
29 return
30 }
31
32 // FIXME: typings
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
37
38 if (hlsTypeRE.test(source.type)) return 'probably'
39 if (hlsExtRE.test(source.src)) return 'maybe'
40
41 return ''
42 },
43
44 handleSource: function (source: videojs.Tech.SourceObject, tech: VideoJSTechHLS) {
45 if (tech.hlsProvider) {
46 tech.hlsProvider.dispose()
47 }
48
49 tech.hlsProvider = new Html5Hlsjs(vjs, source, tech)
50
51 return tech.hlsProvider
52 }
53 }, 0);
54
55 // FIXME: typings
56 (vjs as any).Html5Hlsjs = Html5Hlsjs
57}
58
7e37e111 59function hlsjsConfigHandler (this: videojs.Player, options: HlsjsConfigHandlerOptions) {
83fcadac
C
60 const player = this
61
62 if (!options) return
63
64 if (!player.srOptions_) {
65 player.srOptions_ = {}
66 }
67
68 if (!player.srOptions_.hlsjsConfig) {
69 player.srOptions_.hlsjsConfig = options.hlsjsConfig
70 }
71
83fcadac
C
72 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
73 player.srOptions_.levelLabelHandler = options.levelLabelHandler
74 }
75}
76
77const 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)
81}
82
83class Html5Hlsjs {
9df52d66 84 private static readonly hooks: { [id: string]: HookFn[] } = {}
83fcadac
C
85
86 private readonly videoElement: HTMLVideoElement
87 private readonly errorCounts: ErrorCounts = {}
7e37e111 88 private readonly player: videojs.Player
83fcadac
C
89 private readonly tech: videojs.Tech
90 private readonly source: videojs.Tech.SourceObject
91 private readonly vjs: typeof videojs
92
077a413f
C
93 private maxNetworkErrorRecovery = 5
94
134006b0
C
95 private hls: Hlsjs
96 private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null
83fcadac
C
97
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
103
e367da94
C
104 private handlers: { [ id in 'play' ]: EventListener } = {
105 play: null
83fcadac
C
106 }
107
83fcadac
C
108 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
109 this.vjs = vjs
110 this.source = source
111
112 this.tech = tech;
113 (this.tech as any).name_ = 'Hlsjs'
114
115 this.videoElement = tech.el() as HTMLVideoElement
116 this.player = vjs((tech.options_ as any).playerId)
117
118 this.videoElement.addEventListener('error', event => {
119 let errorTxt: string
d0dd9813 120 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
83fcadac 121
d0dd9813
C
122 if (!mediaError) return
123
42b40636 124 logger.info(mediaError)
83fcadac
C
125 switch (mediaError.code) {
126 case mediaError.MEDIA_ERR_ABORTED:
127 errorTxt = 'You aborted the video playback'
128 break
129 case mediaError.MEDIA_ERR_DECODE:
9df52d66
C
130 errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' +
131 'your browser did not support'
83fcadac
C
132 this._handleMediaError(mediaError)
133 break
134 case mediaError.MEDIA_ERR_NETWORK:
135 errorTxt = 'A network error caused the video download to fail part-way'
136 break
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'
139 break
140
141 default:
142 errorTxt = mediaError.message
143 }
144
42b40636 145 logger.error(`MEDIA_ERROR: ${errorTxt}`)
83fcadac
C
146 })
147
148 this.initialize()
149 }
150
151 duration () {
51d81175 152 if (this._duration === Infinity) return Infinity
22f25c74
C
153 if (!isNaN(this.videoElement.duration)) return this.videoElement.duration
154
155 return this._duration || 0
83fcadac
C
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)
83fcadac 177
c4207f97
C
178 // FIXME: https://github.com/video-dev/hls.js/issues/4092
179 const untypedHLS = this.hls as any
180 untypedHLS.log = untypedHLS.warn = () => {
181 // empty
182 }
183
83fcadac
C
184 this.hls.destroy()
185 }
186
9df52d66
C
187 static addHook (type: string, callback: HookFn) {
188 Html5Hlsjs.hooks[type] = this.hooks[type] || []
189 Html5Hlsjs.hooks[type].push(callback)
83fcadac
C
190 }
191
9df52d66
C
192 static removeHook (type: string, callback: HookFn) {
193 if (Html5Hlsjs.hooks[type] === undefined) return false
83fcadac 194
9df52d66 195 const index = Html5Hlsjs.hooks[type].indexOf(callback)
83fcadac
C
196 if (index === -1) return false
197
9df52d66 198 Html5Hlsjs.hooks[type].splice(index, 1)
83fcadac
C
199
200 return true
201 }
202
203 private _executeHooksFor (type: string) {
9df52d66 204 if (Html5Hlsjs.hooks[type] === undefined) {
83fcadac
C
205 return
206 }
207
208 // ES3 and IE < 9
9df52d66
C
209 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
210 Html5Hlsjs.hooks[type][i](this.player, this.hls)
83fcadac
C
211 }
212 }
213
214 private _handleMediaError (error: any) {
9df52d66 215 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) {
42b40636 216 logger.info('trying to recover media error')
83fcadac
C
217 this.hls.recoverMediaError()
218 return
219 }
220
9df52d66 221 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) {
42b40636 222 logger.info('2nd try to recover media error (by swapping audio codec')
83fcadac
C
223 this.hls.swapAudioCodec()
224 this.hls.recoverMediaError()
225 return
226 }
227
9df52d66 228 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
42b40636 229 logger.info('bubbling media error up to VIDEOJS')
adc1f09c 230 this.hls.destroy()
83fcadac
C
231 this.tech.error = () => error
232 this.tech.trigger('error')
83fcadac
C
233 }
234 }
235
2d056f66 236 private _handleNetworkError (error: any) {
077a413f 237 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= this.maxNetworkErrorRecovery) {
42b40636 238 logger.info('trying to recover network error')
2d056f66
C
239
240 // Wait 1 second and retry
241 setTimeout(() => this.hls.startLoad(), 1000)
242
243 // Reset error count on success
244 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
9df52d66 245 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
2d056f66
C
246 })
247
248 return
249 }
250
42b40636 251 logger.info('bubbling network error up to VIDEOJS')
2d056f66
C
252 this.hls.destroy()
253 this.tech.error = () => error
254 this.tech.trigger('error')
255 }
256
134006b0 257 private _onError (_event: any, data: ErrorData) {
83fcadac
C
258 const error: { message: string, code?: number } = {
259 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
260 }
83fcadac
C
261
262 // increment/set error count
9df52d66
C
263 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
264 else this.errorCounts[data.type] = 1
83fcadac 265
42b40636
C
266 if (data.fatal) logger.warn(error.message)
267 else logger.error(error.message, { data })
83fcadac 268
e25f83ce 269 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
e25f83ce 270 error.code = 2
2d056f66 271 this._handleNetworkError(error)
3e254de8 272 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
e25f83ce
C
273 error.code = 3
274 this._handleMediaError(error)
3e254de8 275 } else if (data.fatal) {
e25f83ce 276 this.hls.destroy()
42b40636 277 logger.info('bubbling error up to VIDEOJS')
e25f83ce
C
278 this.tech.error = () => error as any
279 this.tech.trigger('error')
83fcadac
C
280 }
281 }
282
e367da94 283 private buildLevelLabel (level: Level) {
83fcadac 284 if (this.player.srOptions_.levelLabelHandler) {
3e254de8 285 return this.player.srOptions_.levelLabelHandler(level as any)
83fcadac
C
286 }
287
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'
291
e367da94 292 return '0'
83fcadac
C
293 }
294
295 private _notifyVideoQualities () {
296 if (!this.metadata) return
83fcadac 297
e367da94 298 const resolutions: PeerTubeResolution[] = []
83fcadac
C
299
300 this.metadata.levels.forEach((level, index) => {
e367da94 301 resolutions.push({
83fcadac 302 id: index,
e367da94
C
303 height: level.height,
304 width: level.width,
305 bitrate: level.bitrate,
306 label: this.buildLevelLabel(level),
307 selected: level.id === this.hls.manualLevel,
308
309 selectCallback: () => {
310 this.hls.currentLevel = index
311 }
312 })
83fcadac
C
313 })
314
e367da94
C
315 resolutions.push({
316 id: -1,
317 label: this.player.localize('Auto'),
318 selected: true,
319 selectCallback: () => this.hls.currentLevel = -1
320 })
83fcadac 321
e367da94 322 this.player.peertubeResolutions().add(resolutions)
83fcadac
C
323 }
324
325 private _startLoad () {
326 this.hls.startLoad(-1)
327 this.videoElement.removeEventListener('play', this.handlers.play)
328 }
329
9df52d66 330 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
83fcadac
C
331 const result = {}
332 const objKeys = Object.keys(obj)
333 for (let i = 0; i < objKeys.length; i++) {
9df52d66 334 result[objKeys[i]] = obj[objKeys[i]]
83fcadac
C
335 }
336
337 return result
338 }
339
e367da94 340 private _onMetaData (_event: any, data: ManifestParsedData) {
83fcadac 341 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
e367da94
C
342 this.metadata = data
343 this._notifyVideoQualities()
83fcadac
C
344 }
345
346 private _initHlsjs () {
347 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
348 const srOptions_ = this.player.srOptions_
349
9df52d66 350 const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig
83fcadac
C
351 // Hls.js will write to the reference thus change the object for later streams
352 this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {}
353
354 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
355 this.hlsjsConfig.autoStartLoad = false
356 }
357
83fcadac
C
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)
363 }
364
83fcadac
C
365 this.hls = new Hlsjs(this.hlsjsConfig)
366
367 this._executeHooksFor('beforeinitialize')
368
369 this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data))
e367da94 370 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data))
83fcadac
C
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
377 }
378
379 this.isLive = data.details.live
380 this.dvrDuration = data.details.totalduration
22f25c74 381
83fcadac 382 this._duration = this.isLive ? Infinity : data.details.totalduration
077a413f
C
383
384 // Increase network error recovery for lives since they can be broken (server restart, stream interruption etc)
385 if (this.isLive) this.maxNetworkErrorRecovery = 300
83fcadac 386 })
e367da94 387
83fcadac
C
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')
392 })
393
e367da94
C
394 this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => {
395 const resolutionId = this.hls.autoLevelEnabled
396 ? -1
397 : data.level
398
399 const autoResolutionChosenId = this.hls.autoLevelEnabled
400 ? data.level
401 : -1
402
403 this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true })
404 })
405
83fcadac
C
406 this.hls.attachMedia(this.videoElement)
407
83fcadac
C
408 this.hls.loadSource(this.source.src)
409 }
410
411 private initialize () {
412 this._initHlsjs()
413 }
414}
415
416export {
417 Html5Hlsjs,
418 registerSourceHandler,
419 registerConfigPlugin
420}