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'
7 import { getAverageBandwidth, getStoredMute, getStoredVolume, saveAverageBandwidth, saveMuteInStore, saveVolumeInStore } from './utils'
8 import minBy from 'lodash-es/minBy'
9 import maxBy from 'lodash-es/maxBy'
10 import * as CacheChunkStore from 'cache-chunk-store'
11 import { PeertubeChunkStore } from './peertube-chunk-store'
13 const webtorrent = new WebTorrent({
18 urls: 'stun:stun.stunprotocol.org'
21 urls: 'stun:stun.framasoft.org'
29 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
30 class PeerTubePlugin extends Plugin {
31 private readonly playerElement: HTMLVideoElement
33 private readonly autoplay: boolean = false
34 private readonly startTime: number = 0
35 private readonly savePlayerSrcFunction: Function
36 private readonly videoFiles: VideoFile[]
37 private readonly videoViewUrl: string
38 private readonly videoDuration: number
39 private readonly CONSTANTS = {
40 INFO_SCHEDULER: 1000, // Don't change this
41 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
42 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
43 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
44 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
45 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
49 private currentVideoFile: VideoFile
50 private torrent: WebTorrent.Torrent
51 private autoResolution = true
52 private isAutoResolutionObservation = false
54 private videoViewInterval
55 private torrentInfoInterval
56 private autoQualityInterval
57 private addTorrentDelay
58 private qualityObservationTimer
59 private runAutoQualitySchedulerTimer
61 private downloadSpeeds: number[] = []
63 constructor (player: videojs.Player, options: PeertubePluginOptions) {
64 super(player, options)
66 this.autoplay = options.autoplay
68 this.startTime = options.startTime
69 this.videoFiles = options.videoFiles
70 this.videoViewUrl = options.videoViewUrl
71 this.videoDuration = options.videoDuration
73 this.savePlayerSrcFunction = this.player.src
74 // Hack to "simulate" src link in video.js >= 6
75 // Without this, we can't play the video after pausing it
76 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
77 this.player.src = () => true
79 this.playerElement = options.playerElement
81 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
83 this.player.ready(() => {
84 const volume = getStoredVolume()
85 if (volume !== undefined) this.player.volume(volume)
86 const muted = getStoredMute()
87 if (muted !== undefined) this.player.muted(muted)
89 this.initializePlayer()
90 this.runTorrentInfoScheduler()
93 this.player.one('play', () => {
94 // Don't run immediately scheduler, wait some seconds the TCP connections are made
95 this.runAutoQualitySchedulerTimer = setTimeout(() => {
96 this.runAutoQualityScheduler()
97 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
101 this.player.on('volumechange', () => {
102 saveVolumeInStore(this.player.volume())
103 saveMuteInStore(this.player.muted())
108 clearTimeout(this.addTorrentDelay)
109 clearTimeout(this.qualityObservationTimer)
110 clearTimeout(this.runAutoQualitySchedulerTimer)
112 clearInterval(this.videoViewInterval)
113 clearInterval(this.torrentInfoInterval)
114 clearInterval(this.autoQualityInterval)
116 // Don't need to destroy renderer, video player will be destroyed
117 this.flushVideoFile(this.currentVideoFile, false)
120 getCurrentResolutionId () {
121 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
124 getCurrentResolutionLabel () {
125 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
128 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
129 if (done === undefined) {
130 done = () => { /* empty */ }
133 // Automatically choose the adapted video file
134 if (videoFile === undefined) {
135 const savedAverageBandwidth = getAverageBandwidth()
136 videoFile = savedAverageBandwidth
137 ? this.getAppropriateFile(savedAverageBandwidth)
141 // Don't add the same video file once again
142 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
146 // Do not display error to user because we will have multiple fallback
147 this.disableErrorDisplay()
149 this.player.src = () => true
150 const oldPlaybackRate = this.player.playbackRate()
152 const previousVideoFile = this.currentVideoFile
153 this.currentVideoFile = videoFile
155 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
156 this.player.playbackRate(oldPlaybackRate)
160 this.trigger('videoFileUpdate')
163 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
164 console.log('Adding ' + magnetOrTorrentUrl + '.')
166 const oldTorrent = this.torrent
168 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
173 this.torrent = webtorrent.add(magnetOrTorrentUrl, options, torrent => {
174 console.log('Added ' + magnetOrTorrentUrl + '.')
176 // Pause the old torrent
179 // Pause does not remove actual peers (in particular the webseed peer)
180 oldTorrent.removePeer(oldTorrent['ws'])
183 this.addTorrentDelay = setTimeout(() => {
184 this.flushVideoFile(previousVideoFile)
186 const options = { autoplay: true, controls: true }
187 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
188 this.renderer = renderer
190 if (err) return this.fallbackToHttp(done)
192 if (!this.player.paused()) return this.tryToPlay(done)
199 this.torrent.on('error', err => this.handleError(err))
201 this.torrent.on('warning', (err: any) => {
202 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
203 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
205 // Users don't care about issues with WebRTC, but developers do so log it in the console
206 if (err.message.indexOf('Ice connection failed') !== -1) {
211 // Magnet hash is not up to date with the torrent file, add directly the torrent file
212 if (err.message.indexOf('incorrect info hash') !== -1) {
213 console.error('Incorrect info hash detected, falling back to torrent file.')
214 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
217 return this.handleError(err)
221 updateResolution (resolutionId: number, delay = 0) {
222 // Remember player state
223 const currentTime = this.player.currentTime()
224 const isPaused = this.player.paused()
226 // Remove poster to have black background
227 this.playerElement.poster = ''
229 // Hide bigPlayButton
231 this.player.bigPlayButton.hide()
234 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
235 this.updateVideoFile(newVideoFile, delay, () => this.seek(currentTime))
238 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
239 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
240 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
242 webtorrent.remove(videoFile.magnetUri)
243 console.log('Removed ' + videoFile.magnetUri)
247 isAutoResolutionOn () {
248 return this.autoResolution
251 enableAutoResolution () {
252 this.autoResolution = true
253 this.trigger('autoResolutionUpdate')
256 disableAutoResolution () {
257 this.autoResolution = false
258 this.trigger('autoResolutionUpdate')
261 private tryToPlay (done?: Function) {
262 if (!done) done = function () { /* empty */ }
264 const playPromise = this.player.play()
265 if (playPromise !== undefined) {
266 return playPromise.then(done)
270 this.player.posterImage.show()
271 this.player.removeClass('vjs-has-autoplay')
280 private seek (time: number) {
281 this.player.currentTime(time)
282 this.player.handleTechSeeked_()
285 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
286 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
287 if (this.videoFiles.length === 1) return this.videoFiles[0]
289 // Don't change the torrent is the play was ended
290 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
292 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
294 // Filter videos we can play according to our bandwidth
295 const filteredFiles = this.videoFiles.filter(f => {
296 const fileBitrate = (f.size / this.videoDuration)
297 let threshold = fileBitrate
299 // If this is for a higher resolution or an initial load: add a margin
300 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
301 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
304 return averageDownloadSpeed > threshold
307 // If the download speed is too bad, return the lowest resolution we have
308 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
310 return maxBy(filteredFiles, 'resolution.id')
313 private getAndSaveActualDownloadSpeed () {
314 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
315 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
316 if (lastDownloadSpeeds.length === 0) return -1
318 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
319 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
321 // Save the average bandwidth for future use
322 saveAverageBandwidth(averageBandwidth)
324 return averageBandwidth
327 private initializePlayer () {
328 this.initSmoothProgressBar()
330 this.alterInactivity()
332 if (this.autoplay === true) {
333 this.player.posterImage.hide()
335 this.updateVideoFile(undefined, 0, () => {
336 this.seek(this.startTime)
341 const oldPlay = this.player.play.bind(this.player)
342 this.player.play = () => {
343 this.player.addClass('vjs-has-big-play-button-clicked')
344 this.player.play = oldPlay
346 this.updateVideoFile(undefined, 0, () => this.seek(this.startTime))
351 private runAutoQualityScheduler () {
352 this.autoQualityInterval = setInterval(() => {
354 // Not initialized or in HTTP fallback
355 if (this.torrent === undefined || this.torrent === null) return
356 if (this.isAutoResolutionOn() === false) return
357 if (this.isAutoResolutionObservation === true) return
359 const file = this.getAppropriateFile()
360 let changeResolution = false
361 let changeResolutionDelay = 0
364 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
365 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
366 changeResolution = true
367 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
368 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
369 changeResolution = true
370 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
373 if (changeResolution === true) {
374 this.updateResolution(file.resolution.id, changeResolutionDelay)
376 // Wait some seconds in observation of our new resolution
377 this.isAutoResolutionObservation = true
379 this.qualityObservationTimer = setTimeout(() => {
380 this.isAutoResolutionObservation = false
381 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
383 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
386 private isPlayerWaiting () {
387 return this.player && this.player.hasClass('vjs-waiting')
390 private runTorrentInfoScheduler () {
391 this.torrentInfoInterval = setInterval(() => {
392 // Not initialized yet
393 if (this.torrent === undefined) return
396 if (this.torrent === null) return this.trigger('torrentInfo', false)
398 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
399 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
401 return this.trigger('torrentInfo', {
402 downloadSpeed: this.torrent.downloadSpeed,
403 numPeers: this.torrent.numPeers,
404 uploadSpeed: this.torrent.uploadSpeed
406 }, this.CONSTANTS.INFO_SCHEDULER)
409 private runViewAdd () {
410 this.clearVideoViewInterval()
412 // After 30 seconds (or 3/4 of the video), add a view to the video
413 let minSecondsToView = 30
415 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
417 let secondsViewed = 0
418 this.videoViewInterval = setInterval(() => {
419 if (this.player && !this.player.paused()) {
422 if (secondsViewed > minSecondsToView) {
423 this.clearVideoViewInterval()
425 this.addViewToVideo().catch(err => console.error(err))
431 private clearVideoViewInterval () {
432 if (this.videoViewInterval !== undefined) {
433 clearInterval(this.videoViewInterval)
434 this.videoViewInterval = undefined
438 private addViewToVideo () {
439 return fetch(this.videoViewUrl, { method: 'POST' })
442 private fallbackToHttp (done: Function) {
443 this.flushVideoFile(this.currentVideoFile, true)
446 // Enable error display now this is our last fallback
447 this.player.one('error', () => this.enableErrorDisplay())
449 const httpUrl = this.currentVideoFile.fileUrl
450 this.player.src = this.savePlayerSrcFunction
451 this.player.src(httpUrl)
457 private handleError (err: Error | string) {
458 return this.player.trigger('customError', { err })
461 private enableErrorDisplay () {
462 this.player.addClass('vjs-error-display-enabled')
465 private disableErrorDisplay () {
466 this.player.removeClass('vjs-error-display-enabled')
469 private alterInactivity () {
470 let saveInactivityTimeout: number
472 const disableInactivity = () => {
473 saveInactivityTimeout = this.player.options_.inactivityTimeout
474 this.player.options_.inactivityTimeout = 0
476 const enableInactivity = () => {
477 this.player.options_.inactivityTimeout = saveInactivityTimeout
480 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
482 this.player.controlBar.on('mouseenter', () => disableInactivity())
483 settingsDialog.on('mouseenter', () => disableInactivity())
484 this.player.controlBar.on('mouseleave', () => enableInactivity())
485 settingsDialog.on('mouseleave', () => enableInactivity())
488 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
489 private initSmoothProgressBar () {
490 const SeekBar = videojsUntyped.getComponent('SeekBar')
491 SeekBar.prototype.getPercent = function getPercent () {
492 // Allows for smooth scrubbing, when player can't keep up.
493 // const time = (this.player_.scrubbing()) ?
494 // this.player_.getCache().currentTime :
495 // this.player_.currentTime()
496 const time = this.player_.currentTime()
497 const percent = time / this.player_.duration()
498 return percent >= 1 ? 1 : percent
500 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
501 let newTime = this.calculateDistance(event) * this.player_.duration()
502 if (newTime === this.player_.duration()) {
503 newTime = newTime - 0.1
505 this.player_.currentTime(newTime)
511 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
512 export { PeerTubePlugin }