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 // Filter videos we can play according to our screen resolution and bandwidth
371 const filteredFiles = this.videoFiles.filter(f => f.resolution.id <= this.playerElement.width)
373 const fileBitrate = (f.size / this.videoDuration)
374 let threshold = fileBitrate
376 // If this is for a higher resolution or an initial load: add a margin
377 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
378 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
381 return averageDownloadSpeed > threshold
384 // If the download speed is too bad, return the lowest resolution we have
385 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
387 return videoFileMaxByResolution(filteredFiles)
390 private getAndSaveActualDownloadSpeed () {
391 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
392 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
393 if (lastDownloadSpeeds.length === 0) return -1
395 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
396 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
398 // Save the average bandwidth for future use
399 saveAverageBandwidth(averageBandwidth)
401 return averageBandwidth
404 private initializePlayer () {
405 if (isMobile()) this.player.addClass('vjs-is-mobile')
407 this.initSmoothProgressBar()
409 this.alterInactivity()
411 if (this.autoplay === true) {
412 this.player.posterImage.hide()
414 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
416 // Don't try on iOS that does not support MediaSource
418 this.currentVideoFile = this.pickAverageVideoFile()
419 return this.fallbackToHttp(undefined, false)
423 const oldPlay = this.player.play.bind(this.player)
424 this.player.play = () => {
425 this.player.addClass('vjs-has-big-play-button-clicked')
426 this.player.play = oldPlay
428 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
433 private runAutoQualityScheduler () {
434 this.autoQualityInterval = setInterval(() => {
436 // Not initialized or in HTTP fallback
437 if (this.torrent === undefined || this.torrent === null) return
438 if (this.isAutoResolutionOn() === false) return
439 if (this.isAutoResolutionObservation === true) return
441 const file = this.getAppropriateFile()
442 let changeResolution = false
443 let changeResolutionDelay = 0
446 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
447 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
448 changeResolution = true
449 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
450 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
451 changeResolution = true
452 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
455 if (changeResolution === true) {
456 this.updateResolution(file.resolution.id, changeResolutionDelay)
458 // Wait some seconds in observation of our new resolution
459 this.isAutoResolutionObservation = true
461 this.qualityObservationTimer = setTimeout(() => {
462 this.isAutoResolutionObservation = false
463 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
465 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
468 private isPlayerWaiting () {
469 return this.player && this.player.hasClass('vjs-waiting')
472 private runTorrentInfoScheduler () {
473 this.torrentInfoInterval = setInterval(() => {
474 // Not initialized yet
475 if (this.torrent === undefined) return
478 if (this.torrent === null) return this.trigger('torrentInfo', false)
480 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
481 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
483 return this.trigger('torrentInfo', {
484 downloadSpeed: this.torrent.downloadSpeed,
485 numPeers: this.torrent.numPeers,
486 uploadSpeed: this.torrent.uploadSpeed,
487 downloaded: this.torrent.downloaded,
488 uploaded: this.torrent.uploaded
490 }, this.CONSTANTS.INFO_SCHEDULER)
493 private runViewAdd () {
494 this.clearVideoViewInterval()
496 // After 30 seconds (or 3/4 of the video), add a view to the video
497 let minSecondsToView = 30
499 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
501 let secondsViewed = 0
502 this.videoViewInterval = setInterval(() => {
503 if (this.player && !this.player.paused()) {
506 if (secondsViewed > minSecondsToView) {
507 this.clearVideoViewInterval()
509 this.addViewToVideo().catch(err => console.error(err))
515 private clearVideoViewInterval () {
516 if (this.videoViewInterval !== undefined) {
517 clearInterval(this.videoViewInterval)
518 this.videoViewInterval = undefined
522 private addViewToVideo () {
523 if (!this.videoViewUrl) return Promise.resolve(undefined)
525 return fetch(this.videoViewUrl, { method: 'POST' })
528 private fallbackToHttp (done?: Function, play = true) {
529 this.disableAutoResolution(true)
531 this.flushVideoFile(this.currentVideoFile, true)
534 // Enable error display now this is our last fallback
535 this.player.one('error', () => this.enableErrorDisplay())
537 const httpUrl = this.currentVideoFile.fileUrl
538 this.player.src = this.savePlayerSrcFunction
539 this.player.src(httpUrl)
540 if (play) this.tryToPlay()
542 if (done) return done()
545 private handleError (err: Error | string) {
546 return this.player.trigger('customError', { err })
549 private enableErrorDisplay () {
550 this.player.addClass('vjs-error-display-enabled')
553 private disableErrorDisplay () {
554 this.player.removeClass('vjs-error-display-enabled')
558 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
561 private alterInactivity () {
562 let saveInactivityTimeout: number
564 const disableInactivity = () => {
565 saveInactivityTimeout = this.player.options_.inactivityTimeout
566 this.player.options_.inactivityTimeout = 0
568 const enableInactivity = () => {
569 this.player.options_.inactivityTimeout = saveInactivityTimeout
572 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
574 this.player.controlBar.on('mouseenter', () => disableInactivity())
575 settingsDialog.on('mouseenter', () => disableInactivity())
576 this.player.controlBar.on('mouseleave', () => enableInactivity())
577 settingsDialog.on('mouseleave', () => enableInactivity())
580 private pickAverageVideoFile () {
581 if (this.videoFiles.length === 1) return this.videoFiles[0]
583 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
586 private destroyFakeRenderer () {
587 if (this.fakeRenderer) {
588 if (this.fakeRenderer.destroy) {
590 this.fakeRenderer.destroy()
592 console.log('Cannot destroy correctly fake renderer.', err)
595 this.fakeRenderer = undefined
599 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
600 private initSmoothProgressBar () {
601 const SeekBar = videojsUntyped.getComponent('SeekBar')
602 SeekBar.prototype.getPercent = function getPercent () {
603 // Allows for smooth scrubbing, when player can't keep up.
604 // const time = (this.player_.scrubbing()) ?
605 // this.player_.getCache().currentTime :
606 // this.player_.currentTime()
607 const time = this.player_.currentTime()
608 const percent = time / this.player_.duration()
609 return percent >= 1 ? 1 : percent
611 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
612 let newTime = this.calculateDistance(event) * this.player_.duration()
613 if (newTime === this.player_.duration()) {
614 newTime = newTime - 0.1
616 this.player_.currentTime(newTime)
622 videojs.registerPlugin('peertube', PeerTubePlugin)
623 export { PeerTubePlugin }