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 getStoredWebTorrentPolicy,
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
86 this.startTime = timeToInt(options.startTime)
87 this.videoFiles = options.videoFiles
88 this.videoViewUrl = options.videoViewUrl
89 this.videoDuration = options.videoDuration
90 this.videoCaptions = options.videoCaptions
92 this.savePlayerSrcFunction = this.player.src
93 this.playerElement = options.playerElement
95 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
97 this.player.ready(() => {
98 const volume = getStoredVolume()
99 if (volume !== undefined) this.player.volume(volume)
100 const muted = getStoredMute()
101 if (muted !== undefined) this.player.muted(muted)
102 this.playerRefusedP2P = getStoredWebTorrentPolicy() || false
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 console.log('value this.playerRefusedP2P', this.playerRefusedP2P)
295 if (err || this.playerRefusedP2P) return this.fallbackToHttp(done)
297 return this.tryToPlay(err => {
298 if (err) return done(err)
300 if (options.seek) this.seek(options.seek)
301 if (options.forcePlay === false && paused === true) this.player.pause()
306 }, options.delay || 0)
309 this.torrent.on('error', err => console.error(err))
311 this.torrent.on('warning', (err: any) => {
312 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
313 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
315 // Users don't care about issues with WebRTC, but developers do so log it in the console
316 if (err.message.indexOf('Ice connection failed') !== -1) {
321 // Magnet hash is not up to date with the torrent file, add directly the torrent file
322 if (err.message.indexOf('incorrect info hash') !== -1) {
323 console.error('Incorrect info hash detected, falling back to torrent file.')
324 const newOptions = { forcePlay: true, seek: options.seek }
325 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
328 // Remote instance is down
329 if (err.message.indexOf('from xs param') !== -1) {
330 this.handleError(err)
337 private tryToPlay (done?: Function) {
338 if (!done) done = function () { /* empty */ }
340 const playPromise = this.player.play()
341 if (playPromise !== undefined) {
342 return playPromise.then(done)
344 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
350 this.player.posterImage.show()
351 this.player.removeClass('vjs-has-autoplay')
352 this.player.removeClass('vjs-has-big-play-button-clicked')
361 private seek (time: number) {
362 this.player.currentTime(time)
363 this.player.handleTechSeeked_()
366 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
367 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
368 if (this.videoFiles.length === 1) return this.videoFiles[0]
370 // Don't change the torrent is the play was ended
371 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
373 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
375 // Limit resolution according to player height
376 const playerHeight = this.playerElement.offsetHeight as number
378 // We take the first resolution just above the player height
379 // Example: player height is 530px, we want the 720p file instead of 480p
380 let maxResolution = this.videoFiles[0].resolution.id
381 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
382 const resolutionId = this.videoFiles[i].resolution.id
383 if (resolutionId >= playerHeight) {
384 maxResolution = resolutionId
389 // Filter videos we can play according to our screen resolution and bandwidth
390 const filteredFiles = this.videoFiles
391 .filter(f => f.resolution.id <= maxResolution)
393 const fileBitrate = (f.size / this.videoDuration)
394 let threshold = fileBitrate
396 // If this is for a higher resolution or an initial load: add a margin
397 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
398 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
401 return averageDownloadSpeed > threshold
404 // If the download speed is too bad, return the lowest resolution we have
405 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
407 return videoFileMaxByResolution(filteredFiles)
410 private getAndSaveActualDownloadSpeed () {
411 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
412 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
413 if (lastDownloadSpeeds.length === 0) return -1
415 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
416 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
418 // Save the average bandwidth for future use
419 saveAverageBandwidth(averageBandwidth)
421 return averageBandwidth
424 private initializePlayer () {
425 if (isMobile()) this.player.addClass('vjs-is-mobile')
427 this.initSmoothProgressBar()
431 this.alterInactivity()
433 if (this.autoplay === true) {
434 this.player.posterImage.hide()
436 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
439 // Don't try on iOS that does not support MediaSource
441 this.currentVideoFile = this.pickAverageVideoFile()
442 return this.fallbackToHttp(undefined, false)
446 const oldPlay = this.player.play.bind(this.player)
447 this.player.play = () => {
448 this.player.addClass('vjs-has-big-play-button-clicked')
449 this.player.play = oldPlay
451 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
455 private runAutoQualityScheduler () {
456 this.autoQualityInterval = setInterval(() => {
458 // Not initialized or in HTTP fallback
459 if (this.torrent === undefined || this.torrent === null) return
460 if (this.isAutoResolutionOn() === false) return
461 if (this.isAutoResolutionObservation === true) return
463 const file = this.getAppropriateFile()
464 let changeResolution = false
465 let changeResolutionDelay = 0
468 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
469 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
470 changeResolution = true
471 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
472 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
473 changeResolution = true
474 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
477 if (changeResolution === true) {
478 this.updateResolution(file.resolution.id, changeResolutionDelay)
480 // Wait some seconds in observation of our new resolution
481 this.isAutoResolutionObservation = true
483 this.qualityObservationTimer = setTimeout(() => {
484 this.isAutoResolutionObservation = false
485 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
487 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
490 private isPlayerWaiting () {
491 return this.player && this.player.hasClass('vjs-waiting')
494 private runTorrentInfoScheduler () {
495 this.torrentInfoInterval = setInterval(() => {
496 // Not initialized yet
497 if (this.torrent === undefined) return
500 if (this.torrent === null) return this.trigger('torrentInfo', false)
502 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
503 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
505 return this.trigger('torrentInfo', {
506 downloadSpeed: this.torrent.downloadSpeed,
507 numPeers: this.torrent.numPeers,
508 uploadSpeed: this.torrent.uploadSpeed,
509 downloaded: this.torrent.downloaded,
510 uploaded: this.torrent.uploaded
512 }, this.CONSTANTS.INFO_SCHEDULER)
515 private runViewAdd () {
516 this.clearVideoViewInterval()
518 // After 30 seconds (or 3/4 of the video), add a view to the video
519 let minSecondsToView = 30
521 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
523 let secondsViewed = 0
524 this.videoViewInterval = setInterval(() => {
525 if (this.player && !this.player.paused()) {
528 if (secondsViewed > minSecondsToView) {
529 this.clearVideoViewInterval()
531 this.addViewToVideo().catch(err => console.error(err))
537 private runUserWatchVideo (options: UserWatching) {
538 let lastCurrentTime = 0
540 this.userWatchingVideoInterval = setInterval(() => {
541 const currentTime = Math.floor(this.player.currentTime())
543 if (currentTime - lastCurrentTime >= 1) {
544 lastCurrentTime = currentTime
546 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
547 .catch(err => console.error('Cannot notify user is watching.', err))
549 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
552 private clearVideoViewInterval () {
553 if (this.videoViewInterval !== undefined) {
554 clearInterval(this.videoViewInterval)
555 this.videoViewInterval = undefined
559 private addViewToVideo () {
560 if (!this.videoViewUrl) return Promise.resolve(undefined)
562 return fetch(this.videoViewUrl, { method: 'POST' })
565 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
566 const body = new URLSearchParams()
567 body.append('currentTime', currentTime.toString())
569 const headers = new Headers({ 'Authorization': authorizationHeader })
571 return fetch(url, { method: 'PUT', body, headers })
574 private fallbackToHttp (done?: Function, play = true) {
575 this.disableAutoResolution(true)
577 this.flushVideoFile(this.currentVideoFile, true)
580 // Enable error display now this is our last fallback
581 this.player.one('error', () => this.enableErrorDisplay())
583 const httpUrl = this.currentVideoFile.fileUrl
584 this.player.src = this.savePlayerSrcFunction
585 this.player.src(httpUrl)
586 if (play) this.tryToPlay()
588 if (done) return done()
591 private handleError (err: Error | string) {
592 return this.player.trigger('customError', { err })
595 private enableErrorDisplay () {
596 this.player.addClass('vjs-error-display-enabled')
599 private disableErrorDisplay () {
600 this.player.removeClass('vjs-error-display-enabled')
604 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
607 private alterInactivity () {
608 let saveInactivityTimeout: number
610 const disableInactivity = () => {
611 saveInactivityTimeout = this.player.options_.inactivityTimeout
612 this.player.options_.inactivityTimeout = 0
614 const enableInactivity = () => {
615 this.player.options_.inactivityTimeout = saveInactivityTimeout
618 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
620 this.player.controlBar.on('mouseenter', () => disableInactivity())
621 settingsDialog.on('mouseenter', () => disableInactivity())
622 this.player.controlBar.on('mouseleave', () => enableInactivity())
623 settingsDialog.on('mouseleave', () => enableInactivity())
626 private pickAverageVideoFile () {
627 if (this.videoFiles.length === 1) return this.videoFiles[0]
629 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
632 private stopTorrent (torrent: WebTorrent.Torrent) {
634 // Pause does not remove actual peers (in particular the webseed peer)
635 torrent.removePeer(torrent[ 'ws' ])
638 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
639 this.destoyingFakeRenderer = false
641 const fakeVideoElem = document.createElement('video')
642 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
643 this.fakeRenderer = renderer
645 // The renderer returns an error when we destroy it, so skip them
646 if (this.destoyingFakeRenderer === false && err) {
647 console.error('Cannot render new torrent in fake video element.', err)
650 // Load the future file at the correct time (in delay MS - 2 seconds)
651 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
655 private destroyFakeRenderer () {
656 if (this.fakeRenderer) {
657 this.destoyingFakeRenderer = true
659 if (this.fakeRenderer.destroy) {
661 this.fakeRenderer.destroy()
663 console.log('Cannot destroy correctly fake renderer.', err)
666 this.fakeRenderer = undefined
670 private initCaptions () {
671 for (const caption of this.videoCaptions) {
672 this.player.addRemoteTextTrack({
674 label: caption.label,
675 language: caption.language,
676 id: caption.language,
682 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
683 private initSmoothProgressBar () {
684 const SeekBar = videojsUntyped.getComponent('SeekBar')
685 SeekBar.prototype.getPercent = function getPercent () {
686 // Allows for smooth scrubbing, when player can't keep up.
687 // const time = (this.player_.scrubbing()) ?
688 // this.player_.getCache().currentTime :
689 // this.player_.currentTime()
690 const time = this.player_.currentTime()
691 const percent = time / this.player_.duration()
692 return percent >= 1 ? 1 : percent
694 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
695 let newTime = this.calculateDistance(event) * this.player_.duration()
696 if (newTime === this.player_.duration()) {
697 newTime = newTime - 0.1
699 this.player_.currentTime(newTime)
705 videojs.registerPlugin('peertube', PeerTubePlugin)
706 export { PeerTubePlugin }