]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/p2p-media-loader/hls-plugin.ts
Cleanup player quality change
[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 (!player.srOptions_.captionConfig) {
72 player.srOptions_.captionConfig = options.captionConfig
73 }
74
75 if (options.levelLabelHandler && !player.srOptions_.levelLabelHandler) {
76 player.srOptions_.levelLabelHandler = options.levelLabelHandler
77 }
78 }
79
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)
84 }
85
86 class Html5Hlsjs {
87 private static readonly hooks: { [id: string]: HookFn[] } = {}
88
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
95
96 private hls: Hlsjs
97 private hlsjsConfig: Partial<HlsConfig & { cueHandler: any }> = null
98
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
104
105 private handlers: { [ id in 'play' ]: EventListener } = {
106 play: null
107 }
108
109 constructor (vjs: typeof videojs, source: videojs.Tech.SourceObject, tech: videojs.Tech) {
110 this.vjs = vjs
111 this.source = source
112
113 this.tech = tech;
114 (this.tech as any).name_ = 'Hlsjs'
115
116 this.videoElement = tech.el() as HTMLVideoElement
117 this.player = vjs((tech.options_ as any).playerId)
118
119 this.videoElement.addEventListener('error', event => {
120 let errorTxt: string
121 const mediaError = ((event.currentTarget || event.target) as HTMLVideoElement).error
122
123 if (!mediaError) return
124
125 console.log(mediaError)
126 switch (mediaError.code) {
127 case mediaError.MEDIA_ERR_ABORTED:
128 errorTxt = 'You aborted the video playback'
129 break
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)
134 break
135 case mediaError.MEDIA_ERR_NETWORK:
136 errorTxt = 'A network error caused the video download to fail part-way'
137 break
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'
140 break
141
142 default:
143 errorTxt = mediaError.message
144 }
145
146 console.error('MEDIA_ERROR: ', errorTxt)
147 })
148
149 this.initialize()
150 }
151
152 duration () {
153 return this._duration || this.videoElement.duration || 0
154 }
155
156 seekable () {
157 if (this.hls.media) {
158 if (!this.isLive) {
159 return this.vjs.createTimeRanges(0, this.hls.media.duration)
160 }
161
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)
165
166 return this.vjs.createTimeRanges(startTime, endTime)
167 }
168
169 return this.vjs.createTimeRanges()
170 }
171
172 // See comment for `initialize` method.
173 dispose () {
174 this.videoElement.removeEventListener('play', this.handlers.play)
175
176 this.hls.destroy()
177 }
178
179 static addHook (type: string, callback: HookFn) {
180 Html5Hlsjs.hooks[type] = this.hooks[type] || []
181 Html5Hlsjs.hooks[type].push(callback)
182 }
183
184 static removeHook (type: string, callback: HookFn) {
185 if (Html5Hlsjs.hooks[type] === undefined) return false
186
187 const index = Html5Hlsjs.hooks[type].indexOf(callback)
188 if (index === -1) return false
189
190 Html5Hlsjs.hooks[type].splice(index, 1)
191
192 return true
193 }
194
195 private _executeHooksFor (type: string) {
196 if (Html5Hlsjs.hooks[type] === undefined) {
197 return
198 }
199
200 // ES3 and IE < 9
201 for (let i = 0; i < Html5Hlsjs.hooks[type].length; i++) {
202 Html5Hlsjs.hooks[type][i](this.player, this.hls)
203 }
204 }
205
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()
210 return
211 }
212
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()
217 return
218 }
219
220 if (this.errorCounts[Hlsjs.ErrorTypes.MEDIA_ERROR] > 2) {
221 console.info('bubbling media error up to VIDEOJS')
222 this.hls.destroy()
223 this.tech.error = () => error
224 this.tech.trigger('error')
225 }
226 }
227
228 private _handleNetworkError (error: any) {
229 if (this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] <= 5) {
230 console.info('trying to recover network error')
231
232 // Wait 1 second and retry
233 setTimeout(() => this.hls.startLoad(), 1000)
234
235 // Reset error count on success
236 this.hls.once(Hlsjs.Events.FRAG_LOADED, () => {
237 this.errorCounts[Hlsjs.ErrorTypes.NETWORK_ERROR] = 0
238 })
239
240 return
241 }
242
243 console.info('bubbling network error up to VIDEOJS')
244 this.hls.destroy()
245 this.tech.error = () => error
246 this.tech.trigger('error')
247 }
248
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}`
252 }
253
254 // increment/set error count
255 if (this.errorCounts[data.type]) this.errorCounts[data.type] += 1
256 else this.errorCounts[data.type] = 1
257
258 if (data.fatal) console.warn(error.message)
259 else console.error(error.message, data)
260
261 if (data.type === Hlsjs.ErrorTypes.NETWORK_ERROR) {
262 error.code = 2
263 this._handleNetworkError(error)
264 } else if (data.fatal && data.type === Hlsjs.ErrorTypes.MEDIA_ERROR && data.details !== 'manifestIncompatibleCodecsError') {
265 error.code = 3
266 this._handleMediaError(error)
267 } else if (data.fatal) {
268 this.hls.destroy()
269 console.info('bubbling error up to VIDEOJS')
270 this.tech.error = () => error as any
271 this.tech.trigger('error')
272 }
273 }
274
275 private buildLevelLabel (level: Level) {
276 if (this.player.srOptions_.levelLabelHandler) {
277 return this.player.srOptions_.levelLabelHandler(level as any)
278 }
279
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'
283
284 return '0'
285 }
286
287 private _notifyVideoQualities () {
288 if (!this.metadata) return
289
290 const resolutions: PeerTubeResolution[] = []
291
292 this.metadata.levels.forEach((level, index) => {
293 resolutions.push({
294 id: index,
295 height: level.height,
296 width: level.width,
297 bitrate: level.bitrate,
298 label: this.buildLevelLabel(level),
299 selected: level.id === this.hls.manualLevel,
300
301 selectCallback: () => {
302 this.hls.currentLevel = index
303 }
304 })
305 })
306
307 resolutions.push({
308 id: -1,
309 label: this.player.localize('Auto'),
310 selected: true,
311 selectCallback: () => this.hls.currentLevel = -1
312 })
313
314 this.player.peertubeResolutions().add(resolutions)
315 }
316
317 private _startLoad () {
318 this.hls.startLoad(-1)
319 this.videoElement.removeEventListener('play', this.handlers.play)
320 }
321
322 private _oneLevelObjClone (obj: { [ id: string ]: any }) {
323 const result = {}
324 const objKeys = Object.keys(obj)
325 for (let i = 0; i < objKeys.length; i++) {
326 result[objKeys[i]] = obj[objKeys[i]]
327 }
328
329 return result
330 }
331
332 private _onMetaData (_event: any, data: ManifestParsedData) {
333 // This could arrive before 'loadedqualitydata' handlers is registered, remember it so we can raise it later
334 this.metadata = data
335 this._notifyVideoQualities()
336 }
337
338 private _initHlsjs () {
339 const techOptions = this.tech.options_ as HlsjsConfigHandlerOptions
340 const srOptions_ = this.player.srOptions_
341
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) : {}
345
346 if ([ '', 'auto' ].includes(this.videoElement.preload) && !this.videoElement.autoplay && this.hlsjsConfig.autoStartLoad === undefined) {
347 this.hlsjsConfig.autoStartLoad = false
348 }
349
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)
355 }
356
357 this.hls = new Hlsjs(this.hlsjsConfig)
358
359 this._executeHooksFor('beforeinitialize')
360
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
369 }
370
371 this.isLive = data.details.live
372 this.dvrDuration = data.details.totalduration
373 this._duration = this.isLive ? Infinity : data.details.totalduration
374 })
375
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')
380 })
381
382 this.hls.on(Hlsjs.Events.LEVEL_SWITCHING, (_e, data: LevelSwitchingData) => {
383 const resolutionId = this.hls.autoLevelEnabled
384 ? -1
385 : data.level
386
387 const autoResolutionChosenId = this.hls.autoLevelEnabled
388 ? data.level
389 : -1
390
391 this.player.peertubeResolutions().select({ id: resolutionId, autoResolutionChosenId, byEngine: true })
392 })
393
394 this.hls.attachMedia(this.videoElement)
395
396 this.hls.loadSource(this.source.src)
397 }
398
399 private initialize () {
400 this._initHlsjs()
401 }
402 }
403
404 export {
405 Html5Hlsjs,
406 registerSourceHandler,
407 registerConfigPlugin
408 }