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 // Fix canplay event on google chrome by disabling default videojs autoplay
72 this.autoplay = this.player.options_.autoplay
73 this.player.options_.autoplay = false
75 this.startTime = options.startTime
76 this.videoFiles = options.videoFiles
77 this.videoViewUrl = options.videoViewUrl
78 this.videoDuration = options.videoDuration
80 this.savePlayerSrcFunction = this.player.src
81 // Hack to "simulate" src link in video.js >= 6
82 // Without this, we can't play the video after pausing it
83 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
84 this.player.src = () => true
86 this.playerElement = options.playerElement
88 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
90 this.player.ready(() => {
91 const volume = getStoredVolume()
92 if (volume !== undefined) this.player.volume(volume)
93 const muted = getStoredMute()
94 if (muted !== undefined) this.player.muted(muted)
96 this.initializePlayer()
97 this.runTorrentInfoScheduler()
100 this.player.one('play', () => {
101 // Don't run immediately scheduler, wait some seconds the TCP connections are made
102 this.runAutoQualitySchedulerTimer = setTimeout(() => {
103 this.runAutoQualityScheduler()
104 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
108 this.player.on('volumechange', () => {
109 saveVolumeInStore(this.player.volume())
110 saveMuteInStore(this.player.muted())
115 clearTimeout(this.addTorrentDelay)
116 clearTimeout(this.qualityObservationTimer)
117 clearTimeout(this.runAutoQualitySchedulerTimer)
119 clearInterval(this.videoViewInterval)
120 clearInterval(this.torrentInfoInterval)
121 clearInterval(this.autoQualityInterval)
123 // Don't need to destroy renderer, video player will be destroyed
124 this.flushVideoFile(this.currentVideoFile, false)
127 getCurrentResolutionId () {
128 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
131 getCurrentResolutionLabel () {
132 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
135 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
136 if (done === undefined) {
137 done = () => { /* empty */ }
140 // Automatically choose the adapted video file
141 if (videoFile === undefined) {
142 const savedAverageBandwidth = getAverageBandwidth()
143 videoFile = savedAverageBandwidth
144 ? this.getAppropriateFile(savedAverageBandwidth)
148 // Don't add the same video file once again
149 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
153 // Do not display error to user because we will have multiple fallback
154 this.disableErrorDisplay()
156 this.player.src = () => true
157 const oldPlaybackRate = this.player.playbackRate()
159 const previousVideoFile = this.currentVideoFile
160 this.currentVideoFile = videoFile
162 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
163 this.player.playbackRate(oldPlaybackRate)
167 this.trigger('videoFileUpdate')
170 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
171 console.log('Adding ' + magnetOrTorrentUrl + '.')
173 const oldTorrent = this.torrent
174 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
175 console.log('Added ' + magnetOrTorrentUrl + '.')
177 // Pause the old torrent
180 // Pause does not remove actual peers (in particular the webseed peer)
181 oldTorrent.removePeer(oldTorrent['ws'])
184 this.addTorrentDelay = setTimeout(() => {
185 this.flushVideoFile(previousVideoFile)
187 const options = { autoplay: true, controls: true }
188 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
189 this.renderer = renderer
191 if (err) return this.fallbackToHttp(done)
193 if (!this.player.paused()) {
194 const playPromise = this.player.play()
195 if (playPromise !== undefined) return playPromise.then(done)
205 this.torrent.on('error', err => this.handleError(err))
207 this.torrent.on('warning', (err: any) => {
208 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
209 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
211 // Users don't care about issues with WebRTC, but developers do so log it in the console
212 if (err.message.indexOf('Ice connection failed') !== -1) {
217 // Magnet hash is not up to date with the torrent file, add directly the torrent file
218 if (err.message.indexOf('incorrect info hash') !== -1) {
219 console.error('Incorrect info hash detected, falling back to torrent file.')
220 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
223 return this.handleError(err)
227 updateResolution (resolutionId: number, delay = 0) {
228 // Remember player state
229 const currentTime = this.player.currentTime()
230 const isPaused = this.player.paused()
232 // Remove poster to have black background
233 this.playerElement.poster = ''
235 // Hide bigPlayButton
237 this.player.bigPlayButton.hide()
240 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
241 this.updateVideoFile(newVideoFile, delay, () => this.seek(currentTime))
244 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
245 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
246 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
248 webtorrent.remove(videoFile.magnetUri)
249 console.log('Removed ' + videoFile.magnetUri)
253 isAutoResolutionOn () {
254 return this.autoResolution
257 enableAutoResolution () {
258 this.autoResolution = true
259 this.trigger('autoResolutionUpdate')
262 disableAutoResolution () {
263 this.autoResolution = false
264 this.trigger('autoResolutionUpdate')
267 private seek (time: number) {
268 this.player.currentTime(time)
269 this.player.handleTechSeeked_()
272 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
273 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
274 if (this.videoFiles.length === 1) return this.videoFiles[0]
275 if (this.torrent && this.torrent.progress === 1) return this.currentVideoFile
277 if (!averageDownloadSpeed) averageDownloadSpeed = this.getActualDownloadSpeed()
279 // Filter videos we can play according to our bandwidth
280 const filteredFiles = this.videoFiles.filter(f => {
281 const fileBitrate = (f.size / this.videoDuration)
282 let threshold = fileBitrate
284 // If this is for a higher resolution or an initial load: add a margin
285 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
286 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
289 return averageDownloadSpeed > threshold
292 // If the download speed is too bad, return the lowest resolution we have
293 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
295 return maxBy(filteredFiles, 'resolution.id')
298 private getActualDownloadSpeed () {
299 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
300 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
301 if (lastDownloadSpeeds.length === 0) return -1
303 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
304 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
306 // Save the average bandwidth for future use
307 saveAverageBandwidth(averageBandwidth)
309 return averageBandwidth
312 private initializePlayer () {
313 this.initSmoothProgressBar()
315 this.alterInactivity()
317 if (this.autoplay === true) {
318 this.player.posterImage.hide()
320 this.updateVideoFile(undefined, 0, () => this.seek(this.startTime))
323 const oldPlay = this.player.play.bind(this.player)
324 this.player.play = () => {
325 this.player.addClass('vjs-has-big-play-button-clicked')
326 this.player.play = oldPlay
328 this.updateVideoFile(undefined, 0, () => this.seek(this.startTime))
333 private runAutoQualityScheduler () {
334 this.autoQualityInterval = setInterval(() => {
336 // Not initialized or in HTTP fallback
337 if (this.torrent === undefined || this.torrent === null) return
338 if (this.isAutoResolutionOn() === false) return
339 if (this.isAutoResolutionObservation === true) return
341 const file = this.getAppropriateFile()
342 let changeResolution = false
343 let changeResolutionDelay = 0
346 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
347 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
348 changeResolution = true
349 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
350 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
351 changeResolution = true
352 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
355 if (changeResolution === true) {
356 this.updateResolution(file.resolution.id, changeResolutionDelay)
358 // Wait some seconds in observation of our new resolution
359 this.isAutoResolutionObservation = true
361 this.qualityObservationTimer = setTimeout(() => {
362 this.isAutoResolutionObservation = false
363 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
365 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
368 private isPlayerWaiting () {
369 return this.player && this.player.hasClass('vjs-waiting')
372 private runTorrentInfoScheduler () {
373 this.torrentInfoInterval = setInterval(() => {
374 // Not initialized yet
375 if (this.torrent === undefined) return
378 if (this.torrent === null) return this.trigger('torrentInfo', false)
380 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
381 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
383 return this.trigger('torrentInfo', {
384 downloadSpeed: this.torrent.downloadSpeed,
385 numPeers: this.torrent.numPeers,
386 uploadSpeed: this.torrent.uploadSpeed
388 }, this.CONSTANTS.INFO_SCHEDULER)
391 private runViewAdd () {
392 this.clearVideoViewInterval()
394 // After 30 seconds (or 3/4 of the video), add a view to the video
395 let minSecondsToView = 30
397 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
399 let secondsViewed = 0
400 this.videoViewInterval = setInterval(() => {
401 if (this.player && !this.player.paused()) {
404 if (secondsViewed > minSecondsToView) {
405 this.clearVideoViewInterval()
407 this.addViewToVideo().catch(err => console.error(err))
413 private clearVideoViewInterval () {
414 if (this.videoViewInterval !== undefined) {
415 clearInterval(this.videoViewInterval)
416 this.videoViewInterval = undefined
420 private addViewToVideo () {
421 return fetch(this.videoViewUrl, { method: 'POST' })
424 private fallbackToHttp (done: Function) {
425 this.flushVideoFile(this.currentVideoFile, true)
428 // Enable error display now this is our last fallback
429 this.player.one('error', () => this.enableErrorDisplay())
431 const httpUrl = this.currentVideoFile.fileUrl
432 this.player.src = this.savePlayerSrcFunction
433 this.player.src(httpUrl)
439 private handleError (err: Error | string) {
440 return this.player.trigger('customError', { err })
443 private enableErrorDisplay () {
444 this.player.addClass('vjs-error-display-enabled')
447 private disableErrorDisplay () {
448 this.player.removeClass('vjs-error-display-enabled')
451 private alterInactivity () {
452 let saveInactivityTimeout: number
454 const disableInactivity = () => {
455 saveInactivityTimeout = this.player.options_.inactivityTimeout
456 this.player.options_.inactivityTimeout = 0
458 const enableInactivity = () => {
459 this.player.options_.inactivityTimeout = saveInactivityTimeout
462 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
464 this.player.controlBar.on('mouseenter', () => disableInactivity())
465 settingsDialog.on('mouseenter', () => disableInactivity())
466 this.player.controlBar.on('mouseleave', () => enableInactivity())
467 settingsDialog.on('mouseleave', () => enableInactivity())
470 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
471 private initSmoothProgressBar () {
472 const SeekBar = videojsUntyped.getComponent('SeekBar')
473 SeekBar.prototype.getPercent = function getPercent () {
474 // Allows for smooth scrubbing, when player can't keep up.
475 // const time = (this.player_.scrubbing()) ?
476 // this.player_.getCache().currentTime :
477 // this.player_.currentTime()
478 const time = this.player_.currentTime()
479 const percent = time / this.player_.duration()
480 return percent >= 1 ? 1 : percent
482 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
483 let newTime = this.calculateDistance(event) * this.player_.duration()
484 if (newTime === this.player_.duration()) {
485 newTime = newTime - 0.1
487 this.player_.currentTime(newTime)
493 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
494 export { PeerTubePlugin }