Fix captions in HTTP fallback
[oweals/peertube.git] / client / src / assets / player / peertube-videojs-plugin.ts
1 // FIXME: something weird with our path definition in tsconfig and typings
2 // @ts-ignore
3 import * as videojs from 'video.js'
4
5 import * as WebTorrent from 'webtorrent'
6 import { VideoFile } from '../../../../shared/models/videos/video.model'
7 import { renderVideo } from './video-renderer'
8 import './settings-menu-button'
9 import { PeertubePluginOptions, UserWatching, VideoJSCaption, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
10 import { isMobile, timeToInt, videoFileMaxByResolution, videoFileMinByResolution } from './utils'
11 import { PeertubeChunkStore } from './peertube-chunk-store'
12 import {
13   getAverageBandwidthInStore,
14   getStoredLastSubtitle,
15   getStoredMute,
16   getStoredVolume,
17   getStoredWebTorrentEnabled,
18   saveAverageBandwidth,
19   saveLastSubtitle,
20   saveMuteInStore,
21   saveVolumeInStore
22 } from './peertube-player-local-storage'
23
24 const CacheChunkStore = require('cache-chunk-store')
25
26 type PlayOptions = {
27   forcePlay?: boolean,
28   seek?: number,
29   delay?: number
30 }
31
32 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
33 class PeerTubePlugin extends Plugin {
34   private readonly playerElement: HTMLVideoElement
35
36   private readonly autoplay: boolean = false
37   private readonly startTime: number = 0
38   private readonly savePlayerSrcFunction: Function
39   private readonly videoFiles: VideoFile[]
40   private readonly videoViewUrl: string
41   private readonly videoDuration: number
42   private readonly CONSTANTS = {
43     INFO_SCHEDULER: 1000, // Don't change this
44     AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
45     AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
46     AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
47     AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
48     BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5, // Last 5 seconds to build average bandwidth
49     USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
50   }
51
52   private readonly webtorrent = new WebTorrent({
53     tracker: {
54       rtcConfig: {
55         iceServers: [
56           {
57             urls: 'stun:stun.stunprotocol.org'
58           },
59           {
60             urls: 'stun:stun.framasoft.org'
61           }
62         ]
63       }
64     },
65     dht: false
66   })
67
68   private player: any
69   private currentVideoFile: VideoFile
70   private torrent: WebTorrent.Torrent
71   private videoCaptions: VideoJSCaption[]
72   private defaultSubtitle: string
73
74   private renderer: any
75   private fakeRenderer: any
76   private destroyingFakeRenderer = false
77
78   private autoResolution = true
79   private forbidAutoResolution = false
80   private isAutoResolutionObservation = false
81   private playerRefusedP2P = false
82
83   private videoViewInterval: any
84   private torrentInfoInterval: any
85   private autoQualityInterval: any
86   private userWatchingVideoInterval: any
87   private addTorrentDelay: any
88   private qualityObservationTimer: any
89   private runAutoQualitySchedulerTimer: any
90
91   private downloadSpeeds: number[] = []
92
93   constructor (player: videojs.Player, options: PeertubePluginOptions) {
94     super(player, options)
95
96     // Disable auto play on iOS
97     this.autoplay = options.autoplay && this.isIOS() === false
98     this.playerRefusedP2P = !getStoredWebTorrentEnabled()
99
100     this.startTime = timeToInt(options.startTime)
101     this.videoFiles = options.videoFiles
102     this.videoViewUrl = options.videoViewUrl
103     this.videoDuration = options.videoDuration
104     this.videoCaptions = options.videoCaptions
105
106     this.savePlayerSrcFunction = this.player.src
107     this.playerElement = options.playerElement
108
109     if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
110
111     this.player.ready(() => {
112       const playerOptions = this.player.options_
113
114       const volume = getStoredVolume()
115       if (volume !== undefined) this.player.volume(volume)
116
117       const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
118       if (muted !== undefined) this.player.muted(muted)
119
120       this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
121
122       this.player.on('volumechange', () => {
123         saveVolumeInStore(this.player.volume())
124         saveMuteInStore(this.player.muted())
125       })
126
127       this.player.textTracks().on('change', () => {
128         const showing = this.player.textTracks().tracks_.find((t: { kind: string, mode: string }) => {
129           return t.kind === 'captions' && t.mode === 'showing'
130         })
131
132         if (!showing) {
133           saveLastSubtitle('off')
134           return
135         }
136
137         saveLastSubtitle(showing.language)
138       })
139
140       this.player.duration(options.videoDuration)
141
142       this.initializePlayer()
143       this.runTorrentInfoScheduler()
144       this.runViewAdd()
145
146       if (options.userWatching) this.runUserWatchVideo(options.userWatching)
147
148       this.player.one('play', () => {
149         // Don't run immediately scheduler, wait some seconds the TCP connections are made
150         this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
151       })
152     })
153   }
154
155   dispose () {
156     clearTimeout(this.addTorrentDelay)
157     clearTimeout(this.qualityObservationTimer)
158     clearTimeout(this.runAutoQualitySchedulerTimer)
159
160     clearInterval(this.videoViewInterval)
161     clearInterval(this.torrentInfoInterval)
162     clearInterval(this.autoQualityInterval)
163
164     if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
165
166     // Don't need to destroy renderer, video player will be destroyed
167     this.flushVideoFile(this.currentVideoFile, false)
168
169     this.destroyFakeRenderer()
170   }
171
172   getCurrentResolutionId () {
173     return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
174   }
175
176   getCurrentResolutionLabel () {
177     if (!this.currentVideoFile) return ''
178
179     const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
180     return this.currentVideoFile.resolution.label + fps
181   }
182
183   updateVideoFile (
184     videoFile?: VideoFile,
185     options: {
186       forcePlay?: boolean,
187       seek?: number,
188       delay?: number
189     } = {},
190     done: () => void = () => { /* empty */ }
191   ) {
192     // Automatically choose the adapted video file
193     if (videoFile === undefined) {
194       const savedAverageBandwidth = getAverageBandwidthInStore()
195       videoFile = savedAverageBandwidth
196         ? this.getAppropriateFile(savedAverageBandwidth)
197         : this.pickAverageVideoFile()
198     }
199
200     // Don't add the same video file once again
201     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
202       return
203     }
204
205     // Do not display error to user because we will have multiple fallback
206     this.disableErrorDisplay()
207
208     // Hack to "simulate" src link in video.js >= 6
209     // Without this, we can't play the video after pausing it
210     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
211     this.player.src = () => true
212     const oldPlaybackRate = this.player.playbackRate()
213
214     const previousVideoFile = this.currentVideoFile
215     this.currentVideoFile = videoFile
216
217     // Don't try on iOS that does not support MediaSource
218     // Or don't use P2P if webtorrent is disabled
219     if (this.isIOS() || this.playerRefusedP2P) {
220       return this.fallbackToHttp(options, () => {
221         this.player.playbackRate(oldPlaybackRate)
222         return done()
223       })
224     }
225
226     this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
227       this.player.playbackRate(oldPlaybackRate)
228       return done()
229     })
230
231     this.trigger('videoFileUpdate')
232   }
233
234   updateResolution (resolutionId: number, delay = 0) {
235     // Remember player state
236     const currentTime = this.player.currentTime()
237     const isPaused = this.player.paused()
238
239     // Remove poster to have black background
240     this.playerElement.poster = ''
241
242     // Hide bigPlayButton
243     if (!isPaused) {
244       this.player.bigPlayButton.hide()
245     }
246
247     const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
248     const options = {
249       forcePlay: false,
250       delay,
251       seek: currentTime + (delay / 1000)
252     }
253     this.updateVideoFile(newVideoFile, options)
254   }
255
256   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
257     if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
258       if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
259
260       this.webtorrent.remove(videoFile.magnetUri)
261       console.log('Removed ' + videoFile.magnetUri)
262     }
263   }
264
265   isAutoResolutionOn () {
266     return this.autoResolution
267   }
268
269   enableAutoResolution () {
270     this.autoResolution = true
271     this.trigger('autoResolutionUpdate')
272   }
273
274   disableAutoResolution (forbid = false) {
275     if (forbid === true) this.forbidAutoResolution = true
276
277     this.autoResolution = false
278     this.trigger('autoResolutionUpdate')
279   }
280
281   isAutoResolutionForbidden () {
282     return this.forbidAutoResolution === true
283   }
284
285   getCurrentVideoFile () {
286     return this.currentVideoFile
287   }
288
289   getTorrent () {
290     return this.torrent
291   }
292
293   private addTorrent (
294     magnetOrTorrentUrl: string,
295     previousVideoFile: VideoFile,
296     options: PlayOptions,
297     done: Function
298   ) {
299     console.log('Adding ' + magnetOrTorrentUrl + '.')
300
301     const oldTorrent = this.torrent
302     const torrentOptions = {
303       store: (chunkLength: number, storeOpts: any) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
304         max: 100
305       })
306     }
307
308     this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
309       console.log('Added ' + magnetOrTorrentUrl + '.')
310
311       if (oldTorrent) {
312         // Pause the old torrent
313         this.stopTorrent(oldTorrent)
314
315         // We use a fake renderer so we download correct pieces of the next file
316         if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
317       }
318
319       // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
320       this.addTorrentDelay = setTimeout(() => {
321         // We don't need the fake renderer anymore
322         this.destroyFakeRenderer()
323
324         const paused = this.player.paused()
325
326         this.flushVideoFile(previousVideoFile)
327
328         // Update progress bar (just for the UI), do not wait rendering
329         if (options.seek) this.player.currentTime(options.seek)
330
331         const renderVideoOptions = { autoplay: false, controls: true }
332         renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
333           this.renderer = renderer
334
335           if (err) return this.fallbackToHttp(options, done)
336
337           return this.tryToPlay(err => {
338             if (err) return done(err)
339
340             if (options.seek) this.seek(options.seek)
341             if (options.forcePlay === false && paused === true) this.player.pause()
342
343             return done()
344           })
345         })
346       }, options.delay || 0)
347     })
348
349     this.torrent.on('error', (err: any) => console.error(err))
350
351     this.torrent.on('warning', (err: any) => {
352       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
353       if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
354
355       // Users don't care about issues with WebRTC, but developers do so log it in the console
356       if (err.message.indexOf('Ice connection failed') !== -1) {
357         console.log(err)
358         return
359       }
360
361       // Magnet hash is not up to date with the torrent file, add directly the torrent file
362       if (err.message.indexOf('incorrect info hash') !== -1) {
363         console.error('Incorrect info hash detected, falling back to torrent file.')
364         const newOptions = { forcePlay: true, seek: options.seek }
365         return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
366       }
367
368       // Remote instance is down
369       if (err.message.indexOf('from xs param') !== -1) {
370         this.handleError(err)
371       }
372
373       console.warn(err)
374     })
375   }
376
377   private tryToPlay (done?: (err?: Error) => void) {
378     if (!done) done = function () { /* empty */ }
379
380     const playPromise = this.player.play()
381     if (playPromise !== undefined) {
382       return playPromise.then(done)
383                         .catch((err: Error) => {
384                           if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
385                             return
386                           }
387
388                           console.error(err)
389                           this.player.pause()
390                           this.player.posterImage.show()
391                           this.player.removeClass('vjs-has-autoplay')
392                           this.player.removeClass('vjs-has-big-play-button-clicked')
393
394                           return done()
395                         })
396     }
397
398     return done()
399   }
400
401   private seek (time: number) {
402     this.player.currentTime(time)
403     this.player.handleTechSeeked_()
404   }
405
406   private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
407     if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
408     if (this.videoFiles.length === 1) return this.videoFiles[0]
409
410     // Don't change the torrent is the play was ended
411     if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
412
413     if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
414
415     // Limit resolution according to player height
416     const playerHeight = this.playerElement.offsetHeight as number
417
418     // We take the first resolution just above the player height
419     // Example: player height is 530px, we want the 720p file instead of 480p
420     let maxResolution = this.videoFiles[0].resolution.id
421     for (let i = this.videoFiles.length - 1; i >= 0; i--) {
422       const resolutionId = this.videoFiles[i].resolution.id
423       if (resolutionId >= playerHeight) {
424         maxResolution = resolutionId
425         break
426       }
427     }
428
429     // Filter videos we can play according to our screen resolution and bandwidth
430     const filteredFiles = this.videoFiles
431                               .filter(f => f.resolution.id <= maxResolution)
432                               .filter(f => {
433                                 const fileBitrate = (f.size / this.videoDuration)
434                                 let threshold = fileBitrate
435
436                                 // If this is for a higher resolution or an initial load: add a margin
437                                 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
438                                   threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
439                                 }
440
441                                 return averageDownloadSpeed > threshold
442                               })
443
444     // If the download speed is too bad, return the lowest resolution we have
445     if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
446
447     return videoFileMaxByResolution(filteredFiles)
448   }
449
450   private getAndSaveActualDownloadSpeed () {
451     const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
452     const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
453     if (lastDownloadSpeeds.length === 0) return -1
454
455     const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
456     const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
457
458     // Save the average bandwidth for future use
459     saveAverageBandwidth(averageBandwidth)
460
461     return averageBandwidth
462   }
463
464   private initializePlayer () {
465     if (isMobile()) this.player.addClass('vjs-is-mobile')
466
467     this.initSmoothProgressBar()
468
469     this.initCaptions()
470
471     this.alterInactivity()
472
473     if (this.autoplay === true) {
474       this.player.posterImage.hide()
475
476       return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
477     }
478
479     // Proxy first play
480     const oldPlay = this.player.play.bind(this.player)
481     this.player.play = () => {
482       this.player.addClass('vjs-has-big-play-button-clicked')
483       this.player.play = oldPlay
484
485       this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
486     }
487   }
488
489   private runAutoQualityScheduler () {
490     this.autoQualityInterval = setInterval(() => {
491
492       // Not initialized or in HTTP fallback
493       if (this.torrent === undefined || this.torrent === null) return
494       if (this.isAutoResolutionOn() === false) return
495       if (this.isAutoResolutionObservation === true) return
496
497       const file = this.getAppropriateFile()
498       let changeResolution = false
499       let changeResolutionDelay = 0
500
501       // Lower resolution
502       if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
503         console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
504         changeResolution = true
505       } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
506         console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
507         changeResolution = true
508         changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
509       }
510
511       if (changeResolution === true) {
512         this.updateResolution(file.resolution.id, changeResolutionDelay)
513
514         // Wait some seconds in observation of our new resolution
515         this.isAutoResolutionObservation = true
516
517         this.qualityObservationTimer = setTimeout(() => {
518           this.isAutoResolutionObservation = false
519         }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
520       }
521     }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
522   }
523
524   private isPlayerWaiting () {
525     return this.player && this.player.hasClass('vjs-waiting')
526   }
527
528   private runTorrentInfoScheduler () {
529     this.torrentInfoInterval = setInterval(() => {
530       // Not initialized yet
531       if (this.torrent === undefined) return
532
533       // Http fallback
534       if (this.torrent === null) return this.trigger('torrentInfo', false)
535
536       // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
537       if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
538
539       return this.trigger('torrentInfo', {
540         downloadSpeed: this.torrent.downloadSpeed,
541         numPeers: this.torrent.numPeers,
542         uploadSpeed: this.torrent.uploadSpeed,
543         downloaded: this.torrent.downloaded,
544         uploaded: this.torrent.uploaded
545       })
546     }, this.CONSTANTS.INFO_SCHEDULER)
547   }
548
549   private runViewAdd () {
550     this.clearVideoViewInterval()
551
552     // After 30 seconds (or 3/4 of the video), add a view to the video
553     let minSecondsToView = 30
554
555     if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
556
557     let secondsViewed = 0
558     this.videoViewInterval = setInterval(() => {
559       if (this.player && !this.player.paused()) {
560         secondsViewed += 1
561
562         if (secondsViewed > minSecondsToView) {
563           this.clearVideoViewInterval()
564
565           this.addViewToVideo().catch(err => console.error(err))
566         }
567       }
568     }, 1000)
569   }
570
571   private runUserWatchVideo (options: UserWatching) {
572     let lastCurrentTime = 0
573
574     this.userWatchingVideoInterval = setInterval(() => {
575       const currentTime = Math.floor(this.player.currentTime())
576
577       if (currentTime - lastCurrentTime >= 1) {
578         lastCurrentTime = currentTime
579
580         this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
581           .catch(err => console.error('Cannot notify user is watching.', err))
582       }
583     }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
584   }
585
586   private clearVideoViewInterval () {
587     if (this.videoViewInterval !== undefined) {
588       clearInterval(this.videoViewInterval)
589       this.videoViewInterval = undefined
590     }
591   }
592
593   private addViewToVideo () {
594     if (!this.videoViewUrl) return Promise.resolve(undefined)
595
596     return fetch(this.videoViewUrl, { method: 'POST' })
597   }
598
599   private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
600     const body = new URLSearchParams()
601     body.append('currentTime', currentTime.toString())
602
603     const headers = new Headers({ 'Authorization': authorizationHeader })
604
605     return fetch(url, { method: 'PUT', body, headers })
606   }
607
608   private fallbackToHttp (options: PlayOptions, done?: Function) {
609     const paused = this.player.paused()
610
611     this.disableAutoResolution(true)
612
613     this.flushVideoFile(this.currentVideoFile, true)
614     this.torrent = null
615
616     // Enable error display now this is our last fallback
617     this.player.one('error', () => this.enableErrorDisplay())
618
619     const httpUrl = this.currentVideoFile.fileUrl
620     this.player.src = this.savePlayerSrcFunction
621     this.player.src(httpUrl)
622
623     // We changed the source, so reinit captions
624     this.initCaptions()
625
626     return this.tryToPlay(err => {
627       if (err && done) return done(err)
628
629       if (options.seek) this.seek(options.seek)
630       if (options.forcePlay === false && paused === true) this.player.pause()
631
632       if (done) return done()
633     })
634   }
635
636   private handleError (err: Error | string) {
637     return this.player.trigger('customError', { err })
638   }
639
640   private enableErrorDisplay () {
641     this.player.addClass('vjs-error-display-enabled')
642   }
643
644   private disableErrorDisplay () {
645     this.player.removeClass('vjs-error-display-enabled')
646   }
647
648   private isIOS () {
649     return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
650   }
651
652   private alterInactivity () {
653     let saveInactivityTimeout: number
654
655     const disableInactivity = () => {
656       saveInactivityTimeout = this.player.options_.inactivityTimeout
657       this.player.options_.inactivityTimeout = 0
658     }
659     const enableInactivity = () => {
660       this.player.options_.inactivityTimeout = saveInactivityTimeout
661     }
662
663     const settingsDialog = this.player.children_.find((c: any) => c.name_ === 'SettingsDialog')
664
665     this.player.controlBar.on('mouseenter', () => disableInactivity())
666     settingsDialog.on('mouseenter', () => disableInactivity())
667     this.player.controlBar.on('mouseleave', () => enableInactivity())
668     settingsDialog.on('mouseleave', () => enableInactivity())
669   }
670
671   private pickAverageVideoFile () {
672     if (this.videoFiles.length === 1) return this.videoFiles[0]
673
674     return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
675   }
676
677   private stopTorrent (torrent: WebTorrent.Torrent) {
678     torrent.pause()
679     // Pause does not remove actual peers (in particular the webseed peer)
680     torrent.removePeer(torrent[ 'ws' ])
681   }
682
683   private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
684     this.destroyingFakeRenderer = false
685
686     const fakeVideoElem = document.createElement('video')
687     renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
688       this.fakeRenderer = renderer
689
690       // The renderer returns an error when we destroy it, so skip them
691       if (this.destroyingFakeRenderer === false && err) {
692         console.error('Cannot render new torrent in fake video element.', err)
693       }
694
695       // Load the future file at the correct time (in delay MS - 2 seconds)
696       fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
697     })
698   }
699
700   private destroyFakeRenderer () {
701     if (this.fakeRenderer) {
702       this.destroyingFakeRenderer = true
703
704       if (this.fakeRenderer.destroy) {
705         try {
706           this.fakeRenderer.destroy()
707         } catch (err) {
708           console.log('Cannot destroy correctly fake renderer.', err)
709         }
710       }
711       this.fakeRenderer = undefined
712     }
713   }
714
715   private initCaptions () {
716     for (const caption of this.videoCaptions) {
717       this.player.addRemoteTextTrack({
718         kind: 'captions',
719         label: caption.label,
720         language: caption.language,
721         id: caption.language,
722         src: caption.src,
723         default: this.defaultSubtitle === caption.language
724       }, false)
725     }
726
727     this.player.trigger('captionsChanged')
728   }
729
730   // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
731   private initSmoothProgressBar () {
732     const SeekBar = videojsUntyped.getComponent('SeekBar')
733     SeekBar.prototype.getPercent = function getPercent () {
734       // Allows for smooth scrubbing, when player can't keep up.
735       // const time = (this.player_.scrubbing()) ?
736       //   this.player_.getCache().currentTime :
737       //   this.player_.currentTime()
738       const time = this.player_.currentTime()
739       const percent = time / this.player_.duration()
740       return percent >= 1 ? 1 : percent
741     }
742     SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
743       let newTime = this.calculateDistance(event) * this.player_.duration()
744       if (newTime === this.player_.duration()) {
745         newTime = newTime - 0.1
746       }
747       this.player_.currentTime(newTime)
748       this.update()
749     }
750   }
751 }
752
753 videojs.registerPlugin('peertube', PeerTubePlugin)
754 export { PeerTubePlugin }