1 import * as videojs from '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 import * as CacheChunkStore from 'cache-chunk-store'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
11 getAverageBandwidthInStore,
17 } from './peertube-player-local-storage'
19 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
20 class PeerTubePlugin extends Plugin {
21 private readonly playerElement: HTMLVideoElement
23 private readonly autoplay: boolean = false
24 private readonly startTime: number = 0
25 private readonly savePlayerSrcFunction: Function
26 private readonly videoFiles: VideoFile[]
27 private readonly videoViewUrl: string
28 private readonly videoDuration: number
29 private readonly CONSTANTS = {
30 INFO_SCHEDULER: 1000, // Don't change this
31 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
32 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
33 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
34 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
35 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5, // Last 5 seconds to build average bandwidth
36 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
39 private readonly webtorrent = new WebTorrent({
44 urls: 'stun:stun.stunprotocol.org'
47 urls: 'stun:stun.framasoft.org'
56 private currentVideoFile: VideoFile
57 private torrent: WebTorrent.Torrent
58 private videoCaptions: VideoJSCaption[]
62 private destoyingFakeRenderer = false
64 private autoResolution = true
65 private forbidAutoResolution = false
66 private isAutoResolutionObservation = false
68 private videoViewInterval
69 private torrentInfoInterval
70 private autoQualityInterval
71 private userWatchingVideoInterval
72 private addTorrentDelay
73 private qualityObservationTimer
74 private runAutoQualitySchedulerTimer
76 private downloadSpeeds: number[] = []
78 constructor (player: videojs.Player, options: PeertubePluginOptions) {
79 super(player, options)
81 // Disable auto play on iOS
82 this.autoplay = options.autoplay && this.isIOS() === false
84 this.startTime = timeToInt(options.startTime)
85 this.videoFiles = options.videoFiles
86 this.videoViewUrl = options.videoViewUrl
87 this.videoDuration = options.videoDuration
88 this.videoCaptions = options.videoCaptions
90 this.savePlayerSrcFunction = this.player.src
91 this.playerElement = options.playerElement
93 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
95 this.player.ready(() => {
96 const volume = getStoredVolume()
97 if (volume !== undefined) this.player.volume(volume)
98 const muted = getStoredMute()
99 if (muted !== undefined) this.player.muted(muted)
101 this.initializePlayer()
102 this.runTorrentInfoScheduler()
105 if (options.userWatching) this.runUserWatchVideo(options.userWatching)
107 this.player.one('play', () => {
108 // Don't run immediately scheduler, wait some seconds the TCP connections are made
109 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
113 this.player.on('volumechange', () => {
114 saveVolumeInStore(this.player.volume())
115 saveMuteInStore(this.player.muted())
120 clearTimeout(this.addTorrentDelay)
121 clearTimeout(this.qualityObservationTimer)
122 clearTimeout(this.runAutoQualitySchedulerTimer)
124 clearInterval(this.videoViewInterval)
125 clearInterval(this.torrentInfoInterval)
126 clearInterval(this.autoQualityInterval)
128 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
130 // Don't need to destroy renderer, video player will be destroyed
131 this.flushVideoFile(this.currentVideoFile, false)
133 this.destroyFakeRenderer()
136 getCurrentResolutionId () {
137 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
140 getCurrentResolutionLabel () {
141 if (!this.currentVideoFile) return ''
143 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
144 return this.currentVideoFile.resolution.label + fps
148 videoFile?: VideoFile,
154 done: () => void = () => { /* empty */ }
156 // Automatically choose the adapted video file
157 if (videoFile === undefined) {
158 const savedAverageBandwidth = getAverageBandwidthInStore()
159 videoFile = savedAverageBandwidth
160 ? this.getAppropriateFile(savedAverageBandwidth)
161 : this.pickAverageVideoFile()
164 // Don't add the same video file once again
165 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
169 // Do not display error to user because we will have multiple fallback
170 this.disableErrorDisplay()
172 // Hack to "simulate" src link in video.js >= 6
173 // Without this, we can't play the video after pausing it
174 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
175 this.player.src = () => true
176 const oldPlaybackRate = this.player.playbackRate()
178 const previousVideoFile = this.currentVideoFile
179 this.currentVideoFile = videoFile
181 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
182 this.player.playbackRate(oldPlaybackRate)
186 this.trigger('videoFileUpdate')
189 updateResolution (resolutionId: number, delay = 0) {
190 // Remember player state
191 const currentTime = this.player.currentTime()
192 const isPaused = this.player.paused()
194 // Remove poster to have black background
195 this.playerElement.poster = ''
197 // Hide bigPlayButton
199 this.player.bigPlayButton.hide()
202 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
206 seek: currentTime + (delay / 1000)
208 this.updateVideoFile(newVideoFile, options)
211 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
212 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
213 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
215 this.webtorrent.remove(videoFile.magnetUri)
216 console.log('Removed ' + videoFile.magnetUri)
220 isAutoResolutionOn () {
221 return this.autoResolution
224 enableAutoResolution () {
225 this.autoResolution = true
226 this.trigger('autoResolutionUpdate')
229 disableAutoResolution (forbid = false) {
230 if (forbid === true) this.forbidAutoResolution = true
232 this.autoResolution = false
233 this.trigger('autoResolutionUpdate')
236 isAutoResolutionForbidden () {
237 return this.forbidAutoResolution === true
240 getCurrentVideoFile () {
241 return this.currentVideoFile
249 magnetOrTorrentUrl: string,
250 previousVideoFile: VideoFile,
258 console.log('Adding ' + magnetOrTorrentUrl + '.')
260 const oldTorrent = this.torrent
261 const torrentOptions = {
262 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
267 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
268 console.log('Added ' + magnetOrTorrentUrl + '.')
271 // Pause the old torrent
272 this.stopTorrent(oldTorrent)
274 // We use a fake renderer so we download correct pieces of the next file
275 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
278 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
279 this.addTorrentDelay = setTimeout(() => {
280 // We don't need the fake renderer anymore
281 this.destroyFakeRenderer()
283 const paused = this.player.paused()
285 this.flushVideoFile(previousVideoFile)
287 const renderVideoOptions = { autoplay: false, controls: true }
288 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
289 this.renderer = renderer
291 if (err) return this.fallbackToHttp(done)
293 return this.tryToPlay(err => {
294 if (err) return done(err)
296 if (options.seek) this.seek(options.seek)
297 if (options.forcePlay === false && paused === true) this.player.pause()
302 }, options.delay || 0)
305 this.torrent.on('error', err => console.error(err))
307 this.torrent.on('warning', (err: any) => {
308 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
309 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
311 // Users don't care about issues with WebRTC, but developers do so log it in the console
312 if (err.message.indexOf('Ice connection failed') !== -1) {
317 // Magnet hash is not up to date with the torrent file, add directly the torrent file
318 if (err.message.indexOf('incorrect info hash') !== -1) {
319 console.error('Incorrect info hash detected, falling back to torrent file.')
320 const newOptions = { forcePlay: true, seek: options.seek }
321 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
324 // Remote instance is down
325 if (err.message.indexOf('from xs param') !== -1) {
326 this.handleError(err)
333 private tryToPlay (done?: Function) {
334 if (!done) done = function () { /* empty */ }
336 const playPromise = this.player.play()
337 if (playPromise !== undefined) {
338 return playPromise.then(done)
340 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
346 this.player.posterImage.show()
347 this.player.removeClass('vjs-has-autoplay')
348 this.player.removeClass('vjs-has-big-play-button-clicked')
357 private seek (time: number) {
358 this.player.currentTime(time)
359 this.player.handleTechSeeked_()
362 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
363 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
364 if (this.videoFiles.length === 1) return this.videoFiles[0]
366 // Don't change the torrent is the play was ended
367 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
369 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
371 // Limit resolution according to player height
372 const playerHeight = this.playerElement.offsetHeight as number
374 // We take the first resolution just above the player height
375 // Example: player height is 530px, we want the 720p file instead of 480p
376 let maxResolution = this.videoFiles[0].resolution.id
377 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
378 const resolutionId = this.videoFiles[i].resolution.id
379 if (resolutionId >= playerHeight) {
380 maxResolution = resolutionId
385 // Filter videos we can play according to our screen resolution and bandwidth
386 const filteredFiles = this.videoFiles
387 .filter(f => f.resolution.id <= maxResolution)
389 const fileBitrate = (f.size / this.videoDuration)
390 let threshold = fileBitrate
392 // If this is for a higher resolution or an initial load: add a margin
393 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
394 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
397 return averageDownloadSpeed > threshold
400 // If the download speed is too bad, return the lowest resolution we have
401 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
403 return videoFileMaxByResolution(filteredFiles)
406 private getAndSaveActualDownloadSpeed () {
407 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
408 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
409 if (lastDownloadSpeeds.length === 0) return -1
411 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
412 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
414 // Save the average bandwidth for future use
415 saveAverageBandwidth(averageBandwidth)
417 return averageBandwidth
420 private initializePlayer () {
421 if (isMobile()) this.player.addClass('vjs-is-mobile')
423 this.initSmoothProgressBar()
427 this.alterInactivity()
429 if (this.autoplay === true) {
430 this.player.posterImage.hide()
432 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
435 // Don't try on iOS that does not support MediaSource
437 this.currentVideoFile = this.pickAverageVideoFile()
438 return this.fallbackToHttp(undefined, false)
442 const oldPlay = this.player.play.bind(this.player)
443 this.player.play = () => {
444 this.player.addClass('vjs-has-big-play-button-clicked')
445 this.player.play = oldPlay
447 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
451 private runAutoQualityScheduler () {
452 this.autoQualityInterval = setInterval(() => {
454 // Not initialized or in HTTP fallback
455 if (this.torrent === undefined || this.torrent === null) return
456 if (this.isAutoResolutionOn() === false) return
457 if (this.isAutoResolutionObservation === true) return
459 const file = this.getAppropriateFile()
460 let changeResolution = false
461 let changeResolutionDelay = 0
464 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
465 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
466 changeResolution = true
467 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
468 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
469 changeResolution = true
470 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
473 if (changeResolution === true) {
474 this.updateResolution(file.resolution.id, changeResolutionDelay)
476 // Wait some seconds in observation of our new resolution
477 this.isAutoResolutionObservation = true
479 this.qualityObservationTimer = setTimeout(() => {
480 this.isAutoResolutionObservation = false
481 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
483 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
486 private isPlayerWaiting () {
487 return this.player && this.player.hasClass('vjs-waiting')
490 private runTorrentInfoScheduler () {
491 this.torrentInfoInterval = setInterval(() => {
492 // Not initialized yet
493 if (this.torrent === undefined) return
496 if (this.torrent === null) return this.trigger('torrentInfo', false)
498 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
499 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
501 return this.trigger('torrentInfo', {
502 downloadSpeed: this.torrent.downloadSpeed,
503 numPeers: this.torrent.numPeers,
504 uploadSpeed: this.torrent.uploadSpeed,
505 downloaded: this.torrent.downloaded,
506 uploaded: this.torrent.uploaded
508 }, this.CONSTANTS.INFO_SCHEDULER)
511 private runViewAdd () {
512 this.clearVideoViewInterval()
514 // After 30 seconds (or 3/4 of the video), add a view to the video
515 let minSecondsToView = 30
517 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
519 let secondsViewed = 0
520 this.videoViewInterval = setInterval(() => {
521 if (this.player && !this.player.paused()) {
524 if (secondsViewed > minSecondsToView) {
525 this.clearVideoViewInterval()
527 this.addViewToVideo().catch(err => console.error(err))
533 private runUserWatchVideo (options: UserWatching) {
534 let lastCurrentTime = 0
536 this.userWatchingVideoInterval = setInterval(() => {
537 const currentTime = Math.floor(this.player.currentTime())
539 if (currentTime - lastCurrentTime >= 1) {
540 lastCurrentTime = currentTime
542 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
543 .catch(err => console.error('Cannot notify user is watching.', err))
545 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
548 private clearVideoViewInterval () {
549 if (this.videoViewInterval !== undefined) {
550 clearInterval(this.videoViewInterval)
551 this.videoViewInterval = undefined
555 private addViewToVideo () {
556 if (!this.videoViewUrl) return Promise.resolve(undefined)
558 return fetch(this.videoViewUrl, { method: 'POST' })
561 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
562 const body = new URLSearchParams()
563 body.append('currentTime', currentTime.toString())
565 const headers = new Headers({ 'Authorization': authorizationHeader })
567 return fetch(url, { method: 'PUT', body, headers })
570 private fallbackToHttp (done?: Function, play = true) {
571 this.disableAutoResolution(true)
573 this.flushVideoFile(this.currentVideoFile, true)
576 // Enable error display now this is our last fallback
577 this.player.one('error', () => this.enableErrorDisplay())
579 const httpUrl = this.currentVideoFile.fileUrl
580 this.player.src = this.savePlayerSrcFunction
581 this.player.src(httpUrl)
582 if (play) this.tryToPlay()
584 if (done) return done()
587 private handleError (err: Error | string) {
588 return this.player.trigger('customError', { err })
591 private enableErrorDisplay () {
592 this.player.addClass('vjs-error-display-enabled')
595 private disableErrorDisplay () {
596 this.player.removeClass('vjs-error-display-enabled')
600 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
603 private alterInactivity () {
604 let saveInactivityTimeout: number
606 const disableInactivity = () => {
607 saveInactivityTimeout = this.player.options_.inactivityTimeout
608 this.player.options_.inactivityTimeout = 0
610 const enableInactivity = () => {
611 this.player.options_.inactivityTimeout = saveInactivityTimeout
614 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
616 this.player.controlBar.on('mouseenter', () => disableInactivity())
617 settingsDialog.on('mouseenter', () => disableInactivity())
618 this.player.controlBar.on('mouseleave', () => enableInactivity())
619 settingsDialog.on('mouseleave', () => enableInactivity())
622 private pickAverageVideoFile () {
623 if (this.videoFiles.length === 1) return this.videoFiles[0]
625 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
628 private stopTorrent (torrent: WebTorrent.Torrent) {
630 // Pause does not remove actual peers (in particular the webseed peer)
631 torrent.removePeer(torrent[ 'ws' ])
634 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
635 this.destoyingFakeRenderer = false
637 const fakeVideoElem = document.createElement('video')
638 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
639 this.fakeRenderer = renderer
641 // The renderer returns an error when we destroy it, so skip them
642 if (this.destoyingFakeRenderer === false && err) {
643 console.error('Cannot render new torrent in fake video element.', err)
646 // Load the future file at the correct time (in delay MS - 2 seconds)
647 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
651 private destroyFakeRenderer () {
652 if (this.fakeRenderer) {
653 this.destoyingFakeRenderer = true
655 if (this.fakeRenderer.destroy) {
657 this.fakeRenderer.destroy()
659 console.log('Cannot destroy correctly fake renderer.', err)
662 this.fakeRenderer = undefined
666 private initCaptions () {
667 for (const caption of this.videoCaptions) {
668 this.player.addRemoteTextTrack({
670 label: caption.label,
671 language: caption.language,
672 id: caption.language,
678 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
679 private initSmoothProgressBar () {
680 const SeekBar = videojsUntyped.getComponent('SeekBar')
681 SeekBar.prototype.getPercent = function getPercent () {
682 // Allows for smooth scrubbing, when player can't keep up.
683 // const time = (this.player_.scrubbing()) ?
684 // this.player_.getCache().currentTime :
685 // this.player_.currentTime()
686 const time = this.player_.currentTime()
687 const percent = time / this.player_.duration()
688 return percent >= 1 ? 1 : percent
690 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
691 let newTime = this.calculateDistance(event) * this.player_.duration()
692 if (newTime === this.player_.duration()) {
693 newTime = newTime - 0.1
695 this.player_.currentTime(newTime)
701 videojs.registerPlugin('peertube', PeerTubePlugin)
702 export { PeerTubePlugin }