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, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
15 import minBy from 'lodash-es/minBy'
16 import maxBy from 'lodash-es/maxBy'
18 const webtorrent = new WebTorrent({
23 urls: 'stun:stun.stunprotocol.org'
26 urls: 'stun:stun.framasoft.org'
34 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
35 class PeerTubePlugin extends Plugin {
36 private readonly playerElement: HTMLVideoElement
38 private readonly autoplay: boolean = false
39 private readonly startTime: number = 0
40 private readonly savePlayerSrcFunction: Function
41 private readonly videoFiles: VideoFile[]
42 private readonly videoViewUrl: string
43 private readonly videoDuration: number
44 private readonly CONSTANTS = {
45 INFO_SCHEDULER: 1000, // Don't change this
46 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
47 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
48 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
49 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
50 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
54 private currentVideoFile: VideoFile
55 private torrent: WebTorrent.Torrent
56 private autoResolution = true
57 private isAutoResolutionObservation = false
59 private videoViewInterval
60 private torrentInfoInterval
61 private autoQualityInterval
62 private addTorrentDelay
63 private qualityObservationTimer
64 private runAutoQualitySchedulerTimer
66 private downloadSpeeds: number[] = []
68 constructor (player: videojs.Player, options: PeertubePluginOptions) {
69 super(player, options)
71 this.autoplay = options.autoplay
73 this.startTime = options.startTime
74 this.videoFiles = options.videoFiles
75 this.videoViewUrl = options.videoViewUrl
76 this.videoDuration = options.videoDuration
78 this.savePlayerSrcFunction = this.player.src
79 // Hack to "simulate" src link in video.js >= 6
80 // Without this, we can't play the video after pausing it
81 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
82 this.player.src = () => true
84 this.playerElement = options.playerElement
86 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
88 this.player.ready(() => {
89 const volume = getStoredVolume()
90 if (volume !== undefined) this.player.volume(volume)
91 const muted = getStoredMute()
92 if (muted !== undefined) this.player.muted(muted)
94 this.initializePlayer()
95 this.runTorrentInfoScheduler()
98 this.player.one('play', () => {
99 // Don't run immediately scheduler, wait some seconds the TCP connections are made
100 this.runAutoQualitySchedulerTimer = setTimeout(() => {
101 this.runAutoQualityScheduler()
102 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
106 this.player.on('volumechange', () => {
107 saveVolumeInStore(this.player.volume())
108 saveMuteInStore(this.player.muted())
113 clearTimeout(this.addTorrentDelay)
114 clearTimeout(this.qualityObservationTimer)
115 clearTimeout(this.runAutoQualitySchedulerTimer)
117 clearInterval(this.videoViewInterval)
118 clearInterval(this.torrentInfoInterval)
119 clearInterval(this.autoQualityInterval)
121 // Don't need to destroy renderer, video player will be destroyed
122 this.flushVideoFile(this.currentVideoFile, false)
125 getCurrentResolutionId () {
126 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
129 getCurrentResolutionLabel () {
130 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
133 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
134 if (done === undefined) {
135 done = () => { /* empty */ }
138 // Automatically choose the adapted video file
139 if (videoFile === undefined) {
140 const savedAverageBandwidth = getAverageBandwidth()
141 videoFile = savedAverageBandwidth
142 ? this.getAppropriateFile(savedAverageBandwidth)
146 // Don't add the same video file once again
147 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
151 // Do not display error to user because we will have multiple fallback
152 this.disableErrorDisplay()
154 this.player.src = () => true
155 const oldPlaybackRate = this.player.playbackRate()
157 const previousVideoFile = this.currentVideoFile
158 this.currentVideoFile = videoFile
160 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
161 this.player.playbackRate(oldPlaybackRate)
165 this.trigger('videoFileUpdate')
168 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
169 console.log('Adding ' + magnetOrTorrentUrl + '.')
171 const oldTorrent = this.torrent
172 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
173 console.log('Added ' + magnetOrTorrentUrl + '.')
175 // Pause the old torrent
178 // Pause does not remove actual peers (in particular the webseed peer)
179 oldTorrent.removePeer(oldTorrent['ws'])
182 this.addTorrentDelay = setTimeout(() => {
183 this.flushVideoFile(previousVideoFile)
185 const options = { autoplay: true, controls: true }
186 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
187 this.renderer = renderer
189 if (err) return this.fallbackToHttp(done)
191 if (!this.player.paused()) return this.tryToPlay(done)
198 this.torrent.on('error', err => this.handleError(err))
200 this.torrent.on('warning', (err: any) => {
201 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
202 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
204 // Users don't care about issues with WebRTC, but developers do so log it in the console
205 if (err.message.indexOf('Ice connection failed') !== -1) {
210 // Magnet hash is not up to date with the torrent file, add directly the torrent file
211 if (err.message.indexOf('incorrect info hash') !== -1) {
212 console.error('Incorrect info hash detected, falling back to torrent file.')
213 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
216 return this.handleError(err)
220 updateResolution (resolutionId: number, delay = 0) {
221 // Remember player state
222 const currentTime = this.player.currentTime()
223 const isPaused = this.player.paused()
225 // Remove poster to have black background
226 this.playerElement.poster = ''
228 // Hide bigPlayButton
230 this.player.bigPlayButton.hide()
233 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
234 this.updateVideoFile(newVideoFile, delay, () => this.seek(currentTime))
237 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
238 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
239 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
241 webtorrent.remove(videoFile.magnetUri)
242 console.log('Removed ' + videoFile.magnetUri)
246 isAutoResolutionOn () {
247 return this.autoResolution
250 enableAutoResolution () {
251 this.autoResolution = true
252 this.trigger('autoResolutionUpdate')
255 disableAutoResolution () {
256 this.autoResolution = false
257 this.trigger('autoResolutionUpdate')
260 private tryToPlay (done?: Function) {
261 if (!done) done = function () { /* empty */ }
263 const playPromise = this.player.play()
264 if (playPromise !== undefined) {
265 return playPromise.then(done)
269 this.player.posterImage.show()
270 this.player.removeClass('vjs-has-autoplay')
279 private seek (time: number) {
280 this.player.currentTime(time)
281 this.player.handleTechSeeked_()
284 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
285 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
286 if (this.videoFiles.length === 1) return this.videoFiles[0]
287 if (this.torrent && this.torrent.progress === 1) return this.currentVideoFile
289 if (!averageDownloadSpeed) averageDownloadSpeed = this.getActualDownloadSpeed()
291 // Filter videos we can play according to our bandwidth
292 const filteredFiles = this.videoFiles.filter(f => {
293 const fileBitrate = (f.size / this.videoDuration)
294 let threshold = fileBitrate
296 // If this is for a higher resolution or an initial load: add a margin
297 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
298 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
301 return averageDownloadSpeed > threshold
304 // If the download speed is too bad, return the lowest resolution we have
305 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
307 return maxBy(filteredFiles, 'resolution.id')
310 private getActualDownloadSpeed () {
311 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
312 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
313 if (lastDownloadSpeeds.length === 0) return -1
315 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
316 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
318 // Save the average bandwidth for future use
319 saveAverageBandwidth(averageBandwidth)
321 return averageBandwidth
324 private initializePlayer () {
325 this.initSmoothProgressBar()
327 this.alterInactivity()
329 if (this.autoplay === true) {
330 this.player.posterImage.hide()
332 this.updateVideoFile(undefined, 0, () => {
333 this.seek(this.startTime)
338 const oldPlay = this.player.play.bind(this.player)
339 this.player.play = () => {
340 this.player.addClass('vjs-has-big-play-button-clicked')
341 this.player.play = oldPlay
343 this.updateVideoFile(undefined, 0, () => this.seek(this.startTime))
348 private runAutoQualityScheduler () {
349 this.autoQualityInterval = setInterval(() => {
351 // Not initialized or in HTTP fallback
352 if (this.torrent === undefined || this.torrent === null) return
353 if (this.isAutoResolutionOn() === false) return
354 if (this.isAutoResolutionObservation === true) return
356 const file = this.getAppropriateFile()
357 let changeResolution = false
358 let changeResolutionDelay = 0
361 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
362 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
363 changeResolution = true
364 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
365 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
366 changeResolution = true
367 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
370 if (changeResolution === true) {
371 this.updateResolution(file.resolution.id, changeResolutionDelay)
373 // Wait some seconds in observation of our new resolution
374 this.isAutoResolutionObservation = true
376 this.qualityObservationTimer = setTimeout(() => {
377 this.isAutoResolutionObservation = false
378 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
380 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
383 private isPlayerWaiting () {
384 return this.player && this.player.hasClass('vjs-waiting')
387 private runTorrentInfoScheduler () {
388 this.torrentInfoInterval = setInterval(() => {
389 // Not initialized yet
390 if (this.torrent === undefined) return
393 if (this.torrent === null) return this.trigger('torrentInfo', false)
395 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
396 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
398 return this.trigger('torrentInfo', {
399 downloadSpeed: this.torrent.downloadSpeed,
400 numPeers: this.torrent.numPeers,
401 uploadSpeed: this.torrent.uploadSpeed
403 }, this.CONSTANTS.INFO_SCHEDULER)
406 private runViewAdd () {
407 this.clearVideoViewInterval()
409 // After 30 seconds (or 3/4 of the video), add a view to the video
410 let minSecondsToView = 30
412 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
414 let secondsViewed = 0
415 this.videoViewInterval = setInterval(() => {
416 if (this.player && !this.player.paused()) {
419 if (secondsViewed > minSecondsToView) {
420 this.clearVideoViewInterval()
422 this.addViewToVideo().catch(err => console.error(err))
428 private clearVideoViewInterval () {
429 if (this.videoViewInterval !== undefined) {
430 clearInterval(this.videoViewInterval)
431 this.videoViewInterval = undefined
435 private addViewToVideo () {
436 return fetch(this.videoViewUrl, { method: 'POST' })
439 private fallbackToHttp (done: Function) {
440 this.flushVideoFile(this.currentVideoFile, true)
443 // Enable error display now this is our last fallback
444 this.player.one('error', () => this.enableErrorDisplay())
446 const httpUrl = this.currentVideoFile.fileUrl
447 this.player.src = this.savePlayerSrcFunction
448 this.player.src(httpUrl)
454 private handleError (err: Error | string) {
455 return this.player.trigger('customError', { err })
458 private enableErrorDisplay () {
459 this.player.addClass('vjs-error-display-enabled')
462 private disableErrorDisplay () {
463 this.player.removeClass('vjs-error-display-enabled')
466 private alterInactivity () {
467 let saveInactivityTimeout: number
469 const disableInactivity = () => {
470 saveInactivityTimeout = this.player.options_.inactivityTimeout
471 this.player.options_.inactivityTimeout = 0
473 const enableInactivity = () => {
474 this.player.options_.inactivityTimeout = saveInactivityTimeout
477 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
479 this.player.controlBar.on('mouseenter', () => disableInactivity())
480 settingsDialog.on('mouseenter', () => disableInactivity())
481 this.player.controlBar.on('mouseleave', () => enableInactivity())
482 settingsDialog.on('mouseleave', () => enableInactivity())
485 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
486 private initSmoothProgressBar () {
487 const SeekBar = videojsUntyped.getComponent('SeekBar')
488 SeekBar.prototype.getPercent = function getPercent () {
489 // Allows for smooth scrubbing, when player can't keep up.
490 // const time = (this.player_.scrubbing()) ?
491 // this.player_.getCache().currentTime :
492 // this.player_.currentTime()
493 const time = this.player_.currentTime()
494 const percent = time / this.player_.duration()
495 return percent >= 1 ? 1 : percent
497 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
498 let newTime = this.calculateDistance(event) * this.player_.duration()
499 if (newTime === this.player_.duration()) {
500 newTime = newTime - 0.1
502 this.player_.currentTime(newTime)
508 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
509 export { PeerTubePlugin }