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