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,
14 getStoredLastSubtitle,
17 getStoredWebTorrentEnabled,
22 } from './peertube-player-local-storage'
24 const CacheChunkStore = require('cache-chunk-store')
32 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
33 class PeerTubePlugin extends Plugin {
34 private readonly playerElement: HTMLVideoElement
36 private readonly autoplay: boolean = false
37 private readonly startTime: number = 0
38 private readonly savePlayerSrcFunction: Function
39 private readonly videoFiles: VideoFile[]
40 private readonly videoViewUrl: string
41 private readonly videoDuration: number
42 private readonly CONSTANTS = {
43 INFO_SCHEDULER: 1000, // Don't change this
44 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
45 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
46 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
47 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
48 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5, // Last 5 seconds to build average bandwidth
49 USER_WATCHING_VIDEO_INTERVAL: 5000 // Every 5 seconds, notify the user is watching the video
52 private readonly webtorrent = new WebTorrent({
57 urls: 'stun:stun.stunprotocol.org'
60 urls: 'stun:stun.framasoft.org'
69 private currentVideoFile: VideoFile
70 private torrent: WebTorrent.Torrent
71 private videoCaptions: VideoJSCaption[]
72 private defaultSubtitle: string
75 private fakeRenderer: any
76 private destroyingFakeRenderer = false
78 private autoResolution = true
79 private forbidAutoResolution = false
80 private isAutoResolutionObservation = false
81 private playerRefusedP2P = false
83 private videoViewInterval: any
84 private torrentInfoInterval: any
85 private autoQualityInterval: any
86 private userWatchingVideoInterval: any
87 private addTorrentDelay: any
88 private qualityObservationTimer: any
89 private runAutoQualitySchedulerTimer: any
91 private downloadSpeeds: number[] = []
93 constructor (player: videojs.Player, options: PeertubePluginOptions) {
94 super(player, options)
96 // Disable auto play on iOS
97 this.autoplay = options.autoplay && this.isIOS() === false
98 this.playerRefusedP2P = !getStoredWebTorrentEnabled()
100 this.startTime = timeToInt(options.startTime)
101 this.videoFiles = options.videoFiles
102 this.videoViewUrl = options.videoViewUrl
103 this.videoDuration = options.videoDuration
104 this.videoCaptions = options.videoCaptions
106 this.savePlayerSrcFunction = this.player.src
107 this.playerElement = options.playerElement
109 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
111 this.player.ready(() => {
112 const playerOptions = this.player.options_
114 const volume = getStoredVolume()
115 if (volume !== undefined) this.player.volume(volume)
117 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
118 if (muted !== undefined) this.player.muted(muted)
120 this.defaultSubtitle = options.subtitle || getStoredLastSubtitle()
122 this.player.on('volumechange', () => {
123 saveVolumeInStore(this.player.volume())
124 saveMuteInStore(this.player.muted())
127 this.player.textTracks().on('change', () => {
128 const showing = this.player.textTracks().tracks_.find((t: { kind: string, mode: string }) => {
129 return t.kind === 'captions' && t.mode === 'showing'
133 saveLastSubtitle('off')
137 saveLastSubtitle(showing.language)
140 this.player.duration(options.videoDuration)
142 this.initializePlayer()
143 this.runTorrentInfoScheduler()
146 if (options.userWatching) this.runUserWatchVideo(options.userWatching)
148 this.player.one('play', () => {
149 // Don't run immediately scheduler, wait some seconds the TCP connections are made
150 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
156 clearTimeout(this.addTorrentDelay)
157 clearTimeout(this.qualityObservationTimer)
158 clearTimeout(this.runAutoQualitySchedulerTimer)
160 clearInterval(this.videoViewInterval)
161 clearInterval(this.torrentInfoInterval)
162 clearInterval(this.autoQualityInterval)
164 if (this.userWatchingVideoInterval) clearInterval(this.userWatchingVideoInterval)
166 // Don't need to destroy renderer, video player will be destroyed
167 this.flushVideoFile(this.currentVideoFile, false)
169 this.destroyFakeRenderer()
172 getCurrentResolutionId () {
173 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
176 getCurrentResolutionLabel () {
177 if (!this.currentVideoFile) return ''
179 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
180 return this.currentVideoFile.resolution.label + fps
184 videoFile?: VideoFile,
190 done: () => void = () => { /* empty */ }
192 // Automatically choose the adapted video file
193 if (videoFile === undefined) {
194 const savedAverageBandwidth = getAverageBandwidthInStore()
195 videoFile = savedAverageBandwidth
196 ? this.getAppropriateFile(savedAverageBandwidth)
197 : this.pickAverageVideoFile()
200 // Don't add the same video file once again
201 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
205 // Do not display error to user because we will have multiple fallback
206 this.disableErrorDisplay()
208 // Hack to "simulate" src link in video.js >= 6
209 // Without this, we can't play the video after pausing it
210 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
211 this.player.src = () => true
212 const oldPlaybackRate = this.player.playbackRate()
214 const previousVideoFile = this.currentVideoFile
215 this.currentVideoFile = videoFile
217 // Don't try on iOS that does not support MediaSource
218 // Or don't use P2P if webtorrent is disabled
219 if (this.isIOS() || this.playerRefusedP2P) {
220 return this.fallbackToHttp(options, () => {
221 this.player.playbackRate(oldPlaybackRate)
226 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
227 this.player.playbackRate(oldPlaybackRate)
231 this.trigger('videoFileUpdate')
234 updateResolution (resolutionId: number, delay = 0) {
235 // Remember player state
236 const currentTime = this.player.currentTime()
237 const isPaused = this.player.paused()
239 // Remove poster to have black background
240 this.playerElement.poster = ''
242 // Hide bigPlayButton
244 this.player.bigPlayButton.hide()
247 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
251 seek: currentTime + (delay / 1000)
253 this.updateVideoFile(newVideoFile, options)
256 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
257 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
258 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
260 this.webtorrent.remove(videoFile.magnetUri)
261 console.log('Removed ' + videoFile.magnetUri)
265 isAutoResolutionOn () {
266 return this.autoResolution
269 enableAutoResolution () {
270 this.autoResolution = true
271 this.trigger('autoResolutionUpdate')
274 disableAutoResolution (forbid = false) {
275 if (forbid === true) this.forbidAutoResolution = true
277 this.autoResolution = false
278 this.trigger('autoResolutionUpdate')
281 isAutoResolutionForbidden () {
282 return this.forbidAutoResolution === true
285 getCurrentVideoFile () {
286 return this.currentVideoFile
294 magnetOrTorrentUrl: string,
295 previousVideoFile: VideoFile,
296 options: PlayOptions,
299 console.log('Adding ' + magnetOrTorrentUrl + '.')
301 const oldTorrent = this.torrent
302 const torrentOptions = {
303 store: (chunkLength: number, storeOpts: any) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
308 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
309 console.log('Added ' + magnetOrTorrentUrl + '.')
312 // Pause the old torrent
313 this.stopTorrent(oldTorrent)
315 // We use a fake renderer so we download correct pieces of the next file
316 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
319 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
320 this.addTorrentDelay = setTimeout(() => {
321 // We don't need the fake renderer anymore
322 this.destroyFakeRenderer()
324 const paused = this.player.paused()
326 this.flushVideoFile(previousVideoFile)
328 // Update progress bar (just for the UI), do not wait rendering
329 if (options.seek) this.player.currentTime(options.seek)
331 const renderVideoOptions = { autoplay: false, controls: true }
332 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
333 this.renderer = renderer
335 if (err) return this.fallbackToHttp(options, done)
337 return this.tryToPlay(err => {
338 if (err) return done(err)
340 if (options.seek) this.seek(options.seek)
341 if (options.forcePlay === false && paused === true) this.player.pause()
346 }, options.delay || 0)
349 this.torrent.on('error', (err: any) => console.error(err))
351 this.torrent.on('warning', (err: any) => {
352 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
353 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
355 // Users don't care about issues with WebRTC, but developers do so log it in the console
356 if (err.message.indexOf('Ice connection failed') !== -1) {
361 // Magnet hash is not up to date with the torrent file, add directly the torrent file
362 if (err.message.indexOf('incorrect info hash') !== -1) {
363 console.error('Incorrect info hash detected, falling back to torrent file.')
364 const newOptions = { forcePlay: true, seek: options.seek }
365 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
368 // Remote instance is down
369 if (err.message.indexOf('from xs param') !== -1) {
370 this.handleError(err)
377 private tryToPlay (done?: (err?: Error) => void) {
378 if (!done) done = function () { /* empty */ }
380 const playPromise = this.player.play()
381 if (playPromise !== undefined) {
382 return playPromise.then(done)
383 .catch((err: Error) => {
384 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
390 this.player.posterImage.show()
391 this.player.removeClass('vjs-has-autoplay')
392 this.player.removeClass('vjs-has-big-play-button-clicked')
401 private seek (time: number) {
402 this.player.currentTime(time)
403 this.player.handleTechSeeked_()
406 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
407 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
408 if (this.videoFiles.length === 1) return this.videoFiles[0]
410 // Don't change the torrent is the play was ended
411 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
413 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
415 // Limit resolution according to player height
416 const playerHeight = this.playerElement.offsetHeight as number
418 // We take the first resolution just above the player height
419 // Example: player height is 530px, we want the 720p file instead of 480p
420 let maxResolution = this.videoFiles[0].resolution.id
421 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
422 const resolutionId = this.videoFiles[i].resolution.id
423 if (resolutionId >= playerHeight) {
424 maxResolution = resolutionId
429 // Filter videos we can play according to our screen resolution and bandwidth
430 const filteredFiles = this.videoFiles
431 .filter(f => f.resolution.id <= maxResolution)
433 const fileBitrate = (f.size / this.videoDuration)
434 let threshold = fileBitrate
436 // If this is for a higher resolution or an initial load: add a margin
437 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
438 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
441 return averageDownloadSpeed > threshold
444 // If the download speed is too bad, return the lowest resolution we have
445 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
447 return videoFileMaxByResolution(filteredFiles)
450 private getAndSaveActualDownloadSpeed () {
451 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
452 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
453 if (lastDownloadSpeeds.length === 0) return -1
455 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
456 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
458 // Save the average bandwidth for future use
459 saveAverageBandwidth(averageBandwidth)
461 return averageBandwidth
464 private initializePlayer () {
465 if (isMobile()) this.player.addClass('vjs-is-mobile')
467 this.initSmoothProgressBar()
471 this.alterInactivity()
473 if (this.autoplay === true) {
474 this.player.posterImage.hide()
476 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
480 const oldPlay = this.player.play.bind(this.player)
481 this.player.play = () => {
482 this.player.addClass('vjs-has-big-play-button-clicked')
483 this.player.play = oldPlay
485 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
489 private runAutoQualityScheduler () {
490 this.autoQualityInterval = setInterval(() => {
492 // Not initialized or in HTTP fallback
493 if (this.torrent === undefined || this.torrent === null) return
494 if (this.isAutoResolutionOn() === false) return
495 if (this.isAutoResolutionObservation === true) return
497 const file = this.getAppropriateFile()
498 let changeResolution = false
499 let changeResolutionDelay = 0
502 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
503 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
504 changeResolution = true
505 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
506 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
507 changeResolution = true
508 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
511 if (changeResolution === true) {
512 this.updateResolution(file.resolution.id, changeResolutionDelay)
514 // Wait some seconds in observation of our new resolution
515 this.isAutoResolutionObservation = true
517 this.qualityObservationTimer = setTimeout(() => {
518 this.isAutoResolutionObservation = false
519 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
521 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
524 private isPlayerWaiting () {
525 return this.player && this.player.hasClass('vjs-waiting')
528 private runTorrentInfoScheduler () {
529 this.torrentInfoInterval = setInterval(() => {
530 // Not initialized yet
531 if (this.torrent === undefined) return
534 if (this.torrent === null) return this.trigger('torrentInfo', false)
536 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
537 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
539 return this.trigger('torrentInfo', {
540 downloadSpeed: this.torrent.downloadSpeed,
541 numPeers: this.torrent.numPeers,
542 uploadSpeed: this.torrent.uploadSpeed,
543 downloaded: this.torrent.downloaded,
544 uploaded: this.torrent.uploaded
546 }, this.CONSTANTS.INFO_SCHEDULER)
549 private runViewAdd () {
550 this.clearVideoViewInterval()
552 // After 30 seconds (or 3/4 of the video), add a view to the video
553 let minSecondsToView = 30
555 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
557 let secondsViewed = 0
558 this.videoViewInterval = setInterval(() => {
559 if (this.player && !this.player.paused()) {
562 if (secondsViewed > minSecondsToView) {
563 this.clearVideoViewInterval()
565 this.addViewToVideo().catch(err => console.error(err))
571 private runUserWatchVideo (options: UserWatching) {
572 let lastCurrentTime = 0
574 this.userWatchingVideoInterval = setInterval(() => {
575 const currentTime = Math.floor(this.player.currentTime())
577 if (currentTime - lastCurrentTime >= 1) {
578 lastCurrentTime = currentTime
580 this.notifyUserIsWatching(currentTime, options.url, options.authorizationHeader)
581 .catch(err => console.error('Cannot notify user is watching.', err))
583 }, this.CONSTANTS.USER_WATCHING_VIDEO_INTERVAL)
586 private clearVideoViewInterval () {
587 if (this.videoViewInterval !== undefined) {
588 clearInterval(this.videoViewInterval)
589 this.videoViewInterval = undefined
593 private addViewToVideo () {
594 if (!this.videoViewUrl) return Promise.resolve(undefined)
596 return fetch(this.videoViewUrl, { method: 'POST' })
599 private notifyUserIsWatching (currentTime: number, url: string, authorizationHeader: string) {
600 const body = new URLSearchParams()
601 body.append('currentTime', currentTime.toString())
603 const headers = new Headers({ 'Authorization': authorizationHeader })
605 return fetch(url, { method: 'PUT', body, headers })
608 private fallbackToHttp (options: PlayOptions, done?: Function) {
609 const paused = this.player.paused()
611 this.disableAutoResolution(true)
613 this.flushVideoFile(this.currentVideoFile, true)
616 // Enable error display now this is our last fallback
617 this.player.one('error', () => this.enableErrorDisplay())
619 const httpUrl = this.currentVideoFile.fileUrl
620 this.player.src = this.savePlayerSrcFunction
621 this.player.src(httpUrl)
623 return this.tryToPlay(err => {
624 if (err && done) return done(err)
626 if (options.seek) this.seek(options.seek)
627 if (options.forcePlay === false && paused === true) this.player.pause()
629 if (done) return done()
633 private handleError (err: Error | string) {
634 return this.player.trigger('customError', { err })
637 private enableErrorDisplay () {
638 this.player.addClass('vjs-error-display-enabled')
641 private disableErrorDisplay () {
642 this.player.removeClass('vjs-error-display-enabled')
646 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
649 private alterInactivity () {
650 let saveInactivityTimeout: number
652 const disableInactivity = () => {
653 saveInactivityTimeout = this.player.options_.inactivityTimeout
654 this.player.options_.inactivityTimeout = 0
656 const enableInactivity = () => {
657 this.player.options_.inactivityTimeout = saveInactivityTimeout
660 const settingsDialog = this.player.children_.find((c: any) => c.name_ === 'SettingsDialog')
662 this.player.controlBar.on('mouseenter', () => disableInactivity())
663 settingsDialog.on('mouseenter', () => disableInactivity())
664 this.player.controlBar.on('mouseleave', () => enableInactivity())
665 settingsDialog.on('mouseleave', () => enableInactivity())
668 private pickAverageVideoFile () {
669 if (this.videoFiles.length === 1) return this.videoFiles[0]
671 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
674 private stopTorrent (torrent: WebTorrent.Torrent) {
676 // Pause does not remove actual peers (in particular the webseed peer)
677 torrent.removePeer(torrent[ 'ws' ])
680 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
681 this.destroyingFakeRenderer = false
683 const fakeVideoElem = document.createElement('video')
684 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
685 this.fakeRenderer = renderer
687 // The renderer returns an error when we destroy it, so skip them
688 if (this.destroyingFakeRenderer === false && err) {
689 console.error('Cannot render new torrent in fake video element.', err)
692 // Load the future file at the correct time (in delay MS - 2 seconds)
693 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
697 private destroyFakeRenderer () {
698 if (this.fakeRenderer) {
699 this.destroyingFakeRenderer = true
701 if (this.fakeRenderer.destroy) {
703 this.fakeRenderer.destroy()
705 console.log('Cannot destroy correctly fake renderer.', err)
708 this.fakeRenderer = undefined
712 private initCaptions () {
713 for (const caption of this.videoCaptions) {
714 this.player.addRemoteTextTrack({
716 label: caption.label,
717 language: caption.language,
718 id: caption.language,
720 default: this.defaultSubtitle === caption.language
725 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
726 private initSmoothProgressBar () {
727 const SeekBar = videojsUntyped.getComponent('SeekBar')
728 SeekBar.prototype.getPercent = function getPercent () {
729 // Allows for smooth scrubbing, when player can't keep up.
730 // const time = (this.player_.scrubbing()) ?
731 // this.player_.getCache().currentTime :
732 // this.player_.currentTime()
733 const time = this.player_.currentTime()
734 const percent = time / this.player_.duration()
735 return percent >= 1 ? 1 : percent
737 SeekBar.prototype.handleMouseMove = function handleMouseMove (event: any) {
738 let newTime = this.calculateDistance(event) * this.player_.duration()
739 if (newTime === this.player_.duration()) {
740 newTime = newTime - 0.1
742 this.player_.currentTime(newTime)
748 videojs.registerPlugin('peertube', PeerTubePlugin)
749 export { PeerTubePlugin }