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 isAutoResolutionObservation = false
62 private videoViewInterval
63 private torrentInfoInterval
64 private autoQualityInterval
65 private addTorrentDelay
66 private qualityObservationTimer
67 private runAutoQualitySchedulerTimer
69 private downloadSpeeds: number[] = []
71 constructor (player: videojs.Player, options: PeertubePluginOptions) {
72 super(player, options)
74 // Disable auto play on iOS
75 this.autoplay = options.autoplay && this.isIOS() === false
77 this.startTime = options.startTime
78 this.videoFiles = options.videoFiles
79 this.videoViewUrl = options.videoViewUrl
80 this.videoDuration = options.videoDuration
82 this.savePlayerSrcFunction = this.player.src
83 // Hack to "simulate" src link in video.js >= 6
84 // Without this, we can't play the video after pausing it
85 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
86 this.player.src = () => true
88 this.playerElement = options.playerElement
90 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
92 this.player.ready(() => {
93 const volume = getStoredVolume()
94 if (volume !== undefined) this.player.volume(volume)
95 const muted = getStoredMute()
96 if (muted !== undefined) this.player.muted(muted)
98 this.initializePlayer()
99 this.runTorrentInfoScheduler()
102 this.player.one('play', () => {
103 // Don't run immediately scheduler, wait some seconds the TCP connections are made
104 this.runAutoQualitySchedulerTimer = setTimeout(() => {
105 this.runAutoQualityScheduler()
106 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
110 this.player.on('volumechange', () => {
111 saveVolumeInStore(this.player.volume())
112 saveMuteInStore(this.player.muted())
117 clearTimeout(this.addTorrentDelay)
118 clearTimeout(this.qualityObservationTimer)
119 clearTimeout(this.runAutoQualitySchedulerTimer)
121 clearInterval(this.videoViewInterval)
122 clearInterval(this.torrentInfoInterval)
123 clearInterval(this.autoQualityInterval)
125 // Don't need to destroy renderer, video player will be destroyed
126 this.flushVideoFile(this.currentVideoFile, false)
128 this.destroyFakeRenderer()
131 getCurrentResolutionId () {
132 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
135 getCurrentResolutionLabel () {
136 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
140 videoFile?: VideoFile,
146 done: () => void = () => { /* empty */ }
148 // Automatically choose the adapted video file
149 if (videoFile === undefined) {
150 const savedAverageBandwidth = getAverageBandwidthInStore()
151 videoFile = savedAverageBandwidth
152 ? this.getAppropriateFile(savedAverageBandwidth)
153 : this.pickAverageVideoFile()
156 // Don't add the same video file once again
157 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
161 // Do not display error to user because we will have multiple fallback
162 this.disableErrorDisplay()
164 this.player.src = () => true
165 const oldPlaybackRate = this.player.playbackRate()
167 const previousVideoFile = this.currentVideoFile
168 this.currentVideoFile = videoFile
170 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
171 this.player.playbackRate(oldPlaybackRate)
175 this.trigger('videoFileUpdate')
179 magnetOrTorrentUrl: string,
180 previousVideoFile: VideoFile,
188 console.log('Adding ' + magnetOrTorrentUrl + '.')
190 const oldTorrent = this.torrent
191 const torrentOptions = {
192 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
197 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
198 console.log('Added ' + magnetOrTorrentUrl + '.')
201 // Pause the old torrent
203 // Pause does not remove actual peers (in particular the webseed peer)
204 oldTorrent.removePeer(oldTorrent['ws'])
206 // We use a fake renderer so we download correct pieces of the next file
208 const fakeVideoElem = document.createElement('video')
209 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
210 this.fakeRenderer = renderer
212 if (err) console.error('Cannot render new torrent in fake video element.', err)
214 // Load the future file at the correct time
215 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
220 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
221 this.addTorrentDelay = setTimeout(() => {
222 this.destroyFakeRenderer()
224 const paused = this.player.paused()
226 this.flushVideoFile(previousVideoFile)
228 const renderVideoOptions = { autoplay: false, controls: true }
229 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
230 this.renderer = renderer
232 if (err) return this.fallbackToHttp(done)
234 return this.tryToPlay(err => {
235 if (err) return done(err)
237 if (options.seek) this.seek(options.seek)
238 if (options.forcePlay === false && paused === true) this.player.pause()
241 }, options.delay || 0)
244 this.torrent.on('error', err => this.handleError(err))
246 this.torrent.on('warning', (err: any) => {
247 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
248 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
250 // Users don't care about issues with WebRTC, but developers do so log it in the console
251 if (err.message.indexOf('Ice connection failed') !== -1) {
256 // Magnet hash is not up to date with the torrent file, add directly the torrent file
257 if (err.message.indexOf('incorrect info hash') !== -1) {
258 console.error('Incorrect info hash detected, falling back to torrent file.')
259 const options = { forcePlay: true }
260 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
263 return this.handleError(err)
267 updateResolution (resolutionId: number, delay = 0) {
268 // Remember player state
269 const currentTime = this.player.currentTime()
270 const isPaused = this.player.paused()
272 // Remove poster to have black background
273 this.playerElement.poster = ''
275 // Hide bigPlayButton
277 this.player.bigPlayButton.hide()
280 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
284 seek: currentTime + (delay / 1000)
286 this.updateVideoFile(newVideoFile, options)
289 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
290 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
291 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
293 this.webtorrent.remove(videoFile.magnetUri)
294 console.log('Removed ' + videoFile.magnetUri)
298 isAutoResolutionOn () {
299 return this.autoResolution
302 enableAutoResolution () {
303 this.autoResolution = true
304 this.trigger('autoResolutionUpdate')
307 disableAutoResolution () {
308 this.autoResolution = false
309 this.trigger('autoResolutionUpdate')
312 getCurrentVideoFile () {
313 return this.currentVideoFile
320 private tryToPlay (done?: Function) {
321 if (!done) done = function () { /* empty */ }
323 const playPromise = this.player.play()
324 if (playPromise !== undefined) {
325 return playPromise.then(done)
329 this.player.posterImage.show()
330 this.player.removeClass('vjs-has-autoplay')
331 this.player.removeClass('vjs-has-big-play-button-clicked')
340 private seek (time: number) {
341 this.player.currentTime(time)
342 this.player.handleTechSeeked_()
345 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
346 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
347 if (this.videoFiles.length === 1) return this.videoFiles[0]
349 // Don't change the torrent is the play was ended
350 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
352 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
354 // Filter videos we can play according to our bandwidth
355 const filteredFiles = this.videoFiles.filter(f => {
356 const fileBitrate = (f.size / this.videoDuration)
357 let threshold = fileBitrate
359 // If this is for a higher resolution or an initial load: add a margin
360 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
361 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
364 return averageDownloadSpeed > threshold
367 // If the download speed is too bad, return the lowest resolution we have
368 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
370 return videoFileMaxByResolution(filteredFiles)
373 private getAndSaveActualDownloadSpeed () {
374 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
375 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
376 if (lastDownloadSpeeds.length === 0) return -1
378 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
379 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
381 // Save the average bandwidth for future use
382 saveAverageBandwidth(averageBandwidth)
384 return averageBandwidth
387 private initializePlayer () {
388 if (isMobile()) this.player.addClass('vjs-is-mobile')
390 this.initSmoothProgressBar()
392 this.alterInactivity()
394 if (this.autoplay === true) {
395 this.player.posterImage.hide()
397 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
399 // Don't try on iOS that does not support MediaSource
401 this.currentVideoFile = this.pickAverageVideoFile()
402 return this.fallbackToHttp(undefined, false)
406 const oldPlay = this.player.play.bind(this.player)
407 this.player.play = () => {
408 this.player.addClass('vjs-has-big-play-button-clicked')
409 this.player.play = oldPlay
411 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
416 private runAutoQualityScheduler () {
417 this.autoQualityInterval = setInterval(() => {
419 // Not initialized or in HTTP fallback
420 if (this.torrent === undefined || this.torrent === null) return
421 if (this.isAutoResolutionOn() === false) return
422 if (this.isAutoResolutionObservation === true) return
424 const file = this.getAppropriateFile()
425 let changeResolution = false
426 let changeResolutionDelay = 0
429 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
430 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
431 changeResolution = true
432 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
433 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
434 changeResolution = true
435 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
438 if (changeResolution === true) {
439 this.updateResolution(file.resolution.id, changeResolutionDelay)
441 // Wait some seconds in observation of our new resolution
442 this.isAutoResolutionObservation = true
444 this.qualityObservationTimer = setTimeout(() => {
445 this.isAutoResolutionObservation = false
446 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
448 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
451 private isPlayerWaiting () {
452 return this.player && this.player.hasClass('vjs-waiting')
455 private runTorrentInfoScheduler () {
456 this.torrentInfoInterval = setInterval(() => {
457 // Not initialized yet
458 if (this.torrent === undefined) return
461 if (this.torrent === null) return this.trigger('torrentInfo', false)
463 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
464 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
466 return this.trigger('torrentInfo', {
467 downloadSpeed: this.torrent.downloadSpeed,
468 numPeers: this.torrent.numPeers,
469 uploadSpeed: this.torrent.uploadSpeed,
470 downloaded: this.torrent.downloaded,
471 uploaded: this.torrent.uploaded
473 }, this.CONSTANTS.INFO_SCHEDULER)
476 private runViewAdd () {
477 this.clearVideoViewInterval()
479 // After 30 seconds (or 3/4 of the video), add a view to the video
480 let minSecondsToView = 30
482 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
484 let secondsViewed = 0
485 this.videoViewInterval = setInterval(() => {
486 if (this.player && !this.player.paused()) {
489 if (secondsViewed > minSecondsToView) {
490 this.clearVideoViewInterval()
492 this.addViewToVideo().catch(err => console.error(err))
498 private clearVideoViewInterval () {
499 if (this.videoViewInterval !== undefined) {
500 clearInterval(this.videoViewInterval)
501 this.videoViewInterval = undefined
505 private addViewToVideo () {
506 if (!this.videoViewUrl) return Promise.resolve(undefined)
508 return fetch(this.videoViewUrl, { method: 'POST' })
511 private fallbackToHttp (done?: Function, play = true) {
512 this.flushVideoFile(this.currentVideoFile, true)
515 // Enable error display now this is our last fallback
516 this.player.one('error', () => this.enableErrorDisplay())
518 const httpUrl = this.currentVideoFile.fileUrl
519 this.player.src = this.savePlayerSrcFunction
520 this.player.src(httpUrl)
521 if (play) this.tryToPlay()
523 if (done) return done()
526 private handleError (err: Error | string) {
527 return this.player.trigger('customError', { err })
530 private enableErrorDisplay () {
531 this.player.addClass('vjs-error-display-enabled')
534 private disableErrorDisplay () {
535 this.player.removeClass('vjs-error-display-enabled')
539 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
542 private alterInactivity () {
543 let saveInactivityTimeout: number
545 const disableInactivity = () => {
546 saveInactivityTimeout = this.player.options_.inactivityTimeout
547 this.player.options_.inactivityTimeout = 0
549 const enableInactivity = () => {
550 this.player.options_.inactivityTimeout = saveInactivityTimeout
553 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
555 this.player.controlBar.on('mouseenter', () => disableInactivity())
556 settingsDialog.on('mouseenter', () => disableInactivity())
557 this.player.controlBar.on('mouseleave', () => enableInactivity())
558 settingsDialog.on('mouseleave', () => enableInactivity())
561 private pickAverageVideoFile () {
562 if (this.videoFiles.length === 1) return this.videoFiles[0]
564 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
567 private destroyFakeRenderer () {
568 if (this.fakeRenderer) {
569 if (this.fakeRenderer.destroy) {
571 this.fakeRenderer.destroy()
573 console.log('Cannot destroy correctly fake renderer.', err)
576 this.fakeRenderer = undefined
580 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
581 private initSmoothProgressBar () {
582 const SeekBar = videojsUntyped.getComponent('SeekBar')
583 SeekBar.prototype.getPercent = function getPercent () {
584 // Allows for smooth scrubbing, when player can't keep up.
585 // const time = (this.player_.scrubbing()) ?
586 // this.player_.getCache().currentTime :
587 // this.player_.currentTime()
588 const time = this.player_.currentTime()
589 const percent = time / this.player_.duration()
590 return percent >= 1 ? 1 : percent
592 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
593 let newTime = this.calculateDistance(event) * this.player_.duration()
594 if (newTime === this.player_.duration()) {
595 newTime = newTime - 0.1
597 this.player_.currentTime(newTime)
603 videojs.registerPlugin('peertube', PeerTubePlugin)
604 export { PeerTubePlugin }