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 before potentially changing the definition
48 AUTO_QUALITY_UPPER_RESOLUTION_DELAY: 5000, // Buffer upper 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 videoViewInterval
56 private torrentInfoInterval
57 private autoQualityInterval
58 private autoResolution = true
59 private isAutoResolutionObservation = false
61 private downloadSpeeds: number[] = []
63 constructor (player: videojs.Player, options: PeertubePluginOptions) {
64 super(player, options)
66 // Fix canplay event on google chrome by disabling default videojs autoplay
67 this.autoplay = this.player.options_.autoplay
68 this.player.options_.autoplay = false
70 this.videoFiles = options.videoFiles
71 this.videoViewUrl = options.videoViewUrl
72 this.videoDuration = options.videoDuration
74 this.savePlayerSrcFunction = this.player.src
75 // Hack to "simulate" src link in video.js >= 6
76 // Without this, we can't play the video after pausing it
77 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
78 this.player.src = () => true
80 this.playerElement = options.playerElement
82 this.player.ready(() => {
83 const volume = getStoredVolume()
84 if (volume !== undefined) this.player.volume(volume)
85 const muted = getStoredMute()
86 if (muted !== undefined) this.player.muted(muted)
88 this.initializePlayer()
89 this.runTorrentInfoScheduler()
92 this.player.one('play', () => {
93 // Don't run immediately scheduler, wait some seconds the TCP connections are maid
94 setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
98 this.player.on('volumechange', () => {
99 saveVolumeInStore(this.player.volume())
100 saveMuteInStore(this.player.muted())
105 clearInterval(this.videoViewInterval)
106 clearInterval(this.torrentInfoInterval)
107 clearInterval(this.autoQualityInterval)
109 // Don't need to destroy renderer, video player will be destroyed
110 this.flushVideoFile(this.currentVideoFile, false)
113 getCurrentResolutionId () {
114 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
117 getCurrentResolutionLabel () {
118 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
121 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
122 if (done === undefined) {
123 done = () => { /* empty */ }
126 // Automatically choose the adapted video file
127 if (videoFile === undefined) {
128 const savedAverageBandwidth = getAverageBandwidth()
129 videoFile = savedAverageBandwidth
130 ? this.getAppropriateFile(savedAverageBandwidth)
134 // Don't add the same video file once again
135 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
139 // Do not display error to user because we will have multiple fallback
140 this.disableErrorDisplay()
142 this.player.src = () => true
143 const oldPlaybackRate = this.player.playbackRate()
145 const previousVideoFile = this.currentVideoFile
146 this.currentVideoFile = videoFile
148 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
149 this.player.playbackRate(oldPlaybackRate)
153 this.trigger('videoFileUpdate')
156 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
157 console.log('Adding ' + magnetOrTorrentUrl + '.')
159 const oldTorrent = this.torrent
160 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
161 console.log('Added ' + magnetOrTorrentUrl + '.')
163 // Pause the old torrent
166 // Pause does not remove actual peers (in particular the webseed peer)
167 oldTorrent.removePeer(oldTorrent['ws'])
171 this.flushVideoFile(previousVideoFile)
173 const options = { autoplay: true, controls: true }
174 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
175 this.renderer = renderer
177 if (err) return this.fallbackToHttp(done)
179 if (!this.player.paused()) {
180 const playPromise = this.player.play()
181 if (playPromise !== undefined) return playPromise.then(done)
191 this.torrent.on('error', err => this.handleError(err))
193 this.torrent.on('warning', (err: any) => {
194 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
195 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
197 // Users don't care about issues with WebRTC, but developers do so log it in the console
198 if (err.message.indexOf('Ice connection failed') !== -1) {
203 // Magnet hash is not up to date with the torrent file, add directly the torrent file
204 if (err.message.indexOf('incorrect info hash') !== -1) {
205 console.error('Incorrect info hash detected, falling back to torrent file.')
206 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
209 return this.handleError(err)
213 updateResolution (resolutionId: number, delay = 0) {
214 // Remember player state
215 const currentTime = this.player.currentTime()
216 const isPaused = this.player.paused()
218 // Remove poster to have black background
219 this.playerElement.poster = ''
221 // Hide bigPlayButton
223 this.player.bigPlayButton.hide()
226 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
227 this.updateVideoFile(newVideoFile, delay, () => {
228 this.player.currentTime(currentTime)
229 this.player.handleTechSeeked_()
233 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
234 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
235 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
237 webtorrent.remove(videoFile.magnetUri)
238 console.log('Removed ' + videoFile.magnetUri)
242 isAutoResolutionOn () {
243 return this.autoResolution
246 enableAutoResolution () {
247 this.autoResolution = true
248 this.trigger('autoResolutionUpdate')
251 disableAutoResolution () {
252 this.autoResolution = false
253 this.trigger('autoResolutionUpdate')
256 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
257 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
258 if (this.videoFiles.length === 1) return this.videoFiles[0]
259 if (this.torrent && this.torrent.progress === 1) return this.currentVideoFile
261 if (!averageDownloadSpeed) averageDownloadSpeed = this.getActualDownloadSpeed()
263 // Filter videos we can play according to our bandwidth
264 const filteredFiles = this.videoFiles.filter(f => {
265 const fileBitrate = (f.size / this.videoDuration)
266 let threshold = fileBitrate
268 // If this is for a higher resolution, or an initial load -> add a upper margin
269 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
270 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
273 return averageDownloadSpeed > threshold
276 // If the download speed is too bad, return the lowest resolution we have
277 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
279 return maxBy(filteredFiles, 'resolution.id')
282 private getActualDownloadSpeed () {
283 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
284 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
285 if (lastDownloadSpeeds.length === 0) return -1
287 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
288 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
290 // Save the average bandwidth for future use
291 saveAverageBandwidth(averageBandwidth)
293 return averageBandwidth
296 private initializePlayer () {
297 this.initSmoothProgressBar()
299 this.alterInactivity()
301 if (this.autoplay === true) {
302 this.player.posterImage.hide()
303 this.updateVideoFile(undefined, 0, () => this.player.play())
306 const oldPlay = this.player.play.bind(this.player)
307 this.player.play = () => {
308 this.updateVideoFile(undefined, 0, () => oldPlay)
309 this.player.play = oldPlay
314 private runAutoQualityScheduler () {
315 this.autoQualityInterval = setInterval(() => {
316 // Not initialized or in HTTP fallback
317 if (this.torrent === undefined || this.torrent === null) return
318 if (this.isAutoResolutionOn() === false) return
319 if (this.isAutoResolutionObservation === true) return
321 const file = this.getAppropriateFile()
322 let changeResolution = false
323 let changeResolutionDelay = 0
326 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
327 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
328 changeResolution = true
329 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Greater resolution
330 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
331 changeResolution = true
332 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_UPPER_RESOLUTION_DELAY
335 if (changeResolution === true) {
336 this.updateResolution(file.resolution.id, changeResolutionDelay)
338 // Wait some seconds in observation of our new resolution
339 this.isAutoResolutionObservation = true
340 setTimeout(() => this.isAutoResolutionObservation = false, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
342 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
345 private isPlayerWaiting () {
346 return this.player.hasClass('vjs-waiting')
349 private runTorrentInfoScheduler () {
350 this.torrentInfoInterval = setInterval(() => {
351 // Not initialized yet
352 if (this.torrent === undefined) return
355 if (this.torrent === null) return this.trigger('torrentInfo', false)
357 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
358 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
360 return this.trigger('torrentInfo', {
361 downloadSpeed: this.torrent.downloadSpeed,
362 numPeers: this.torrent.numPeers,
363 uploadSpeed: this.torrent.uploadSpeed
365 }, this.CONSTANTS.INFO_SCHEDULER)
368 private runViewAdd () {
369 this.clearVideoViewInterval()
371 // After 30 seconds (or 3/4 of the video), add a view to the video
372 let minSecondsToView = 30
374 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
376 let secondsViewed = 0
377 this.videoViewInterval = setInterval(() => {
378 if (this.player && !this.player.paused()) {
381 if (secondsViewed > minSecondsToView) {
382 this.clearVideoViewInterval()
384 this.addViewToVideo().catch(err => console.error(err))
390 private clearVideoViewInterval () {
391 if (this.videoViewInterval !== undefined) {
392 clearInterval(this.videoViewInterval)
393 this.videoViewInterval = undefined
397 private addViewToVideo () {
398 return fetch(this.videoViewUrl, { method: 'POST' })
401 private fallbackToHttp (done: Function) {
402 this.flushVideoFile(this.currentVideoFile, true)
405 // Enable error display now this is our last fallback
406 this.player.one('error', () => this.enableErrorDisplay())
408 const httpUrl = this.currentVideoFile.fileUrl
409 this.player.src = this.savePlayerSrcFunction
410 this.player.src(httpUrl)
416 private handleError (err: Error | string) {
417 return this.player.trigger('customError', { err })
420 private enableErrorDisplay () {
421 this.player.addClass('vjs-error-display-enabled')
424 private disableErrorDisplay () {
425 this.player.removeClass('vjs-error-display-enabled')
428 private alterInactivity () {
429 let saveInactivityTimeout: number
431 const disableInactivity = () => {
432 saveInactivityTimeout = this.player.options_.inactivityTimeout
433 this.player.options_.inactivityTimeout = 0
435 const enableInactivity = () => {
436 this.player.options_.inactivityTimeout = saveInactivityTimeout
439 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
441 this.player.controlBar.on('mouseenter', () => disableInactivity())
442 settingsDialog.on('mouseenter', () => disableInactivity())
443 this.player.controlBar.on('mouseleave', () => enableInactivity())
444 settingsDialog.on('mouseleave', () => enableInactivity())
447 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
448 private initSmoothProgressBar () {
449 const SeekBar = videojsUntyped.getComponent('SeekBar')
450 SeekBar.prototype.getPercent = function getPercent () {
451 // Allows for smooth scrubbing, when player can't keep up.
452 // const time = (this.player_.scrubbing()) ?
453 // this.player_.getCache().currentTime :
454 // this.player_.currentTime()
455 const time = this.player_.currentTime()
456 const percent = time / this.player_.duration()
457 return percent >= 1 ? 1 : percent
459 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
460 let newTime = this.calculateDistance(event) * this.player_.duration()
461 if (newTime === this.player_.duration()) {
462 newTime = newTime - 0.1
464 this.player_.currentTime(newTime)
470 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
471 export { PeerTubePlugin }