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