]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/p2p-media-loader/hls-plugin.ts
Merge branch 'release/4.0.0' into develop
[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 if (!isNaN(this.videoElement.duration)) return this.videoElement.duration
150
151 return this._duration || 0
152 }
153
154 seekable () {
155 if (this.hls.media) {
156 if (!this.isLive) {
157 return this.vjs.createTimeRanges(0, this.hls.media.duration)
158 }
159
160 // Video.js doesn't seem to like floating point timeranges
161 const startTime = Math.round(this.hls.media.duration - this.dvrDuration)
162 const endTime = Math.round(this.hls.media.duration - this.edgeMargin)
163
164 return this.vjs.createTimeRanges(startTime, endTime)
165 }
166
167 return this.vjs.createTimeRanges()
168 }
169
170 // See comment for `initialize` method.
171 dispose () {
172 this.videoElement.removeEventListener('play', this.handlers.play)
173
174 this.hls.destroy()
175 }
176
177 static addHook (type: string, callback: HookFn) {
178 Html5Hlsjs.hooks[type] = this.hooks[type] || []
179 Html5Hlsjs.hooks[type].push(callback)
180 }
181
182 static removeHook (type: string, callback: HookFn) {
183 if (Html5Hlsjs.hooks[type] === undefined) return false
184
185 const index = Html5Hlsjs.hooks[type].indexOf(callback)
186 if (index === -1) return false
187
188 Html5Hlsjs.hooks[type].splice(index, 1)
189
190 return true
191 }
192
193 private _executeHooksFor (type: string) {
194 if (Html5Hlsjs.hooks[type] === undefined) {
195 return
196 }
197
198 // ES3 and IE < 9
199 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
200 Html5Hlsjs.hooks[type][i](this.player, this.hls)
201 }
202 }
203
204 private _handleMediaError (error: any) {
205 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 1) {
206 console.info('trying to recover media error')
207 this.hls.recoverMediaError()
208 return
209 }
210
211 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] === 2) {
212 console.info('2nd try to recover media error (by swapping audio codec')
213 this.hls.swapAudioCodec()
214 this.hls.recoverMediaError()
215 return
216 }
217
218 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
219 console.info('bubbling media error up to VIDEOJS')
220 this.hls.destroy()
221 this.tech.error = () => error
222 this.tech.trigger('error')
223 }
224 }
225
226 private _handleNetworkError (error: any) {
227 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) {
228 console.info('trying to recover network error')
229
230 // Wait 1 second and retry
231 setTimeout(() => this.hls.startLoad(), 1000)
232
233 // Reset error count on success
234 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
235 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
236 })
237
238 return
239 }
240
241 console.info('bubbling network error up to VIDEOJS')
242 this.hls.destroy()
243 this.tech.error = () => error
244 this.tech.trigger('error')
245 }
246
247 private _onError (_event: any, data: ErrorData) {
248 const error: { message: string, code?: number } = {
249 message: `HLS.js error: ${data.type} - fatal: ${data.fatal} - ${data.details}`
250 }
251
252 // increment/set error count
253 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
254 else this.errorCounts[data.type] = 1
255
256 if (data.fatal) console.warn(error.message)
257 else console.error(error.message, data)
258
259 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
260 error.code = 2
261 this._handleNetworkError(error)
262 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
263 error.code = 3
264 this._handleMediaError(error)
265 } else if (data.fatal) {
266 this.hls.destroy()
267 console.info('bubbling error up to VIDEOJS')
268 this.tech.error = () => error as any
269 this.tech.trigger('error')
270 }
271 }
272
273 private buildLevelLabel (level: Level) {
274 if (this.player.srOptions_.levelLabelHandler) {
275 return this.player.srOptions_.levelLabelHandler(level as any)
276 }
277
278 if (level.height) return level.height + 'p'
279 if (level.width) return Math.round(level.width * 9 / 16) + 'p'
280 if (level.bitrate) return (level.bitrate / 1000) + 'kbps'
281
282 return '0'
283 }
284
285 private _notifyVideoQualities () {
286 if (!this.metadata) return
287
288 const resolutions: PeerTubeResolution[] = []
289
290 this.metadata.levels.forEach((level, index) => {
291 resolutions.push({
292 id: index,
293 height: level.height,
294 width: level.width,
295 bitrate: level.bitrate,
296 label: this.buildLevelLabel(level),
297 selected: level.id === this.hls.manualLevel,
298
299 selectCallback: () => {
300 this.hls.currentLevel = index
301 }
302 })
303 })
304
305 resolutions.push({
306 id: -1,
307 label: this.player.localize('Auto'),
308 selected: true,
309 selectCallback: () => this.hls.currentLevel = -1
310 })
311
312 this.player.peertubeResolutions().add(resolutions)
313 }
314
315 private _startLoad () {
316 this.hls.startLoad(-1)
317 this.videoElement.removeEventListener('play', this.handlers.play)
318 }
319
320 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
321 const result = {}
322 const objKeys = Object.keys(obj)
323 for (let i = 0; i < objKeys.length; i++) {
324 result[objKeys[i]] = obj[objKeys[i]]
325 }
326
327 return result
328 }
329
330 private _onMetaData (_event: any, data: ManifestParsedData) {
331 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
332 this.metadata = data
333 this._notifyVideoQualities()
334 }
335
336 private _initHlsjs () {
337 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
338 const srOptions_ = this.player.srOptions_
339
340 const hlsjsConfigRef = srOptions_?.hlsjsConfig || techOptions.hlsjsConfig
341 // Hls.js will write to the reference thus change the object for later streams
342 this.hlsjsConfig = hlsjsConfigRef ? this._oneLevelObjClone(hlsjsConfigRef) : {}
343
344 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
345 this.hlsjsConfig.autoStartLoad = false
346 }
347
348 // If the user explicitly sets autoStartLoad to false, we're not going to enter the if block above
349 // That's why we have a separate if block here to set the 'play' listener
350 if (this.hlsjsConfig.autoStartLoad === false) {
351 this.handlers.play = this._startLoad.bind(this)
352 this.videoElement.addEventListener('play', this.handlers.play)
353 }
354
355 this.hls = new Hlsjs(this.hlsjsConfig)
356
357 this._executeHooksFor('beforeinitialize')
358
359 this.hls.on(Hlsjs.Events.ERROR, (event, data) => this._onError(event, data))
360 this.hls.on(Hlsjs.Events.MANIFEST_PARSED, (event, data) => this._onMetaData(event, data))
361 this.hls.on(Hlsjs.Events.LEVEL_LOADED, (event, data) => {
362 // The DVR plugin will auto seek to "live edge" on start up
363 if (this.hlsjsConfig.liveSyncDuration) {
364 this.edgeMargin = this.hlsjsConfig.liveSyncDuration
365 } else if (this.hlsjsConfig.liveSyncDurationCount) {
366 this.edgeMargin = this.hlsjsConfig.liveSyncDurationCount * data.details.targetduration
367 }
368
369 this.isLive = data.details.live
370 this.dvrDuration = data.details.totalduration
371
372 this._duration = this.isLive ? Infinity : data.details.totalduration
373 })
374
375 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
376 // Emit custom 'loadedmetadata' event for parity with `videojs-contrib-hls`
377 // Ref: https://github.com/videojs/videojs-contrib-hls#loadedmetadata
378 this.tech.trigger('loadedmetadata')
379 })
380
381 this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => {
382 const resolutionId = this.hls.autoLevelEnabled
383 ? -1
384 : data.level
385
386 const autoResolutionChosenId = this.hls.autoLevelEnabled
387 ? data.level
388 : -1
389
390 this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true })
391 })
392
393 this.hls.attachMedia(this.videoElement)
394
395 this.hls.loadSource(this.source.src)
396 }
397
398 private initialize () {
399 this._initHlsjs()
400 }
401 }
402
403 export {
404 Html5Hlsjs,
405 registerSourceHandler,
406 registerConfigPlugin
407 }