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 { isMobile, videoFileMaxByResolution, videoFileMinByResolution } from './utils'
8 import * as CacheChunkStore from 'cache-chunk-store'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
11 getAverageBandwidthInStore,
17 } from './peertube-player-local-storage'
19 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
20 class PeerTubePlugin extends Plugin {
21 private readonly playerElement: HTMLVideoElement
23 private readonly autoplay: boolean = false
24 private readonly startTime: number = 0
25 private readonly savePlayerSrcFunction: Function
26 private readonly videoFiles: VideoFile[]
27 private readonly videoViewUrl: string
28 private readonly videoDuration: number
29 private readonly CONSTANTS = {
30 INFO_SCHEDULER: 1000, // Don't change this
31 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
32 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
33 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
34 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
35 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
38 private readonly webtorrent = new WebTorrent({
43 urls: 'stun:stun.stunprotocol.org'
46 urls: 'stun:stun.framasoft.org'
55 private currentVideoFile: VideoFile
56 private torrent: WebTorrent.Torrent
59 private autoResolution = true
60 private forbidAutoResolution = false
61 private isAutoResolutionObservation = false
63 private videoViewInterval
64 private torrentInfoInterval
65 private autoQualityInterval
66 private addTorrentDelay
67 private qualityObservationTimer
68 private runAutoQualitySchedulerTimer
70 private downloadSpeeds: number[] = []
72 constructor (player: videojs.Player, options: PeertubePluginOptions) {
73 super(player, options)
75 // Disable auto play on iOS
76 this.autoplay = options.autoplay && this.isIOS() === false
78 this.startTime = options.startTime
79 this.videoFiles = options.videoFiles
80 this.videoViewUrl = options.videoViewUrl
81 this.videoDuration = options.videoDuration
83 this.savePlayerSrcFunction = this.player.src
84 // Hack to "simulate" src link in video.js >= 6
85 // Without this, we can't play the video after pausing it
86 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
87 this.player.src = () => true
89 this.playerElement = options.playerElement
91 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
93 this.player.ready(() => {
94 const volume = getStoredVolume()
95 if (volume !== undefined) this.player.volume(volume)
96 const muted = getStoredMute()
97 if (muted !== undefined) this.player.muted(muted)
99 this.initializePlayer()
100 this.runTorrentInfoScheduler()
103 this.player.one('play', () => {
104 // Don't run immediately scheduler, wait some seconds the TCP connections are made
105 this.runAutoQualitySchedulerTimer = setTimeout(() => {
106 this.runAutoQualityScheduler()
107 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
111 this.player.on('volumechange', () => {
112 saveVolumeInStore(this.player.volume())
113 saveMuteInStore(this.player.muted())
118 clearTimeout(this.addTorrentDelay)
119 clearTimeout(this.qualityObservationTimer)
120 clearTimeout(this.runAutoQualitySchedulerTimer)
122 clearInterval(this.videoViewInterval)
123 clearInterval(this.torrentInfoInterval)
124 clearInterval(this.autoQualityInterval)
126 // Don't need to destroy renderer, video player will be destroyed
127 this.flushVideoFile(this.currentVideoFile, false)
129 this.destroyFakeRenderer()
132 getCurrentResolutionId () {
133 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
136 getCurrentResolutionLabel () {
137 if (!this.currentVideoFile) return ''
139 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
140 return this.currentVideoFile.resolution.label + fps
144 videoFile?: VideoFile,
150 done: () => void = () => { /* empty */ }
152 // Automatically choose the adapted video file
153 if (videoFile === undefined) {
154 const savedAverageBandwidth = getAverageBandwidthInStore()
155 videoFile = savedAverageBandwidth
156 ? this.getAppropriateFile(savedAverageBandwidth)
157 : this.pickAverageVideoFile()
160 // Don't add the same video file once again
161 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
165 // Do not display error to user because we will have multiple fallback
166 this.disableErrorDisplay()
168 this.player.src = () => true
169 const oldPlaybackRate = this.player.playbackRate()
171 const previousVideoFile = this.currentVideoFile
172 this.currentVideoFile = videoFile
174 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
175 this.player.playbackRate(oldPlaybackRate)
179 this.trigger('videoFileUpdate')
183 magnetOrTorrentUrl: string,
184 previousVideoFile: VideoFile,
192 console.log('Adding ' + magnetOrTorrentUrl + '.')
194 const oldTorrent = this.torrent
195 const torrentOptions = {
196 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
201 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
202 console.log('Added ' + magnetOrTorrentUrl + '.')
205 // Pause the old torrent
207 // Pause does not remove actual peers (in particular the webseed peer)
208 oldTorrent.removePeer(oldTorrent['ws'])
210 // We use a fake renderer so we download correct pieces of the next file
212 const fakeVideoElem = document.createElement('video')
213 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
214 this.fakeRenderer = renderer
216 if (err) console.error('Cannot render new torrent in fake video element.', err)
218 // Load the future file at the correct time
219 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
224 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
225 this.addTorrentDelay = setTimeout(() => {
226 this.destroyFakeRenderer()
228 const paused = this.player.paused()
230 this.flushVideoFile(previousVideoFile)
232 const renderVideoOptions = { autoplay: false, controls: true }
233 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
234 this.renderer = renderer
236 if (err) return this.fallbackToHttp(done)
238 return this.tryToPlay(err => {
239 if (err) return done(err)
241 if (options.seek) this.seek(options.seek)
242 if (options.forcePlay === false && paused === true) this.player.pause()
245 }, options.delay || 0)
248 this.torrent.on('error', err => console.error(err))
250 this.torrent.on('warning', (err: any) => {
251 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
252 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
254 // Users don't care about issues with WebRTC, but developers do so log it in the console
255 if (err.message.indexOf('Ice connection failed') !== -1) {
260 // Magnet hash is not up to date with the torrent file, add directly the torrent file
261 if (err.message.indexOf('incorrect info hash') !== -1) {
262 console.error('Incorrect info hash detected, falling back to torrent file.')
263 const options = { forcePlay: true }
264 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
267 return console.warn(err)
271 updateResolution (resolutionId: number, delay = 0) {
272 // Remember player state
273 const currentTime = this.player.currentTime()
274 const isPaused = this.player.paused()
276 // Remove poster to have black background
277 this.playerElement.poster = ''
279 // Hide bigPlayButton
281 this.player.bigPlayButton.hide()
284 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
288 seek: currentTime + (delay / 1000)
290 this.updateVideoFile(newVideoFile, options)
293 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
294 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
295 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
297 this.webtorrent.remove(videoFile.magnetUri)
298 console.log('Removed ' + videoFile.magnetUri)
302 isAutoResolutionOn () {
303 return this.autoResolution
306 enableAutoResolution () {
307 this.autoResolution = true
308 this.trigger('autoResolutionUpdate')
311 disableAutoResolution (forbid = false) {
312 if (forbid === true) this.forbidAutoResolution = true
314 this.autoResolution = false
315 this.trigger('autoResolutionUpdate')
318 isAutoResolutionForbidden () {
319 return this.forbidAutoResolution === true
322 getCurrentVideoFile () {
323 return this.currentVideoFile
330 private tryToPlay (done?: Function) {
331 if (!done) done = function () { /* empty */ }
333 const playPromise = this.player.play()
334 if (playPromise !== undefined) {
335 return playPromise.then(done)
337 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
343 this.player.posterImage.show()
344 this.player.removeClass('vjs-has-autoplay')
345 this.player.removeClass('vjs-has-big-play-button-clicked')
354 private seek (time: number) {
355 this.player.currentTime(time)
356 this.player.handleTechSeeked_()
359 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
360 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
361 if (this.videoFiles.length === 1) return this.videoFiles[0]
363 // Don't change the torrent is the play was ended
364 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
366 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
368 // Filter videos we can play according to our screen resolution and bandwidth
369 const filteredFiles = this.videoFiles.filter(f => f.resolution.id <= this.playerElement.width)
371 const fileBitrate = (f.size / this.videoDuration)
372 let threshold = fileBitrate
374 // If this is for a higher resolution or an initial load: add a margin
375 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
376 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
379 return averageDownloadSpeed > threshold
382 // If the download speed is too bad, return the lowest resolution we have
383 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
385 return videoFileMaxByResolution(filteredFiles)
388 private getAndSaveActualDownloadSpeed () {
389 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
390 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
391 if (lastDownloadSpeeds.length === 0) return -1
393 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
394 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
396 // Save the average bandwidth for future use
397 saveAverageBandwidth(averageBandwidth)
399 return averageBandwidth
402 private initializePlayer () {
403 if (isMobile()) this.player.addClass('vjs-is-mobile')
405 this.initSmoothProgressBar()
407 this.alterInactivity()
409 if (this.autoplay === true) {
410 this.player.posterImage.hide()
412 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
414 // Don't try on iOS that does not support MediaSource
416 this.currentVideoFile = this.pickAverageVideoFile()
417 return this.fallbackToHttp(undefined, false)
421 const oldPlay = this.player.play.bind(this.player)
422 this.player.play = () => {
423 this.player.addClass('vjs-has-big-play-button-clicked')
424 this.player.play = oldPlay
426 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
431 private runAutoQualityScheduler () {
432 this.autoQualityInterval = setInterval(() => {
434 // Not initialized or in HTTP fallback
435 if (this.torrent === undefined || this.torrent === null) return
436 if (this.isAutoResolutionOn() === false) return
437 if (this.isAutoResolutionObservation === true) return
439 const file = this.getAppropriateFile()
440 let changeResolution = false
441 let changeResolutionDelay = 0
444 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
445 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
446 changeResolution = true
447 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
448 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
449 changeResolution = true
450 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
453 if (changeResolution === true) {
454 this.updateResolution(file.resolution.id, changeResolutionDelay)
456 // Wait some seconds in observation of our new resolution
457 this.isAutoResolutionObservation = true
459 this.qualityObservationTimer = setTimeout(() => {
460 this.isAutoResolutionObservation = false
461 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
463 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
466 private isPlayerWaiting () {
467 return this.player && this.player.hasClass('vjs-waiting')
470 private runTorrentInfoScheduler () {
471 this.torrentInfoInterval = setInterval(() => {
472 // Not initialized yet
473 if (this.torrent === undefined) return
476 if (this.torrent === null) return this.trigger('torrentInfo', false)
478 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
479 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
481 return this.trigger('torrentInfo', {
482 downloadSpeed: this.torrent.downloadSpeed,
483 numPeers: this.torrent.numPeers,
484 uploadSpeed: this.torrent.uploadSpeed,
485 downloaded: this.torrent.downloaded,
486 uploaded: this.torrent.uploaded
488 }, this.CONSTANTS.INFO_SCHEDULER)
491 private runViewAdd () {
492 this.clearVideoViewInterval()
494 // After 30 seconds (or 3/4 of the video), add a view to the video
495 let minSecondsToView = 30
497 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
499 let secondsViewed = 0
500 this.videoViewInterval = setInterval(() => {
501 if (this.player && !this.player.paused()) {
504 if (secondsViewed > minSecondsToView) {
505 this.clearVideoViewInterval()
507 this.addViewToVideo().catch(err => console.error(err))
513 private clearVideoViewInterval () {
514 if (this.videoViewInterval !== undefined) {
515 clearInterval(this.videoViewInterval)
516 this.videoViewInterval = undefined
520 private addViewToVideo () {
521 if (!this.videoViewUrl) return Promise.resolve(undefined)
523 return fetch(this.videoViewUrl, { method: 'POST' })
526 private fallbackToHttp (done?: Function, play = true) {
527 this.disableAutoResolution(true)
529 this.flushVideoFile(this.currentVideoFile, true)
532 // Enable error display now this is our last fallback
533 this.player.one('error', () => this.enableErrorDisplay())
535 const httpUrl = this.currentVideoFile.fileUrl
536 this.player.src = this.savePlayerSrcFunction
537 this.player.src(httpUrl)
538 if (play) this.tryToPlay()
540 if (done) return done()
543 private handleError (err: Error | string) {
544 return this.player.trigger('customError', { err })
547 private enableErrorDisplay () {
548 this.player.addClass('vjs-error-display-enabled')
551 private disableErrorDisplay () {
552 this.player.removeClass('vjs-error-display-enabled')
556 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
559 private alterInactivity () {
560 let saveInactivityTimeout: number
562 const disableInactivity = () => {
563 saveInactivityTimeout = this.player.options_.inactivityTimeout
564 this.player.options_.inactivityTimeout = 0
566 const enableInactivity = () => {
567 this.player.options_.inactivityTimeout = saveInactivityTimeout
570 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
572 this.player.controlBar.on('mouseenter', () => disableInactivity())
573 settingsDialog.on('mouseenter', () => disableInactivity())
574 this.player.controlBar.on('mouseleave', () => enableInactivity())
575 settingsDialog.on('mouseleave', () => enableInactivity())
578 private pickAverageVideoFile () {
579 if (this.videoFiles.length === 1) return this.videoFiles[0]
581 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
584 private destroyFakeRenderer () {
585 if (this.fakeRenderer) {
586 if (this.fakeRenderer.destroy) {
588 this.fakeRenderer.destroy()
590 console.log('Cannot destroy correctly fake renderer.', err)
593 this.fakeRenderer = undefined
597 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
598 private initSmoothProgressBar () {
599 const SeekBar = videojsUntyped.getComponent('SeekBar')
600 SeekBar.prototype.getPercent = function getPercent () {
601 // Allows for smooth scrubbing, when player can't keep up.
602 // const time = (this.player_.scrubbing()) ?
603 // this.player_.getCache().currentTime :
604 // this.player_.currentTime()
605 const time = this.player_.currentTime()
606 const percent = time / this.player_.duration()
607 return percent >= 1 ? 1 : percent
609 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
610 let newTime = this.calculateDistance(event) * this.player_.duration()
611 if (newTime === this.player_.duration()) {
612 newTime = newTime - 0.1
614 this.player_.currentTime(newTime)
620 videojs.registerPlugin('peertube', PeerTubePlugin)
621 export { PeerTubePlugin }