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 savePlayerSrcFunction: Function
40 private readonly videoFiles: VideoFile[]
41 private readonly videoViewUrl: string
42 private readonly videoDuration: number
43 private readonly CONSTANTS = {
44 INFO_SCHEDULER: 1000, // Don't change this
45 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
46 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
47 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
48 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
49 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
53 private currentVideoFile: VideoFile
54 private torrent: WebTorrent.Torrent
55 private autoResolution = true
56 private isAutoResolutionObservation = false
58 private videoViewInterval
59 private torrentInfoInterval
60 private autoQualityInterval
61 private addTorrentDelay
62 private qualityObservationTimer
63 private runAutoQualitySchedulerTimer
65 private downloadSpeeds: number[] = []
67 constructor (player: videojs.Player, options: PeertubePluginOptions) {
68 super(player, options)
70 // Fix canplay event on google chrome by disabling default videojs autoplay
71 this.autoplay = this.player.options_.autoplay
72 this.player.options_.autoplay = false
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 this.player.ready(() => {
87 const volume = getStoredVolume()
88 if (volume !== undefined) this.player.volume(volume)
89 const muted = getStoredMute()
90 if (muted !== undefined) this.player.muted(muted)
92 this.initializePlayer()
93 this.runTorrentInfoScheduler()
96 this.player.one('play', () => {
97 // Don't run immediately scheduler, wait some seconds the TCP connections are maid
98 this.runAutoQualitySchedulerTimer = setTimeout(() => {
99 this.runAutoQualityScheduler()
100 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
104 this.player.on('volumechange', () => {
105 saveVolumeInStore(this.player.volume())
106 saveMuteInStore(this.player.muted())
111 clearTimeout(this.addTorrentDelay)
112 clearTimeout(this.qualityObservationTimer)
113 clearTimeout(this.runAutoQualitySchedulerTimer)
115 clearInterval(this.videoViewInterval)
116 clearInterval(this.torrentInfoInterval)
117 clearInterval(this.autoQualityInterval)
119 // Don't need to destroy renderer, video player will be destroyed
120 this.flushVideoFile(this.currentVideoFile, false)
123 getCurrentResolutionId () {
124 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
127 getCurrentResolutionLabel () {
128 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
131 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
132 if (done === undefined) {
133 done = () => { /* empty */ }
136 // Automatically choose the adapted video file
137 if (videoFile === undefined) {
138 const savedAverageBandwidth = getAverageBandwidth()
139 videoFile = savedAverageBandwidth
140 ? this.getAppropriateFile(savedAverageBandwidth)
144 // Don't add the same video file once again
145 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
149 // Do not display error to user because we will have multiple fallback
150 this.disableErrorDisplay()
152 this.player.src = () => true
153 const oldPlaybackRate = this.player.playbackRate()
155 const previousVideoFile = this.currentVideoFile
156 this.currentVideoFile = videoFile
158 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
159 this.player.playbackRate(oldPlaybackRate)
163 this.trigger('videoFileUpdate')
166 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
167 console.log('Adding ' + magnetOrTorrentUrl + '.')
169 const oldTorrent = this.torrent
170 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
171 console.log('Added ' + magnetOrTorrentUrl + '.')
173 // Pause the old torrent
176 // Pause does not remove actual peers (in particular the webseed peer)
177 oldTorrent.removePeer(oldTorrent['ws'])
180 this.addTorrentDelay = setTimeout(() => {
181 this.flushVideoFile(previousVideoFile)
183 const options = { autoplay: true, controls: true }
184 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
185 this.renderer = renderer
187 if (err) return this.fallbackToHttp(done)
189 if (!this.player.paused()) {
190 const playPromise = this.player.play()
191 if (playPromise !== undefined) return playPromise.then(done)
201 this.torrent.on('error', err => this.handleError(err))
203 this.torrent.on('warning', (err: any) => {
204 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
205 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
207 // Users don't care about issues with WebRTC, but developers do so log it in the console
208 if (err.message.indexOf('Ice connection failed') !== -1) {
213 // Magnet hash is not up to date with the torrent file, add directly the torrent file
214 if (err.message.indexOf('incorrect info hash') !== -1) {
215 console.error('Incorrect info hash detected, falling back to torrent file.')
216 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
219 return this.handleError(err)
223 updateResolution (resolutionId: number, delay = 0) {
224 // Remember player state
225 const currentTime = this.player.currentTime()
226 const isPaused = this.player.paused()
228 // Remove poster to have black background
229 this.playerElement.poster = ''
231 // Hide bigPlayButton
233 this.player.bigPlayButton.hide()
236 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
237 this.updateVideoFile(newVideoFile, delay, () => {
238 this.player.currentTime(currentTime)
239 this.player.handleTechSeeked_()
243 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
244 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
245 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
247 webtorrent.remove(videoFile.magnetUri)
248 console.log('Removed ' + videoFile.magnetUri)
252 isAutoResolutionOn () {
253 return this.autoResolution
256 enableAutoResolution () {
257 this.autoResolution = true
258 this.trigger('autoResolutionUpdate')
261 disableAutoResolution () {
262 this.autoResolution = false
263 this.trigger('autoResolutionUpdate')
266 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
267 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
268 if (this.videoFiles.length === 1) return this.videoFiles[0]
269 if (this.torrent && this.torrent.progress === 1) return this.currentVideoFile
271 if (!averageDownloadSpeed) averageDownloadSpeed = this.getActualDownloadSpeed()
273 // Filter videos we can play according to our bandwidth
274 const filteredFiles = this.videoFiles.filter(f => {
275 const fileBitrate = (f.size / this.videoDuration)
276 let threshold = fileBitrate
278 // If this is for a higher resolution or an initial load: add a margin
279 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
280 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
283 return averageDownloadSpeed > threshold
286 // If the download speed is too bad, return the lowest resolution we have
287 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
289 return maxBy(filteredFiles, 'resolution.id')
292 private getActualDownloadSpeed () {
293 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
294 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
295 if (lastDownloadSpeeds.length === 0) return -1
297 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
298 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
300 // Save the average bandwidth for future use
301 saveAverageBandwidth(averageBandwidth)
303 return averageBandwidth
306 private initializePlayer () {
307 this.initSmoothProgressBar()
309 this.alterInactivity()
311 if (this.autoplay === true) {
312 this.player.posterImage.hide()
313 this.updateVideoFile(undefined, 0, () => this.player.play())
316 const oldPlay = this.player.play.bind(this.player)
317 this.player.play = () => {
318 this.updateVideoFile(undefined, 0, () => oldPlay)
319 this.player.play = oldPlay
324 private runAutoQualityScheduler () {
325 this.autoQualityInterval = setInterval(() => {
327 // Not initialized or in HTTP fallback
328 if (this.torrent === undefined || this.torrent === null) return
329 if (this.isAutoResolutionOn() === false) return
330 if (this.isAutoResolutionObservation === true) return
332 const file = this.getAppropriateFile()
333 let changeResolution = false
334 let changeResolutionDelay = 0
337 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
338 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
339 changeResolution = true
340 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
341 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
342 changeResolution = true
343 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
346 if (changeResolution === true) {
347 this.updateResolution(file.resolution.id, changeResolutionDelay)
349 // Wait some seconds in observation of our new resolution
350 this.isAutoResolutionObservation = true
352 this.qualityObservationTimer = setTimeout(() => {
353 this.isAutoResolutionObservation = false
354 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
356 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
359 private isPlayerWaiting () {
360 return this.player && this.player.hasClass('vjs-waiting')
363 private runTorrentInfoScheduler () {
364 this.torrentInfoInterval = setInterval(() => {
365 // Not initialized yet
366 if (this.torrent === undefined) return
369 if (this.torrent === null) return this.trigger('torrentInfo', false)
371 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
372 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
374 return this.trigger('torrentInfo', {
375 downloadSpeed: this.torrent.downloadSpeed,
376 numPeers: this.torrent.numPeers,
377 uploadSpeed: this.torrent.uploadSpeed
379 }, this.CONSTANTS.INFO_SCHEDULER)
382 private runViewAdd () {
383 this.clearVideoViewInterval()
385 // After 30 seconds (or 3/4 of the video), add a view to the video
386 let minSecondsToView = 30
388 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
390 let secondsViewed = 0
391 this.videoViewInterval = setInterval(() => {
392 if (this.player && !this.player.paused()) {
395 if (secondsViewed > minSecondsToView) {
396 this.clearVideoViewInterval()
398 this.addViewToVideo().catch(err => console.error(err))
404 private clearVideoViewInterval () {
405 if (this.videoViewInterval !== undefined) {
406 clearInterval(this.videoViewInterval)
407 this.videoViewInterval = undefined
411 private addViewToVideo () {
412 return fetch(this.videoViewUrl, { method: 'POST' })
415 private fallbackToHttp (done: Function) {
416 this.flushVideoFile(this.currentVideoFile, true)
419 // Enable error display now this is our last fallback
420 this.player.one('error', () => this.enableErrorDisplay())
422 const httpUrl = this.currentVideoFile.fileUrl
423 this.player.src = this.savePlayerSrcFunction
424 this.player.src(httpUrl)
430 private handleError (err: Error | string) {
431 return this.player.trigger('customError', { err })
434 private enableErrorDisplay () {
435 this.player.addClass('vjs-error-display-enabled')
438 private disableErrorDisplay () {
439 this.player.removeClass('vjs-error-display-enabled')
442 private alterInactivity () {
443 let saveInactivityTimeout: number
445 const disableInactivity = () => {
446 saveInactivityTimeout = this.player.options_.inactivityTimeout
447 this.player.options_.inactivityTimeout = 0
449 const enableInactivity = () => {
450 this.player.options_.inactivityTimeout = saveInactivityTimeout
453 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
455 this.player.controlBar.on('mouseenter', () => disableInactivity())
456 settingsDialog.on('mouseenter', () => disableInactivity())
457 this.player.controlBar.on('mouseleave', () => enableInactivity())
458 settingsDialog.on('mouseleave', () => enableInactivity())
461 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
462 private initSmoothProgressBar () {
463 const SeekBar = videojsUntyped.getComponent('SeekBar')
464 SeekBar.prototype.getPercent = function getPercent () {
465 // Allows for smooth scrubbing, when player can't keep up.
466 // const time = (this.player_.scrubbing()) ?
467 // this.player_.getCache().currentTime :
468 // this.player_.currentTime()
469 const time = this.player_.currentTime()
470 const percent = time / this.player_.duration()
471 return percent >= 1 ? 1 : percent
473 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
474 let newTime = this.calculateDistance(event) * this.player_.duration()
475 if (newTime === this.player_.duration()) {
476 newTime = newTime - 0.1
478 this.player_.currentTime(newTime)
484 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
485 export { PeerTubePlugin }