]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/p2p-media-loader/hls-plugin.ts
Fix some old typing issues
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / p2p-media-loader / hls-plugin.ts
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
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'
7
8 type ErrorCounts = {
9 [ type: string ]: number
10 }
11
12 type Metadata = {
13 levels: Level[]
14 }
15
16 type HookFn = (player: videojs.Player, hljs: Hlsjs) => void
17
18 const 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
58 function hlsjsConfigHandler (this: videojs.Player, options: HlsjsConfigHandlerOptions) {
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
71 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
72 player.srOptions_.levelLabelHandler = options.levelLabelHandler
73 }
74 }
75
76 const 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
82 class Html5Hlsjs {
83 private static readonly hooks: { [id: string]: HookFn[] } = {}
84
85 private readonly videoElement: HTMLVideoElement
86 private readonly errorCounts: ErrorCounts = {}
87 private readonly player: videojs.Player
88 private readonly tech: videojs.Tech
89 private readonly source: videojs.Tech.SourceObject
90 private readonly vjs: typeof videojs
91
92 private hls: Hlsjs
93 private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null
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
101 private handlers: { [ id in 'play' ]: EventListener } = {
102 play: null
103 }
104
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
117 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
118
119 if (!mediaError) return
120
121 console.log(mediaError)
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:
127 errorTxt = 'The video playback was aborted due to a corruption problem or because the video used features ' +
128 'your browser did not support'
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)
171
172 this.hls.destroy()
173 }
174
175 static addHook (type: string, callback: HookFn) {
176 Html5Hlsjs.hooks[type] = this.hooks[type] || []
177 Html5Hlsjs.hooks[type].push(callback)
178 }
179
180 static removeHook (type: string, callback: HookFn) {
181 if (Html5Hlsjs.hooks[type] === undefined) return false
182
183 const index = Html5Hlsjs.hooks[type].indexOf(callback)
184 if (index === -1) return false
185
186 Html5Hlsjs.hooks[type].splice(index, 1)
187
188 return true
189 }
190
191 private _executeHooksFor (type: string) {
192 if (Html5Hlsjs.hooks[type] === undefined) {
193 return
194 }
195
196 // ES3 and IE < 9
197 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
198 Html5Hlsjs.hooks[type][i](this.player, this.hls)
199 }
200 }
201
202 private _handleMediaError (error: any) {
203 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) {
204 console.info('trying to recover media error')
205 this.hls.recoverMediaError()
206 return
207 }
208
209 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) {
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
216 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
217 console.info('bubbling media error up to VIDEOJS')
218 this.hls.destroy()
219 this.tech.error = () => error
220 this.tech.trigger('error')
221 }
222 }
223
224 private _handleNetworkError (error: any) {
225 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) {
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, () => {
233 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
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
245 private _onError (_event: any, data: ErrorData) {
246 const error: { message: string, code?: number } = {
247 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
248 }
249
250 // increment/set error count
251 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
252 else this.errorCounts[data.type] = 1
253
254 if (data.fatal) console.warn(error.message)
255 else console.error(error.message, data)
256
257 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
258 error.code = 2
259 this._handleNetworkError(error)
260 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
261 error.code = 3
262 this._handleMediaError(error)
263 } else if (data.fatal) {
264 this.hls.destroy()
265 console.info('bubbling error up to VIDEOJS')
266 this.tech.error = () => error as any
267 this.tech.trigger('error')
268 }
269 }
270
271 private buildLevelLabel (level: Level) {
272 if (this.player.srOptions_.levelLabelHandler) {
273 return this.player.srOptions_.levelLabelHandler(level as any)
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
280 return '0'
281 }
282
283 private _notifyVideoQualities () {
284 if (!this.metadata) return
285
286 const resolutions: PeerTubeResolution[] = []
287
288 this.metadata.levels.forEach((level, index) => {
289 resolutions.push({
290 id: index,
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 })
301 })
302
303 resolutions.push({
304 id: -1,
305 label: this.player.localize('Auto'),
306 selected: true,
307 selectCallback: () => this.hls.currentLevel = -1
308 })
309
310 this.player.peertubeResolutions().add(resolutions)
311 }
312
313 private _startLoad () {
314 this.hls.startLoad(-1)
315 this.videoElement.removeEventListener('play', this.handlers.play)
316 }
317
318 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
319 const result = {}
320 const objKeys = Object.keys(obj)
321 for (let i = 0; i < objKeys.length; i++) {
322 result[objKeys[i]] = obj[objKeys[i]]
323 }
324
325 return result
326 }
327
328 private _onMetaData (_event: any, data: ManifestParsedData) {
329 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
330 this.metadata = data
331 this._notifyVideoQualities()
332 }
333
334 private _initHlsjs () {
335 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
336 const srOptions_ = this.player.srOptions_
337
338 const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig
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
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
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))
358 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data))
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 })
371
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
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
390 this.hls.attachMedia(this.videoElement)
391
392 this.hls.loadSource(this.source.src)
393 }
394
395 private initialize () {
396 this._initHlsjs()
397 }
398 }
399
400 export {
401 Html5Hlsjs,
402 registerSourceHandler,
403 registerConfigPlugin
404 }