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, 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 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
57 private videoCaptions: VideoJSCaption[]
61 private destoyingFakeRenderer = false
63 private autoResolution = true
64 private forbidAutoResolution = false
65 private isAutoResolutionObservation = false
67 private videoViewInterval
68 private torrentInfoInterval
69 private autoQualityInterval
70 private addTorrentDelay
71 private qualityObservationTimer
72 private runAutoQualitySchedulerTimer
74 private downloadSpeeds: number[] = []
76 constructor (player: videojs.Player, options: PeertubePluginOptions) {
77 super(player, options)
79 // Disable auto play on iOS
80 this.autoplay = options.autoplay && this.isIOS() === false
82 this.startTime = timeToInt(options.startTime)
83 this.videoFiles = options.videoFiles
84 this.videoViewUrl = options.videoViewUrl
85 this.videoDuration = options.videoDuration
86 this.videoCaptions = options.videoCaptions
88 this.savePlayerSrcFunction = this.player.src
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(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
109 this.player.on('volumechange', () => {
110 saveVolumeInStore(this.player.volume())
111 saveMuteInStore(this.player.muted())
116 clearTimeout(this.addTorrentDelay)
117 clearTimeout(this.qualityObservationTimer)
118 clearTimeout(this.runAutoQualitySchedulerTimer)
120 clearInterval(this.videoViewInterval)
121 clearInterval(this.torrentInfoInterval)
122 clearInterval(this.autoQualityInterval)
124 // Don't need to destroy renderer, video player will be destroyed
125 this.flushVideoFile(this.currentVideoFile, false)
127 this.destroyFakeRenderer()
130 getCurrentResolutionId () {
131 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
134 getCurrentResolutionLabel () {
135 if (!this.currentVideoFile) return ''
137 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
138 return this.currentVideoFile.resolution.label + fps
142 videoFile?: VideoFile,
148 done: () => void = () => { /* empty */ }
150 // Automatically choose the adapted video file
151 if (videoFile === undefined) {
152 const savedAverageBandwidth = getAverageBandwidthInStore()
153 videoFile = savedAverageBandwidth
154 ? this.getAppropriateFile(savedAverageBandwidth)
155 : this.pickAverageVideoFile()
158 // Don't add the same video file once again
159 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
163 // Do not display error to user because we will have multiple fallback
164 this.disableErrorDisplay()
166 // Hack to "simulate" src link in video.js >= 6
167 // Without this, we can't play the video after pausing it
168 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
169 this.player.src = () => true
170 const oldPlaybackRate = this.player.playbackRate()
172 const previousVideoFile = this.currentVideoFile
173 this.currentVideoFile = videoFile
175 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
176 this.player.playbackRate(oldPlaybackRate)
180 this.trigger('videoFileUpdate')
183 updateResolution (resolutionId: number, delay = 0) {
184 // Remember player state
185 const currentTime = this.player.currentTime()
186 const isPaused = this.player.paused()
188 // Remove poster to have black background
189 this.playerElement.poster = ''
191 // Hide bigPlayButton
193 this.player.bigPlayButton.hide()
196 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
200 seek: currentTime + (delay / 1000)
202 this.updateVideoFile(newVideoFile, options)
205 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
206 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
207 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
209 this.webtorrent.remove(videoFile.magnetUri)
210 console.log('Removed ' + videoFile.magnetUri)
214 isAutoResolutionOn () {
215 return this.autoResolution
218 enableAutoResolution () {
219 this.autoResolution = true
220 this.trigger('autoResolutionUpdate')
223 disableAutoResolution (forbid = false) {
224 if (forbid === true) this.forbidAutoResolution = true
226 this.autoResolution = false
227 this.trigger('autoResolutionUpdate')
230 isAutoResolutionForbidden () {
231 return this.forbidAutoResolution === true
234 getCurrentVideoFile () {
235 return this.currentVideoFile
243 magnetOrTorrentUrl: string,
244 previousVideoFile: VideoFile,
252 console.log('Adding ' + magnetOrTorrentUrl + '.')
254 const oldTorrent = this.torrent
255 const torrentOptions = {
256 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
261 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
262 console.log('Added ' + magnetOrTorrentUrl + '.')
265 // Pause the old torrent
266 this.stopTorrent(oldTorrent)
268 // We use a fake renderer so we download correct pieces of the next file
269 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
272 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
273 this.addTorrentDelay = setTimeout(() => {
274 // We don't need the fake renderer anymore
275 this.destroyFakeRenderer()
277 const paused = this.player.paused()
279 this.flushVideoFile(previousVideoFile)
281 const renderVideoOptions = { autoplay: false, controls: true }
282 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
283 this.renderer = renderer
285 if (err) return this.fallbackToHttp(done)
287 return this.tryToPlay(err => {
288 if (err) return done(err)
290 if (options.seek) this.seek(options.seek)
291 if (options.forcePlay === false && paused === true) this.player.pause()
296 }, options.delay || 0)
299 this.torrent.on('error', err => console.error(err))
301 this.torrent.on('warning', (err: any) => {
302 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
303 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
305 // Users don't care about issues with WebRTC, but developers do so log it in the console
306 if (err.message.indexOf('Ice connection failed') !== -1) {
311 // Magnet hash is not up to date with the torrent file, add directly the torrent file
312 if (err.message.indexOf('incorrect info hash') !== -1) {
313 console.error('Incorrect info hash detected, falling back to torrent file.')
314 const newOptions = { forcePlay: true, seek: options.seek }
315 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
318 // Remote instance is down
319 if (err.message.indexOf('from xs param') !== -1) {
320 this.handleError(err)
327 private tryToPlay (done?: Function) {
328 if (!done) done = function () { /* empty */ }
330 const playPromise = this.player.play()
331 if (playPromise !== undefined) {
332 return playPromise.then(done)
334 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
340 this.player.posterImage.show()
341 this.player.removeClass('vjs-has-autoplay')
342 this.player.removeClass('vjs-has-big-play-button-clicked')
351 private seek (time: number) {
352 this.player.currentTime(time)
353 this.player.handleTechSeeked_()
356 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
357 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
358 if (this.videoFiles.length === 1) return this.videoFiles[0]
360 // Don't change the torrent is the play was ended
361 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
363 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
365 // Limit resolution according to player height
366 const playerHeight = this.playerElement.offsetHeight as number
368 // We take the first resolution just above the player height
369 // Example: player height is 530px, we want the 720p file instead of 480p
370 let maxResolution = this.videoFiles[0].resolution.id
371 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
372 const resolutionId = this.videoFiles[i].resolution.id
373 if (resolutionId >= playerHeight) {
374 maxResolution = resolutionId
379 // Filter videos we can play according to our screen resolution and bandwidth
380 const filteredFiles = this.videoFiles
381 .filter(f => f.resolution.id <= maxResolution)
383 const fileBitrate = (f.size / this.videoDuration)
384 let threshold = fileBitrate
386 // If this is for a higher resolution or an initial load: add a margin
387 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
388 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
391 return averageDownloadSpeed > threshold
394 // If the download speed is too bad, return the lowest resolution we have
395 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
397 return videoFileMaxByResolution(filteredFiles)
400 private getAndSaveActualDownloadSpeed () {
401 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
402 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
403 if (lastDownloadSpeeds.length === 0) return -1
405 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
406 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
408 // Save the average bandwidth for future use
409 saveAverageBandwidth(averageBandwidth)
411 return averageBandwidth
414 private initializePlayer () {
415 if (isMobile()) this.player.addClass('vjs-is-mobile')
417 this.initSmoothProgressBar()
421 this.alterInactivity()
423 if (this.autoplay === true) {
424 this.player.posterImage.hide()
426 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
429 // Don't try on iOS that does not support MediaSource
431 this.currentVideoFile = this.pickAverageVideoFile()
432 return this.fallbackToHttp(undefined, false)
436 const oldPlay = this.player.play.bind(this.player)
437 this.player.play = () => {
438 this.player.addClass('vjs-has-big-play-button-clicked')
439 this.player.play = oldPlay
441 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
445 private runAutoQualityScheduler () {
446 this.autoQualityInterval = setInterval(() => {
448 // Not initialized or in HTTP fallback
449 if (this.torrent === undefined || this.torrent === null) return
450 if (this.isAutoResolutionOn() === false) return
451 if (this.isAutoResolutionObservation === true) return
453 const file = this.getAppropriateFile()
454 let changeResolution = false
455 let changeResolutionDelay = 0
458 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
459 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
460 changeResolution = true
461 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
462 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
463 changeResolution = true
464 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
467 if (changeResolution === true) {
468 this.updateResolution(file.resolution.id, changeResolutionDelay)
470 // Wait some seconds in observation of our new resolution
471 this.isAutoResolutionObservation = true
473 this.qualityObservationTimer = setTimeout(() => {
474 this.isAutoResolutionObservation = false
475 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
477 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
480 private isPlayerWaiting () {
481 return this.player && this.player.hasClass('vjs-waiting')
484 private runTorrentInfoScheduler () {
485 this.torrentInfoInterval = setInterval(() => {
486 // Not initialized yet
487 if (this.torrent === undefined) return
490 if (this.torrent === null) return this.trigger('torrentInfo', false)
492 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
493 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
495 return this.trigger('torrentInfo', {
496 downloadSpeed: this.torrent.downloadSpeed,
497 numPeers: this.torrent.numPeers,
498 uploadSpeed: this.torrent.uploadSpeed,
499 downloaded: this.torrent.downloaded,
500 uploaded: this.torrent.uploaded
502 }, this.CONSTANTS.INFO_SCHEDULER)
505 private runViewAdd () {
506 this.clearVideoViewInterval()
508 // After 30 seconds (or 3/4 of the video), add a view to the video
509 let minSecondsToView = 30
511 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
513 let secondsViewed = 0
514 this.videoViewInterval = setInterval(() => {
515 if (this.player && !this.player.paused()) {
518 if (secondsViewed > minSecondsToView) {
519 this.clearVideoViewInterval()
521 this.addViewToVideo().catch(err => console.error(err))
527 private clearVideoViewInterval () {
528 if (this.videoViewInterval !== undefined) {
529 clearInterval(this.videoViewInterval)
530 this.videoViewInterval = undefined
534 private addViewToVideo () {
535 if (!this.videoViewUrl) return Promise.resolve(undefined)
537 return fetch(this.videoViewUrl, { method: 'POST' })
540 private fallbackToHttp (done?: Function, play = true) {
541 this.disableAutoResolution(true)
543 this.flushVideoFile(this.currentVideoFile, true)
546 // Enable error display now this is our last fallback
547 this.player.one('error', () => this.enableErrorDisplay())
549 const httpUrl = this.currentVideoFile.fileUrl
550 this.player.src = this.savePlayerSrcFunction
551 this.player.src(httpUrl)
552 if (play) this.tryToPlay()
554 if (done) return done()
557 private handleError (err: Error | string) {
558 return this.player.trigger('customError', { err })
561 private enableErrorDisplay () {
562 this.player.addClass('vjs-error-display-enabled')
565 private disableErrorDisplay () {
566 this.player.removeClass('vjs-error-display-enabled')
570 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
573 private alterInactivity () {
574 let saveInactivityTimeout: number
576 const disableInactivity = () => {
577 saveInactivityTimeout = this.player.options_.inactivityTimeout
578 this.player.options_.inactivityTimeout = 0
580 const enableInactivity = () => {
581 this.player.options_.inactivityTimeout = saveInactivityTimeout
584 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
586 this.player.controlBar.on('mouseenter', () => disableInactivity())
587 settingsDialog.on('mouseenter', () => disableInactivity())
588 this.player.controlBar.on('mouseleave', () => enableInactivity())
589 settingsDialog.on('mouseleave', () => enableInactivity())
592 private pickAverageVideoFile () {
593 if (this.videoFiles.length === 1) return this.videoFiles[0]
595 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
598 private stopTorrent (torrent: WebTorrent.Torrent) {
600 // Pause does not remove actual peers (in particular the webseed peer)
601 torrent.removePeer(torrent[ 'ws' ])
604 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
605 this.destoyingFakeRenderer = false
607 const fakeVideoElem = document.createElement('video')
608 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
609 this.fakeRenderer = renderer
611 // The renderer returns an error when we destroy it, so skip them
612 if (this.destoyingFakeRenderer === false && err) {
613 console.error('Cannot render new torrent in fake video element.', err)
616 // Load the future file at the correct time (in delay MS - 2 seconds)
617 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
621 private destroyFakeRenderer () {
622 if (this.fakeRenderer) {
623 this.destoyingFakeRenderer = true
625 if (this.fakeRenderer.destroy) {
627 this.fakeRenderer.destroy()
629 console.log('Cannot destroy correctly fake renderer.', err)
632 this.fakeRenderer = undefined
636 private initCaptions () {
637 for (const caption of this.videoCaptions) {
638 this.player.addRemoteTextTrack({
640 label: caption.label,
641 language: caption.language,
642 id: caption.language,
648 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
649 private initSmoothProgressBar () {
650 const SeekBar = videojsUntyped.getComponent('SeekBar')
651 SeekBar.prototype.getPercent = function getPercent () {
652 // Allows for smooth scrubbing, when player can't keep up.
653 // const time = (this.player_.scrubbing()) ?
654 // this.player_.getCache().currentTime :
655 // this.player_.currentTime()
656 const time = this.player_.currentTime()
657 const percent = time / this.player_.duration()
658 return percent >= 1 ? 1 : percent
660 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
661 let newTime = this.calculateDistance(event) * this.player_.duration()
662 if (newTime === this.player_.duration()) {
663 newTime = newTime - 0.1
665 this.player_.currentTime(newTime)
671 videojs.registerPlugin('peertube', PeerTubePlugin)
672 export { PeerTubePlugin }