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