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