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, UserWatching, VideoJSCaption, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { isMobile, timeToInt, videoFileMaxByResolution, videoFileMinByResolution } from './utils'
8 import * as CacheChunkStore from 'cache-chunk-store'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
11 getStoredWebTorrentEnabled,
12 getAverageBandwidthInStore,
18 } from './peertube-player-local-storage'
20 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
21 class PeerTubePlugin extends Plugin {
22 private readonly playerElement: HTMLVideoElement
24 private readonly autoplay: boolean = false
25 private readonly startTime: number = 0
26 private readonly savePlayerSrcFunction: Function
27 private readonly videoFiles: VideoFile[]
28 private readonly videoViewUrl: string
29 private readonly videoDuration: number
30 private readonly CONSTANTS = {
31 INFO_SCHEDULER: 1000, // Don't change this
32 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
33 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
34 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
35 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
36 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5, // Last 5 seconds to build average bandwidth
37 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
40 private readonly webtorrent = new WebTorrent({
45 urls: 'stun:stun.stunprotocol.org'
48 urls: 'stun:stun.framasoft.org'
57 private currentVideoFile: VideoFile
58 private torrent: WebTorrent.Torrent
59 private videoCaptions: VideoJSCaption[]
63 private destoyingFakeRenderer = false
65 private autoResolution = true
66 private forbidAutoResolution = false
67 private isAutoResolutionObservation = false
68 private playerRefusedP2P = false
70 private videoViewInterval
71 private torrentInfoInterval
72 private autoQualityInterval
73 private userWatchingVideoInterval
74 private addTorrentDelay
75 private qualityObservationTimer
76 private runAutoQualitySchedulerTimer
78 private downloadSpeeds: number[] = []
80 constructor (player: videojs.Player, options: PeertubePluginOptions) {
81 super(player, options)
83 // Disable auto play on iOS
84 this.autoplay = options.autoplay && this.isIOS() === false
85 this.playerRefusedP2P = !getStoredWebTorrentEnabled()
87 this.startTime = timeToInt(options.startTime)
88 this.videoFiles = options.videoFiles
89 this.videoViewUrl = options.videoViewUrl
90 this.videoDuration = options.videoDuration
91 this.videoCaptions = options.videoCaptions
93 this.savePlayerSrcFunction = this.player.src
94 this.playerElement = options.playerElement
96 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
98 this.player.ready(() => {
99 const volume = getStoredVolume()
100 if (volume !== undefined) this.player.volume(volume)
101 const muted = getStoredMute()
102 if (muted !== undefined) this.player.muted(muted)
104 this.initializePlayer()
105 this.runTorrentInfoScheduler()
108 if (options.userWatching) this.runUserWatchVideo(options.userWatching)
110 this.player.one('play', () => {
111 // Don't run immediately scheduler, wait some seconds the TCP connections are made
112 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
116 this.player.on('volumechange', () => {
117 saveVolumeInStore(this.player.volume())
118 saveMuteInStore(this.player.muted())
123 clearTimeout(this.addTorrentDelay)
124 clearTimeout(this.qualityObservationTimer)
125 clearTimeout(this.runAutoQualitySchedulerTimer)
127 clearInterval(this.videoViewInterval)
128 clearInterval(this.torrentInfoInterval)
129 clearInterval(this.autoQualityInterval)
131 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
133 // Don't need to destroy renderer, video player will be destroyed
134 this.flushVideoFile(this.currentVideoFile, false)
136 this.destroyFakeRenderer()
139 getCurrentResolutionId () {
140 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
143 getCurrentResolutionLabel () {
144 if (!this.currentVideoFile) return ''
146 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
147 return this.currentVideoFile.resolution.label + fps
151 videoFile?: VideoFile,
157 done: () => void = () => { /* empty */ }
159 // Automatically choose the adapted video file
160 if (videoFile === undefined) {
161 const savedAverageBandwidth = getAverageBandwidthInStore()
162 videoFile = savedAverageBandwidth
163 ? this.getAppropriateFile(savedAverageBandwidth)
164 : this.pickAverageVideoFile()
167 // Don't add the same video file once again
168 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
172 // Do not display error to user because we will have multiple fallback
173 this.disableErrorDisplay()
175 // Hack to "simulate" src link in video.js >= 6
176 // Without this, we can't play the video after pausing it
177 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
178 this.player.src = () => true
179 const oldPlaybackRate = this.player.playbackRate()
181 const previousVideoFile = this.currentVideoFile
182 this.currentVideoFile = videoFile
184 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
185 this.player.playbackRate(oldPlaybackRate)
189 this.trigger('videoFileUpdate')
192 updateResolution (resolutionId: number, delay = 0) {
193 // Remember player state
194 const currentTime = this.player.currentTime()
195 const isPaused = this.player.paused()
197 // Remove poster to have black background
198 this.playerElement.poster = ''
200 // Hide bigPlayButton
202 this.player.bigPlayButton.hide()
205 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
209 seek: currentTime + (delay / 1000)
211 this.updateVideoFile(newVideoFile, options)
214 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
215 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
216 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
218 this.webtorrent.remove(videoFile.magnetUri)
219 console.log('Removed ' + videoFile.magnetUri)
223 isAutoResolutionOn () {
224 return this.autoResolution
227 enableAutoResolution () {
228 this.autoResolution = true
229 this.trigger('autoResolutionUpdate')
232 disableAutoResolution (forbid = false) {
233 if (forbid === true) this.forbidAutoResolution = true
235 this.autoResolution = false
236 this.trigger('autoResolutionUpdate')
239 isAutoResolutionForbidden () {
240 return this.forbidAutoResolution === true
243 getCurrentVideoFile () {
244 return this.currentVideoFile
252 magnetOrTorrentUrl: string,
253 previousVideoFile: VideoFile,
261 console.log('Adding ' + magnetOrTorrentUrl + '.')
263 const oldTorrent = this.torrent
264 const torrentOptions = {
265 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
270 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
271 console.log('Added ' + magnetOrTorrentUrl + '.')
274 // Pause the old torrent
275 this.stopTorrent(oldTorrent)
277 // We use a fake renderer so we download correct pieces of the next file
278 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
281 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
282 this.addTorrentDelay = setTimeout(() => {
283 // We don't need the fake renderer anymore
284 this.destroyFakeRenderer()
286 const paused = this.player.paused()
288 this.flushVideoFile(previousVideoFile)
290 const renderVideoOptions = { autoplay: false, controls: true }
291 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
292 this.renderer = renderer
294 if (err || this.playerRefusedP2P) return this.fallbackToHttp(done)
296 return this.tryToPlay(err => {
297 if (err) return done(err)
299 if (options.seek) this.seek(options.seek)
300 if (options.forcePlay === false && paused === true) this.player.pause()
305 }, options.delay || 0)
308 this.torrent.on('error', err => console.error(err))
310 this.torrent.on('warning', (err: any) => {
311 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
312 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
314 // Users don't care about issues with WebRTC, but developers do so log it in the console
315 if (err.message.indexOf('Ice connection failed') !== -1) {
320 // Magnet hash is not up to date with the torrent file, add directly the torrent file
321 if (err.message.indexOf('incorrect info hash') !== -1) {
322 console.error('Incorrect info hash detected, falling back to torrent file.')
323 const newOptions = { forcePlay: true, seek: options.seek }
324 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
327 // Remote instance is down
328 if (err.message.indexOf('from xs param') !== -1) {
329 this.handleError(err)
336 private tryToPlay (done?: Function) {
337 if (!done) done = function () { /* empty */ }
339 const playPromise = this.player.play()
340 if (playPromise !== undefined) {
341 return playPromise.then(done)
343 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
349 this.player.posterImage.show()
350 this.player.removeClass('vjs-has-autoplay')
351 this.player.removeClass('vjs-has-big-play-button-clicked')
360 private seek (time: number) {
361 this.player.currentTime(time)
362 this.player.handleTechSeeked_()
365 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
366 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
367 if (this.videoFiles.length === 1) return this.videoFiles[0]
369 // Don't change the torrent is the play was ended
370 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
372 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
374 // Limit resolution according to player height
375 const playerHeight = this.playerElement.offsetHeight as number
377 // We take the first resolution just above the player height
378 // Example: player height is 530px, we want the 720p file instead of 480p
379 let maxResolution = this.videoFiles[0].resolution.id
380 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
381 const resolutionId = this.videoFiles[i].resolution.id
382 if (resolutionId >= playerHeight) {
383 maxResolution = resolutionId
388 // Filter videos we can play according to our screen resolution and bandwidth
389 const filteredFiles = this.videoFiles
390 .filter(f => f.resolution.id <= maxResolution)
392 const fileBitrate = (f.size / this.videoDuration)
393 let threshold = fileBitrate
395 // If this is for a higher resolution or an initial load: add a margin
396 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
397 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
400 return averageDownloadSpeed > threshold
403 // If the download speed is too bad, return the lowest resolution we have
404 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
406 return videoFileMaxByResolution(filteredFiles)
409 private getAndSaveActualDownloadSpeed () {
410 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
411 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
412 if (lastDownloadSpeeds.length === 0) return -1
414 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
415 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
417 // Save the average bandwidth for future use
418 saveAverageBandwidth(averageBandwidth)
420 return averageBandwidth
423 private initializePlayer () {
424 if (isMobile()) this.player.addClass('vjs-is-mobile')
426 this.initSmoothProgressBar()
430 this.alterInactivity()
432 if (this.autoplay === true) {
433 this.player.posterImage.hide()
435 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
438 // Don't try on iOS that does not support MediaSource
440 this.currentVideoFile = this.pickAverageVideoFile()
441 return this.fallbackToHttp(undefined, false)
445 const oldPlay = this.player.play.bind(this.player)
446 this.player.play = () => {
447 this.player.addClass('vjs-has-big-play-button-clicked')
448 this.player.play = oldPlay
450 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
454 private runAutoQualityScheduler () {
455 this.autoQualityInterval = setInterval(() => {
457 // Not initialized or in HTTP fallback
458 if (this.torrent === undefined || this.torrent === null) return
459 if (this.isAutoResolutionOn() === false) return
460 if (this.isAutoResolutionObservation === true) return
462 const file = this.getAppropriateFile()
463 let changeResolution = false
464 let changeResolutionDelay = 0
467 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
468 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
469 changeResolution = true
470 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
471 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
472 changeResolution = true
473 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
476 if (changeResolution === true) {
477 this.updateResolution(file.resolution.id, changeResolutionDelay)
479 // Wait some seconds in observation of our new resolution
480 this.isAutoResolutionObservation = true
482 this.qualityObservationTimer = setTimeout(() => {
483 this.isAutoResolutionObservation = false
484 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
486 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
489 private isPlayerWaiting () {
490 return this.player && this.player.hasClass('vjs-waiting')
493 private runTorrentInfoScheduler () {
494 this.torrentInfoInterval = setInterval(() => {
495 // Not initialized yet
496 if (this.torrent === undefined) return
499 if (this.torrent === null) return this.trigger('torrentInfo', false)
501 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
502 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
504 return this.trigger('torrentInfo', {
505 downloadSpeed: this.torrent.downloadSpeed,
506 numPeers: this.torrent.numPeers,
507 uploadSpeed: this.torrent.uploadSpeed,
508 downloaded: this.torrent.downloaded,
509 uploaded: this.torrent.uploaded
511 }, this.CONSTANTS.INFO_SCHEDULER)
514 private runViewAdd () {
515 this.clearVideoViewInterval()
517 // After 30 seconds (or 3/4 of the video), add a view to the video
518 let minSecondsToView = 30
520 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
522 let secondsViewed = 0
523 this.videoViewInterval = setInterval(() => {
524 if (this.player && !this.player.paused()) {
527 if (secondsViewed > minSecondsToView) {
528 this.clearVideoViewInterval()
530 this.addViewToVideo().catch(err => console.error(err))
536 private runUserWatchVideo (options: UserWatching) {
537 let lastCurrentTime = 0
539 this.userWatchingVideoInterval = setInterval(() => {
540 const currentTime = Math.floor(this.player.currentTime())
542 if (currentTime - lastCurrentTime >= 1) {
543 lastCurrentTime = currentTime
545 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
546 .catch(err => console.error('Cannot notify user is watching.', err))
548 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
551 private clearVideoViewInterval () {
552 if (this.videoViewInterval !== undefined) {
553 clearInterval(this.videoViewInterval)
554 this.videoViewInterval = undefined
558 private addViewToVideo () {
559 if (!this.videoViewUrl) return Promise.resolve(undefined)
561 return fetch(this.videoViewUrl, { method: 'POST' })
564 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
565 const body = new URLSearchParams()
566 body.append('currentTime', currentTime.toString())
568 const headers = new Headers({ 'Authorization': authorizationHeader })
570 return fetch(url, { method: 'PUT', body, headers })
573 private fallbackToHttp (done?: Function, play = true) {
574 this.disableAutoResolution(true)
576 this.flushVideoFile(this.currentVideoFile, true)
579 // Enable error display now this is our last fallback
580 this.player.one('error', () => this.enableErrorDisplay())
582 const httpUrl = this.currentVideoFile.fileUrl
583 this.player.src = this.savePlayerSrcFunction
584 this.player.src(httpUrl)
585 if (play) this.tryToPlay()
587 if (done) return done()
590 private handleError (err: Error | string) {
591 return this.player.trigger('customError', { err })
594 private enableErrorDisplay () {
595 this.player.addClass('vjs-error-display-enabled')
598 private disableErrorDisplay () {
599 this.player.removeClass('vjs-error-display-enabled')
603 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
606 private alterInactivity () {
607 let saveInactivityTimeout: number
609 const disableInactivity = () => {
610 saveInactivityTimeout = this.player.options_.inactivityTimeout
611 this.player.options_.inactivityTimeout = 0
613 const enableInactivity = () => {
614 this.player.options_.inactivityTimeout = saveInactivityTimeout
617 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
619 this.player.controlBar.on('mouseenter', () => disableInactivity())
620 settingsDialog.on('mouseenter', () => disableInactivity())
621 this.player.controlBar.on('mouseleave', () => enableInactivity())
622 settingsDialog.on('mouseleave', () => enableInactivity())
625 private pickAverageVideoFile () {
626 if (this.videoFiles.length === 1) return this.videoFiles[0]
628 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
631 private stopTorrent (torrent: WebTorrent.Torrent) {
633 // Pause does not remove actual peers (in particular the webseed peer)
634 torrent.removePeer(torrent[ 'ws' ])
637 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
638 this.destoyingFakeRenderer = false
640 const fakeVideoElem = document.createElement('video')
641 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
642 this.fakeRenderer = renderer
644 // The renderer returns an error when we destroy it, so skip them
645 if (this.destoyingFakeRenderer === false && err) {
646 console.error('Cannot render new torrent in fake video element.', err)
649 // Load the future file at the correct time (in delay MS - 2 seconds)
650 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
654 private destroyFakeRenderer () {
655 if (this.fakeRenderer) {
656 this.destoyingFakeRenderer = true
658 if (this.fakeRenderer.destroy) {
660 this.fakeRenderer.destroy()
662 console.log('Cannot destroy correctly fake renderer.', err)
665 this.fakeRenderer = undefined
669 private initCaptions () {
670 for (const caption of this.videoCaptions) {
671 this.player.addRemoteTextTrack({
673 label: caption.label,
674 language: caption.language,
675 id: caption.language,
681 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
682 private initSmoothProgressBar () {
683 const SeekBar = videojsUntyped.getComponent('SeekBar')
684 SeekBar.prototype.getPercent = function getPercent () {
685 // Allows for smooth scrubbing, when player can't keep up.
686 // const time = (this.player_.scrubbing()) ?
687 // this.player_.getCache().currentTime :
688 // this.player_.currentTime()
689 const time = this.player_.currentTime()
690 const percent = time / this.player_.duration()
691 return percent >= 1 ? 1 : percent
693 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
694 let newTime = this.calculateDistance(event) * this.player_.duration()
695 if (newTime === this.player_.duration()) {
696 newTime = newTime - 0.1
698 this.player_.currentTime(newTime)
704 videojs.registerPlugin('peertube', PeerTubePlugin)
705 export { PeerTubePlugin }