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, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { isMobile, 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
59 private autoResolution = true
60 private forbidAutoResolution = false
61 private isAutoResolutionObservation = false
63 private videoViewInterval
64 private torrentInfoInterval
65 private autoQualityInterval
66 private addTorrentDelay
67 private qualityObservationTimer
68 private runAutoQualitySchedulerTimer
70 private downloadSpeeds: number[] = []
72 constructor (player: videojs.Player, options: PeertubePluginOptions) {
73 super(player, options)
75 // Disable auto play on iOS
76 this.autoplay = options.autoplay && this.isIOS() === false
78 this.startTime = options.startTime
79 this.videoFiles = options.videoFiles
80 this.videoViewUrl = options.videoViewUrl
81 this.videoDuration = options.videoDuration
83 this.savePlayerSrcFunction = this.player.src
84 // Hack to "simulate" src link in video.js >= 6
85 // Without this, we can't play the video after pausing it
86 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
87 this.player.src = () => true
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(() => {
106 this.runAutoQualityScheduler()
107 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
111 this.player.on('volumechange', () => {
112 saveVolumeInStore(this.player.volume())
113 saveMuteInStore(this.player.muted())
118 clearTimeout(this.addTorrentDelay)
119 clearTimeout(this.qualityObservationTimer)
120 clearTimeout(this.runAutoQualitySchedulerTimer)
122 clearInterval(this.videoViewInterval)
123 clearInterval(this.torrentInfoInterval)
124 clearInterval(this.autoQualityInterval)
126 // Don't need to destroy renderer, video player will be destroyed
127 this.flushVideoFile(this.currentVideoFile, false)
129 this.destroyFakeRenderer()
132 getCurrentResolutionId () {
133 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
136 getCurrentResolutionLabel () {
137 if (!this.currentVideoFile) return ''
139 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
140 return this.currentVideoFile.resolution.label + fps
144 videoFile?: VideoFile,
150 done: () => void = () => { /* empty */ }
152 // Automatically choose the adapted video file
153 if (videoFile === undefined) {
154 const savedAverageBandwidth = getAverageBandwidthInStore()
155 videoFile = savedAverageBandwidth
156 ? this.getAppropriateFile(savedAverageBandwidth)
157 : this.pickAverageVideoFile()
160 // Don't add the same video file once again
161 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
165 // Do not display error to user because we will have multiple fallback
166 this.disableErrorDisplay()
168 this.player.src = () => true
169 const oldPlaybackRate = this.player.playbackRate()
171 const previousVideoFile = this.currentVideoFile
172 this.currentVideoFile = videoFile
174 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
175 this.player.playbackRate(oldPlaybackRate)
179 this.trigger('videoFileUpdate')
183 magnetOrTorrentUrl: string,
184 previousVideoFile: VideoFile,
192 console.log('Adding ' + magnetOrTorrentUrl + '.')
194 const oldTorrent = this.torrent
195 const torrentOptions = {
196 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
201 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
202 console.log('Added ' + magnetOrTorrentUrl + '.')
205 // Pause the old torrent
207 // Pause does not remove actual peers (in particular the webseed peer)
208 oldTorrent.removePeer(oldTorrent['ws'])
210 // We use a fake renderer so we download correct pieces of the next file
212 const fakeVideoElem = document.createElement('video')
213 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
214 this.fakeRenderer = renderer
216 if (err) console.error('Cannot render new torrent in fake video element.', err)
218 // Load the future file at the correct time
219 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
224 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
225 this.addTorrentDelay = setTimeout(() => {
226 this.destroyFakeRenderer()
228 const paused = this.player.paused()
230 this.flushVideoFile(previousVideoFile)
232 const renderVideoOptions = { autoplay: false, controls: true }
233 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
234 this.renderer = renderer
236 if (err) return this.fallbackToHttp(done)
238 return this.tryToPlay(err => {
239 if (err) return done(err)
241 if (options.seek) this.seek(options.seek)
242 if (options.forcePlay === false && paused === true) this.player.pause()
247 }, options.delay || 0)
250 this.torrent.on('error', err => console.error(err))
252 this.torrent.on('warning', (err: any) => {
253 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
254 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
256 // Users don't care about issues with WebRTC, but developers do so log it in the console
257 if (err.message.indexOf('Ice connection failed') !== -1) {
262 // Magnet hash is not up to date with the torrent file, add directly the torrent file
263 if (err.message.indexOf('incorrect info hash') !== -1) {
264 console.error('Incorrect info hash detected, falling back to torrent file.')
265 const options = { forcePlay: true }
266 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
269 return console.warn(err)
273 updateResolution (resolutionId: number, delay = 0) {
274 // Remember player state
275 const currentTime = this.player.currentTime()
276 const isPaused = this.player.paused()
278 // Remove poster to have black background
279 this.playerElement.poster = ''
281 // Hide bigPlayButton
283 this.player.bigPlayButton.hide()
286 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
290 seek: currentTime + (delay / 1000)
292 this.updateVideoFile(newVideoFile, options)
295 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
296 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
297 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
299 this.webtorrent.remove(videoFile.magnetUri)
300 console.log('Removed ' + videoFile.magnetUri)
304 isAutoResolutionOn () {
305 return this.autoResolution
308 enableAutoResolution () {
309 this.autoResolution = true
310 this.trigger('autoResolutionUpdate')
313 disableAutoResolution (forbid = false) {
314 if (forbid === true) this.forbidAutoResolution = true
316 this.autoResolution = false
317 this.trigger('autoResolutionUpdate')
320 isAutoResolutionForbidden () {
321 return this.forbidAutoResolution === true
324 getCurrentVideoFile () {
325 return this.currentVideoFile
332 private tryToPlay (done?: Function) {
333 if (!done) done = function () { /* empty */ }
335 const playPromise = this.player.play()
336 if (playPromise !== undefined) {
337 return playPromise.then(done)
339 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
345 this.player.posterImage.show()
346 this.player.removeClass('vjs-has-autoplay')
347 this.player.removeClass('vjs-has-big-play-button-clicked')
356 private seek (time: number) {
357 this.player.currentTime(time)
358 this.player.handleTechSeeked_()
361 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
362 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
363 if (this.videoFiles.length === 1) return this.videoFiles[0]
365 // Don't change the torrent is the play was ended
366 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
368 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
370 // Limit resolution according to player height
371 const playerHeight = this.playerElement.offsetHeight as number
373 // We take the first resolution just above the player height
374 // Example: player height is 530px, we want the 720p file instead of 480p
375 let maxResolution = this.videoFiles[0].resolution.id
376 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
377 const resolutionId = this.videoFiles[i].resolution.id
378 if (resolutionId >= playerHeight) {
379 maxResolution = resolutionId
384 // Filter videos we can play according to our screen resolution and bandwidth
385 const filteredFiles = this.videoFiles
386 .filter(f => f.resolution.id <= maxResolution)
388 const fileBitrate = (f.size / this.videoDuration)
389 let threshold = fileBitrate
391 // If this is for a higher resolution or an initial load: add a margin
392 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
393 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
396 return averageDownloadSpeed > threshold
399 // If the download speed is too bad, return the lowest resolution we have
400 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
402 return videoFileMaxByResolution(filteredFiles)
405 private getAndSaveActualDownloadSpeed () {
406 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
407 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
408 if (lastDownloadSpeeds.length === 0) return -1
410 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
411 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
413 // Save the average bandwidth for future use
414 saveAverageBandwidth(averageBandwidth)
416 return averageBandwidth
419 private initializePlayer () {
420 if (isMobile()) this.player.addClass('vjs-is-mobile')
422 this.initSmoothProgressBar()
424 this.alterInactivity()
426 if (this.autoplay === true) {
427 this.player.posterImage.hide()
429 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
431 // Don't try on iOS that does not support MediaSource
433 this.currentVideoFile = this.pickAverageVideoFile()
434 return this.fallbackToHttp(undefined, false)
438 const oldPlay = this.player.play.bind(this.player)
439 this.player.play = () => {
440 this.player.addClass('vjs-has-big-play-button-clicked')
441 this.player.play = oldPlay
443 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
448 private runAutoQualityScheduler () {
449 this.autoQualityInterval = setInterval(() => {
451 // Not initialized or in HTTP fallback
452 if (this.torrent === undefined || this.torrent === null) return
453 if (this.isAutoResolutionOn() === false) return
454 if (this.isAutoResolutionObservation === true) return
456 const file = this.getAppropriateFile()
457 let changeResolution = false
458 let changeResolutionDelay = 0
461 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
462 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
463 changeResolution = true
464 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
465 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
466 changeResolution = true
467 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
470 if (changeResolution === true) {
471 this.updateResolution(file.resolution.id, changeResolutionDelay)
473 // Wait some seconds in observation of our new resolution
474 this.isAutoResolutionObservation = true
476 this.qualityObservationTimer = setTimeout(() => {
477 this.isAutoResolutionObservation = false
478 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
480 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
483 private isPlayerWaiting () {
484 return this.player && this.player.hasClass('vjs-waiting')
487 private runTorrentInfoScheduler () {
488 this.torrentInfoInterval = setInterval(() => {
489 // Not initialized yet
490 if (this.torrent === undefined) return
493 if (this.torrent === null) return this.trigger('torrentInfo', false)
495 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
496 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
498 return this.trigger('torrentInfo', {
499 downloadSpeed: this.torrent.downloadSpeed,
500 numPeers: this.torrent.numPeers,
501 uploadSpeed: this.torrent.uploadSpeed,
502 downloaded: this.torrent.downloaded,
503 uploaded: this.torrent.uploaded
505 }, this.CONSTANTS.INFO_SCHEDULER)
508 private runViewAdd () {
509 this.clearVideoViewInterval()
511 // After 30 seconds (or 3/4 of the video), add a view to the video
512 let minSecondsToView = 30
514 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
516 let secondsViewed = 0
517 this.videoViewInterval = setInterval(() => {
518 if (this.player && !this.player.paused()) {
521 if (secondsViewed > minSecondsToView) {
522 this.clearVideoViewInterval()
524 this.addViewToVideo().catch(err => console.error(err))
530 private clearVideoViewInterval () {
531 if (this.videoViewInterval !== undefined) {
532 clearInterval(this.videoViewInterval)
533 this.videoViewInterval = undefined
537 private addViewToVideo () {
538 if (!this.videoViewUrl) return Promise.resolve(undefined)
540 return fetch(this.videoViewUrl, { method: 'POST' })
543 private fallbackToHttp (done?: Function, play = true) {
544 this.disableAutoResolution(true)
546 this.flushVideoFile(this.currentVideoFile, true)
549 // Enable error display now this is our last fallback
550 this.player.one('error', () => this.enableErrorDisplay())
552 const httpUrl = this.currentVideoFile.fileUrl
553 this.player.src = this.savePlayerSrcFunction
554 this.player.src(httpUrl)
555 if (play) this.tryToPlay()
557 if (done) return done()
560 private handleError (err: Error | string) {
561 return this.player.trigger('customError', { err })
564 private enableErrorDisplay () {
565 this.player.addClass('vjs-error-display-enabled')
568 private disableErrorDisplay () {
569 this.player.removeClass('vjs-error-display-enabled')
573 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
576 private alterInactivity () {
577 let saveInactivityTimeout: number
579 const disableInactivity = () => {
580 saveInactivityTimeout = this.player.options_.inactivityTimeout
581 this.player.options_.inactivityTimeout = 0
583 const enableInactivity = () => {
584 this.player.options_.inactivityTimeout = saveInactivityTimeout
587 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
589 this.player.controlBar.on('mouseenter', () => disableInactivity())
590 settingsDialog.on('mouseenter', () => disableInactivity())
591 this.player.controlBar.on('mouseleave', () => enableInactivity())
592 settingsDialog.on('mouseleave', () => enableInactivity())
595 private pickAverageVideoFile () {
596 if (this.videoFiles.length === 1) return this.videoFiles[0]
598 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
601 private destroyFakeRenderer () {
602 if (this.fakeRenderer) {
603 if (this.fakeRenderer.destroy) {
605 this.fakeRenderer.destroy()
607 console.log('Cannot destroy correctly fake renderer.', err)
610 this.fakeRenderer = undefined
614 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
615 private initSmoothProgressBar () {
616 const SeekBar = videojsUntyped.getComponent('SeekBar')
617 SeekBar.prototype.getPercent = function getPercent () {
618 // Allows for smooth scrubbing, when player can't keep up.
619 // const time = (this.player_.scrubbing()) ?
620 // this.player_.getCache().currentTime :
621 // this.player_.currentTime()
622 const time = this.player_.currentTime()
623 const percent = time / this.player_.duration()
624 return percent >= 1 ? 1 : percent
626 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
627 let newTime = this.calculateDistance(event) * this.player_.duration()
628 if (newTime === this.player_.duration()) {
629 newTime = newTime - 0.1
631 this.player_.currentTime(newTime)
637 videojs.registerPlugin('peertube', PeerTubePlugin)
638 export { PeerTubePlugin }