1 // FIXME: something weird with our path definition in tsconfig and typings
3 import * as videojs from 'video.js'
5 import * as WebTorrent from 'webtorrent'
6 import { VideoFile } from '../../../../shared/models/videos/video.model'
7 import { renderVideo } from './video-renderer'
8 import './settings-menu-button'
9 import { PeertubePluginOptions, UserWatching, VideoJSCaption, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
10 import { isMobile, timeToInt, videoFileMaxByResolution, videoFileMinByResolution } from './utils'
11 import { PeertubeChunkStore } from './peertube-chunk-store'
13 getAverageBandwidthInStore,
16 getStoredWebTorrentEnabled,
20 } from './peertube-player-local-storage'
22 const CacheChunkStore = require('cache-chunk-store')
30 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
31 class PeerTubePlugin extends Plugin {
32 private readonly playerElement: HTMLVideoElement
34 private readonly autoplay: boolean = false
35 private readonly startTime: number = 0
36 private readonly savePlayerSrcFunction: Function
37 private readonly videoFiles: VideoFile[]
38 private readonly videoViewUrl: string
39 private readonly videoDuration: number
40 private readonly CONSTANTS = {
41 INFO_SCHEDULER: 1000, // Don't change this
42 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
43 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
44 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
45 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
46 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5, // Last 5 seconds to build average bandwidth
47 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
50 private readonly webtorrent = new WebTorrent({
55 urls: 'stun:stun.stunprotocol.org'
58 urls: 'stun:stun.framasoft.org'
67 private currentVideoFile: VideoFile
68 private torrent: WebTorrent.Torrent
69 private videoCaptions: VideoJSCaption[]
72 private fakeRenderer: any
73 private destoyingFakeRenderer = false
75 private autoResolution = true
76 private forbidAutoResolution = false
77 private isAutoResolutionObservation = false
78 private playerRefusedP2P = false
80 private videoViewInterval: any
81 private torrentInfoInterval: any
82 private autoQualityInterval: any
83 private userWatchingVideoInterval: any
84 private addTorrentDelay: any
85 private qualityObservationTimer: any
86 private runAutoQualitySchedulerTimer: any
88 private downloadSpeeds: number[] = []
90 constructor (player: videojs.Player, options: PeertubePluginOptions) {
91 super(player, options)
93 // Disable auto play on iOS
94 this.autoplay = options.autoplay && this.isIOS() === false
95 this.playerRefusedP2P = !getStoredWebTorrentEnabled()
97 this.startTime = timeToInt(options.startTime)
98 this.videoFiles = options.videoFiles
99 this.videoViewUrl = options.videoViewUrl
100 this.videoDuration = options.videoDuration
101 this.videoCaptions = options.videoCaptions
103 this.savePlayerSrcFunction = this.player.src
104 this.playerElement = options.playerElement
106 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
108 this.player.ready(() => {
109 const volume = getStoredVolume()
110 if (volume !== undefined) this.player.volume(volume)
111 const muted = getStoredMute()
112 if (muted !== undefined) this.player.muted(muted)
114 this.initializePlayer()
115 this.runTorrentInfoScheduler()
118 if (options.userWatching) this.runUserWatchVideo(options.userWatching)
120 this.player.one('play', () => {
121 // Don't run immediately scheduler, wait some seconds the TCP connections are made
122 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
126 this.player.on('volumechange', () => {
127 saveVolumeInStore(this.player.volume())
128 saveMuteInStore(this.player.muted())
133 clearTimeout(this.addTorrentDelay)
134 clearTimeout(this.qualityObservationTimer)
135 clearTimeout(this.runAutoQualitySchedulerTimer)
137 clearInterval(this.videoViewInterval)
138 clearInterval(this.torrentInfoInterval)
139 clearInterval(this.autoQualityInterval)
141 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
143 // Don't need to destroy renderer, video player will be destroyed
144 this.flushVideoFile(this.currentVideoFile, false)
146 this.destroyFakeRenderer()
149 getCurrentResolutionId () {
150 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
153 getCurrentResolutionLabel () {
154 if (!this.currentVideoFile) return ''
156 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
157 return this.currentVideoFile.resolution.label + fps
161 videoFile?: VideoFile,
167 done: () => void = () => { /* empty */ }
169 // Automatically choose the adapted video file
170 if (videoFile === undefined) {
171 const savedAverageBandwidth = getAverageBandwidthInStore()
172 videoFile = savedAverageBandwidth
173 ? this.getAppropriateFile(savedAverageBandwidth)
174 : this.pickAverageVideoFile()
177 // Don't add the same video file once again
178 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
182 // Do not display error to user because we will have multiple fallback
183 this.disableErrorDisplay()
185 // Hack to "simulate" src link in video.js >= 6
186 // Without this, we can't play the video after pausing it
187 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
188 this.player.src = () => true
189 const oldPlaybackRate = this.player.playbackRate()
191 const previousVideoFile = this.currentVideoFile
192 this.currentVideoFile = videoFile
194 // Don't try on iOS that does not support MediaSource
195 // Or don't use P2P if webtorrent is disabled
196 if (this.isIOS() || this.playerRefusedP2P) {
197 return this.fallbackToHttp(options, () => {
198 this.player.playbackRate(oldPlaybackRate)
203 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
204 this.player.playbackRate(oldPlaybackRate)
208 this.trigger('videoFileUpdate')
211 updateResolution (resolutionId: number, delay = 0) {
212 // Remember player state
213 const currentTime = this.player.currentTime()
214 const isPaused = this.player.paused()
216 // Remove poster to have black background
217 this.playerElement.poster = ''
219 // Hide bigPlayButton
221 this.player.bigPlayButton.hide()
224 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
228 seek: currentTime + (delay / 1000)
230 this.updateVideoFile(newVideoFile, options)
233 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
234 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
235 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
237 this.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 (forbid = false) {
252 if (forbid === true) this.forbidAutoResolution = true
254 this.autoResolution = false
255 this.trigger('autoResolutionUpdate')
258 isAutoResolutionForbidden () {
259 return this.forbidAutoResolution === true
262 getCurrentVideoFile () {
263 return this.currentVideoFile
271 magnetOrTorrentUrl: string,
272 previousVideoFile: VideoFile,
273 options: PlayOptions,
276 console.log('Adding ' + magnetOrTorrentUrl + '.')
278 const oldTorrent = this.torrent
279 const torrentOptions = {
280 store: (chunkLength: number, storeOpts: any) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
285 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
286 console.log('Added ' + magnetOrTorrentUrl + '.')
289 // Pause the old torrent
290 this.stopTorrent(oldTorrent)
292 // We use a fake renderer so we download correct pieces of the next file
293 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
296 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
297 this.addTorrentDelay = setTimeout(() => {
298 // We don't need the fake renderer anymore
299 this.destroyFakeRenderer()
301 const paused = this.player.paused()
303 this.flushVideoFile(previousVideoFile)
305 const renderVideoOptions = { autoplay: false, controls: true }
306 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
307 this.renderer = renderer
309 if (err) return this.fallbackToHttp(options, done)
311 return this.tryToPlay(err => {
312 if (err) return done(err)
314 if (options.seek) this.seek(options.seek)
315 if (options.forcePlay === false && paused === true) this.player.pause()
320 }, options.delay || 0)
323 this.torrent.on('error', (err: any) => console.error(err))
325 this.torrent.on('warning', (err: any) => {
326 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
327 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
329 // Users don't care about issues with WebRTC, but developers do so log it in the console
330 if (err.message.indexOf('Ice connection failed') !== -1) {
335 // Magnet hash is not up to date with the torrent file, add directly the torrent file
336 if (err.message.indexOf('incorrect info hash') !== -1) {
337 console.error('Incorrect info hash detected, falling back to torrent file.')
338 const newOptions = { forcePlay: true, seek: options.seek }
339 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
342 // Remote instance is down
343 if (err.message.indexOf('from xs param') !== -1) {
344 this.handleError(err)
351 private tryToPlay (done?: (err?: Error) => void) {
352 if (!done) done = function () { /* empty */ }
354 const playPromise = this.player.play()
355 if (playPromise !== undefined) {
356 return playPromise.then(done)
357 .catch((err: Error) => {
358 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
364 this.player.posterImage.show()
365 this.player.removeClass('vjs-has-autoplay')
366 this.player.removeClass('vjs-has-big-play-button-clicked')
375 private seek (time: number) {
376 this.player.currentTime(time)
377 this.player.handleTechSeeked_()
380 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
381 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
382 if (this.videoFiles.length === 1) return this.videoFiles[0]
384 // Don't change the torrent is the play was ended
385 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
387 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
389 // Limit resolution according to player height
390 const playerHeight = this.playerElement.offsetHeight as number
392 // We take the first resolution just above the player height
393 // Example: player height is 530px, we want the 720p file instead of 480p
394 let maxResolution = this.videoFiles[0].resolution.id
395 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
396 const resolutionId = this.videoFiles[i].resolution.id
397 if (resolutionId >= playerHeight) {
398 maxResolution = resolutionId
403 // Filter videos we can play according to our screen resolution and bandwidth
404 const filteredFiles = this.videoFiles
405 .filter(f => f.resolution.id <= maxResolution)
407 const fileBitrate = (f.size / this.videoDuration)
408 let threshold = fileBitrate
410 // If this is for a higher resolution or an initial load: add a margin
411 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
412 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
415 return averageDownloadSpeed > threshold
418 // If the download speed is too bad, return the lowest resolution we have
419 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
421 return videoFileMaxByResolution(filteredFiles)
424 private getAndSaveActualDownloadSpeed () {
425 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
426 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
427 if (lastDownloadSpeeds.length === 0) return -1
429 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
430 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
432 // Save the average bandwidth for future use
433 saveAverageBandwidth(averageBandwidth)
435 return averageBandwidth
438 private initializePlayer () {
439 if (isMobile()) this.player.addClass('vjs-is-mobile')
441 this.initSmoothProgressBar()
445 this.alterInactivity()
447 if (this.autoplay === true) {
448 this.player.posterImage.hide()
450 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
454 const oldPlay = this.player.play.bind(this.player)
455 this.player.play = () => {
456 this.player.addClass('vjs-has-big-play-button-clicked')
457 this.player.play = oldPlay
459 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
463 private runAutoQualityScheduler () {
464 this.autoQualityInterval = setInterval(() => {
466 // Not initialized or in HTTP fallback
467 if (this.torrent === undefined || this.torrent === null) return
468 if (this.isAutoResolutionOn() === false) return
469 if (this.isAutoResolutionObservation === true) return
471 const file = this.getAppropriateFile()
472 let changeResolution = false
473 let changeResolutionDelay = 0
476 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
477 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
478 changeResolution = true
479 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
480 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
481 changeResolution = true
482 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
485 if (changeResolution === true) {
486 this.updateResolution(file.resolution.id, changeResolutionDelay)
488 // Wait some seconds in observation of our new resolution
489 this.isAutoResolutionObservation = true
491 this.qualityObservationTimer = setTimeout(() => {
492 this.isAutoResolutionObservation = false
493 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
495 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
498 private isPlayerWaiting () {
499 return this.player && this.player.hasClass('vjs-waiting')
502 private runTorrentInfoScheduler () {
503 this.torrentInfoInterval = setInterval(() => {
504 // Not initialized yet
505 if (this.torrent === undefined) return
508 if (this.torrent === null) return this.trigger('torrentInfo', false)
510 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
511 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
513 return this.trigger('torrentInfo', {
514 downloadSpeed: this.torrent.downloadSpeed,
515 numPeers: this.torrent.numPeers,
516 uploadSpeed: this.torrent.uploadSpeed,
517 downloaded: this.torrent.downloaded,
518 uploaded: this.torrent.uploaded
520 }, this.CONSTANTS.INFO_SCHEDULER)
523 private runViewAdd () {
524 this.clearVideoViewInterval()
526 // After 30 seconds (or 3/4 of the video), add a view to the video
527 let minSecondsToView = 30
529 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
531 let secondsViewed = 0
532 this.videoViewInterval = setInterval(() => {
533 if (this.player && !this.player.paused()) {
536 if (secondsViewed > minSecondsToView) {
537 this.clearVideoViewInterval()
539 this.addViewToVideo().catch(err => console.error(err))
545 private runUserWatchVideo (options: UserWatching) {
546 let lastCurrentTime = 0
548 this.userWatchingVideoInterval = setInterval(() => {
549 const currentTime = Math.floor(this.player.currentTime())
551 if (currentTime - lastCurrentTime >= 1) {
552 lastCurrentTime = currentTime
554 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
555 .catch(err => console.error('Cannot notify user is watching.', err))
557 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
560 private clearVideoViewInterval () {
561 if (this.videoViewInterval !== undefined) {
562 clearInterval(this.videoViewInterval)
563 this.videoViewInterval = undefined
567 private addViewToVideo () {
568 if (!this.videoViewUrl) return Promise.resolve(undefined)
570 return fetch(this.videoViewUrl, { method: 'POST' })
573 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
574 const body = new URLSearchParams()
575 body.append('currentTime', currentTime.toString())
577 const headers = new Headers({ 'Authorization': authorizationHeader })
579 return fetch(url, { method: 'PUT', body, headers })
582 private fallbackToHttp (options: PlayOptions, done?: Function) {
583 const paused = this.player.paused()
585 this.disableAutoResolution(true)
587 this.flushVideoFile(this.currentVideoFile, true)
590 // Enable error display now this is our last fallback
591 this.player.one('error', () => this.enableErrorDisplay())
593 const httpUrl = this.currentVideoFile.fileUrl
594 this.player.src = this.savePlayerSrcFunction
595 this.player.src(httpUrl)
597 return this.tryToPlay(err => {
598 if (err && done) return done(err)
600 if (options.seek) this.seek(options.seek)
601 if (options.forcePlay === false && paused === true) this.player.pause()
603 if (done) return done()
607 private handleError (err: Error | string) {
608 return this.player.trigger('customError', { err })
611 private enableErrorDisplay () {
612 this.player.addClass('vjs-error-display-enabled')
615 private disableErrorDisplay () {
616 this.player.removeClass('vjs-error-display-enabled')
620 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
623 private alterInactivity () {
624 let saveInactivityTimeout: number
626 const disableInactivity = () => {
627 saveInactivityTimeout = this.player.options_.inactivityTimeout
628 this.player.options_.inactivityTimeout = 0
630 const enableInactivity = () => {
631 this.player.options_.inactivityTimeout = saveInactivityTimeout
634 const settingsDialog = this.player.children_.find((c: any) => c.name_ === 'SettingsDialog')
636 this.player.controlBar.on('mouseenter', () => disableInactivity())
637 settingsDialog.on('mouseenter', () => disableInactivity())
638 this.player.controlBar.on('mouseleave', () => enableInactivity())
639 settingsDialog.on('mouseleave', () => enableInactivity())
642 private pickAverageVideoFile () {
643 if (this.videoFiles.length === 1) return this.videoFiles[0]
645 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
648 private stopTorrent (torrent: WebTorrent.Torrent) {
650 // Pause does not remove actual peers (in particular the webseed peer)
651 torrent.removePeer(torrent[ 'ws' ])
654 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
655 this.destoyingFakeRenderer = false
657 const fakeVideoElem = document.createElement('video')
658 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
659 this.fakeRenderer = renderer
661 // The renderer returns an error when we destroy it, so skip them
662 if (this.destoyingFakeRenderer === false && err) {
663 console.error('Cannot render new torrent in fake video element.', err)
666 // Load the future file at the correct time (in delay MS - 2 seconds)
667 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
671 private destroyFakeRenderer () {
672 if (this.fakeRenderer) {
673 this.destoyingFakeRenderer = true
675 if (this.fakeRenderer.destroy) {
677 this.fakeRenderer.destroy()
679 console.log('Cannot destroy correctly fake renderer.', err)
682 this.fakeRenderer = undefined
686 private initCaptions () {
687 for (const caption of this.videoCaptions) {
688 this.player.addRemoteTextTrack({
690 label: caption.label,
691 language: caption.language,
692 id: caption.language,
698 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
699 private initSmoothProgressBar () {
700 const SeekBar = videojsUntyped.getComponent('SeekBar')
701 SeekBar.prototype.getPercent = function getPercent () {
702 // Allows for smooth scrubbing, when player can't keep up.
703 // const time = (this.player_.scrubbing()) ?
704 // this.player_.getCache().currentTime :
705 // this.player_.currentTime()
706 const time = this.player_.currentTime()
707 const percent = time / this.player_.duration()
708 return percent >= 1 ? 1 : percent
710 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
711 let newTime = this.calculateDistance(event) * this.player_.duration()
712 if (newTime === this.player_.duration()) {
713 newTime = newTime - 0.1
715 this.player_.currentTime(newTime)
721 videojs.registerPlugin('peertube', PeerTubePlugin)
722 export { PeerTubePlugin }