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'
10 getStoredVolume, isMobile,
14 videoFileMaxByResolution,
15 videoFileMinByResolution
17 import * as CacheChunkStore from 'cache-chunk-store'
18 import { PeertubeChunkStore } from './peertube-chunk-store'
20 const webtorrent = new WebTorrent({
25 urls: 'stun:stun.stunprotocol.org'
28 urls: 'stun:stun.framasoft.org'
36 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
37 class PeerTubePlugin extends Plugin {
38 private readonly playerElement: HTMLVideoElement
40 private readonly autoplay: boolean = false
41 private readonly startTime: number = 0
42 private readonly savePlayerSrcFunction: Function
43 private readonly videoFiles: VideoFile[]
44 private readonly videoViewUrl: string
45 private readonly videoDuration: number
46 private readonly CONSTANTS = {
47 INFO_SCHEDULER: 1000, // Don't change this
48 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
49 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
50 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
51 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
52 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
56 private currentVideoFile: VideoFile
57 private torrent: WebTorrent.Torrent
58 private autoResolution = true
59 private isAutoResolutionObservation = false
61 private videoViewInterval
62 private torrentInfoInterval
63 private autoQualityInterval
64 private addTorrentDelay
65 private qualityObservationTimer
66 private runAutoQualitySchedulerTimer
68 private downloadSpeeds: number[] = []
70 constructor (player: videojs.Player, options: PeertubePluginOptions) {
71 super(player, options)
73 // Disable auto play on iOS
74 this.autoplay = options.autoplay && this.isIOS() === false
76 this.startTime = options.startTime
77 this.videoFiles = options.videoFiles
78 this.videoViewUrl = options.videoViewUrl
79 this.videoDuration = options.videoDuration
81 this.savePlayerSrcFunction = this.player.src
82 // Hack to "simulate" src link in video.js >= 6
83 // Without this, we can't play the video after pausing it
84 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
85 this.player.src = () => true
87 this.playerElement = options.playerElement
89 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
91 this.player.ready(() => {
92 const volume = getStoredVolume()
93 if (volume !== undefined) this.player.volume(volume)
94 const muted = getStoredMute()
95 if (muted !== undefined) this.player.muted(muted)
97 this.initializePlayer()
98 this.runTorrentInfoScheduler()
101 this.player.one('play', () => {
102 // Don't run immediately scheduler, wait some seconds the TCP connections are made
103 this.runAutoQualitySchedulerTimer = setTimeout(() => {
104 this.runAutoQualityScheduler()
105 }, 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)
128 getCurrentResolutionId () {
129 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
132 getCurrentResolutionLabel () {
133 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
137 videoFile?: VideoFile,
143 done: () => void = () => { /* empty */ }
145 // Automatically choose the adapted video file
146 if (videoFile === undefined) {
147 const savedAverageBandwidth = getAverageBandwidth()
148 videoFile = savedAverageBandwidth
149 ? this.getAppropriateFile(savedAverageBandwidth)
150 : this.pickAverageVideoFile()
153 // Don't add the same video file once again
154 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
158 // Do not display error to user because we will have multiple fallback
159 this.disableErrorDisplay()
161 this.player.src = () => true
162 const oldPlaybackRate = this.player.playbackRate()
164 const previousVideoFile = this.currentVideoFile
165 this.currentVideoFile = videoFile
167 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
168 this.player.playbackRate(oldPlaybackRate)
172 this.trigger('videoFileUpdate')
176 magnetOrTorrentUrl: string,
177 previousVideoFile: VideoFile,
185 console.log('Adding ' + magnetOrTorrentUrl + '.')
187 const oldTorrent = this.torrent
189 const torrentOptions = {
190 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
195 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
196 console.log('Added ' + magnetOrTorrentUrl + '.')
198 // Pause the old torrent
201 // Pause does not remove actual peers (in particular the webseed peer)
202 oldTorrent.removePeer(oldTorrent['ws'])
204 // We use a fake renderer so we download correct pieces of the next file
205 // This way we'll be able to
207 const fakeVideoElem = document.createElement('video')
208 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
209 fakeRenderer = renderer
212 console.error('Cannot render new torrent in fake video element.', err)
215 // Load the future file at the correct time
216 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
221 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
222 this.addTorrentDelay = setTimeout(() => {
224 if (fakeRenderer.destroy) {
226 fakeRenderer.destroy()
228 console.log('Cannot destroy correctly fake renderer.', err)
231 fakeRenderer = undefined
234 const paused = this.player.paused()
236 this.flushVideoFile(previousVideoFile)
238 const renderVideoOptions = { autoplay: false, controls: true }
239 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
240 this.renderer = renderer
242 if (err) return this.fallbackToHttp(done)
244 return this.tryToPlay(err => {
245 if (err) return done(err)
247 if (options.seek) this.seek(options.seek)
248 if (options.forcePlay === false && paused === true) this.player.pause()
251 }, options.delay || 0)
254 this.torrent.on('error', err => this.handleError(err))
256 this.torrent.on('warning', (err: any) => {
257 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
258 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
260 // Users don't care about issues with WebRTC, but developers do so log it in the console
261 if (err.message.indexOf('Ice connection failed') !== -1) {
266 // Magnet hash is not up to date with the torrent file, add directly the torrent file
267 if (err.message.indexOf('incorrect info hash') !== -1) {
268 console.error('Incorrect info hash detected, falling back to torrent file.')
269 const options = { forcePlay: true }
270 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
273 return this.handleError(err)
277 updateResolution (resolutionId: number, delay = 0) {
278 // Remember player state
279 const currentTime = this.player.currentTime()
280 const isPaused = this.player.paused()
282 // Remove poster to have black background
283 this.playerElement.poster = ''
285 // Hide bigPlayButton
287 this.player.bigPlayButton.hide()
290 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
294 seek: currentTime + (delay / 1000)
296 this.updateVideoFile(newVideoFile, options)
299 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
300 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
301 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
303 webtorrent.remove(videoFile.magnetUri)
304 console.log('Removed ' + videoFile.magnetUri)
308 isAutoResolutionOn () {
309 return this.autoResolution
312 enableAutoResolution () {
313 this.autoResolution = true
314 this.trigger('autoResolutionUpdate')
317 disableAutoResolution () {
318 this.autoResolution = false
319 this.trigger('autoResolutionUpdate')
322 getCurrentVideoFile () {
323 return this.currentVideoFile
330 private tryToPlay (done?: Function) {
331 if (!done) done = function () { /* empty */ }
333 const playPromise = this.player.play()
334 if (playPromise !== undefined) {
335 return playPromise.then(done)
339 this.player.posterImage.show()
340 this.player.removeClass('vjs-has-autoplay')
341 this.player.removeClass('vjs-has-big-play-button-clicked')
350 private seek (time: number) {
351 this.player.currentTime(time)
352 this.player.handleTechSeeked_()
355 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
356 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
357 if (this.videoFiles.length === 1) return this.videoFiles[0]
359 // Don't change the torrent is the play was ended
360 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
362 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
364 // Filter videos we can play according to our bandwidth
365 const filteredFiles = this.videoFiles.filter(f => {
366 const fileBitrate = (f.size / this.videoDuration)
367 let threshold = fileBitrate
369 // If this is for a higher resolution or an initial load: add a margin
370 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
371 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
374 return averageDownloadSpeed > threshold
377 // If the download speed is too bad, return the lowest resolution we have
378 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
380 return videoFileMaxByResolution(filteredFiles)
383 private getAndSaveActualDownloadSpeed () {
384 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
385 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
386 if (lastDownloadSpeeds.length === 0) return -1
388 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
389 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
391 // Save the average bandwidth for future use
392 saveAverageBandwidth(averageBandwidth)
394 return averageBandwidth
397 private initializePlayer () {
398 if (isMobile()) this.player.addClass('vjs-is-mobile')
400 this.initSmoothProgressBar()
402 this.alterInactivity()
404 if (this.autoplay === true) {
405 this.player.posterImage.hide()
407 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
409 // Don't try on iOS that does not support MediaSource
411 this.currentVideoFile = this.pickAverageVideoFile()
412 return this.fallbackToHttp(undefined, false)
416 const oldPlay = this.player.play.bind(this.player)
417 this.player.play = () => {
418 this.player.addClass('vjs-has-big-play-button-clicked')
419 this.player.play = oldPlay
421 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
426 private runAutoQualityScheduler () {
427 this.autoQualityInterval = setInterval(() => {
429 // Not initialized or in HTTP fallback
430 if (this.torrent === undefined || this.torrent === null) return
431 if (this.isAutoResolutionOn() === false) return
432 if (this.isAutoResolutionObservation === true) return
434 const file = this.getAppropriateFile()
435 let changeResolution = false
436 let changeResolutionDelay = 0
439 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
440 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
441 changeResolution = true
442 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
443 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
444 changeResolution = true
445 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
448 if (changeResolution === true) {
449 this.updateResolution(file.resolution.id, changeResolutionDelay)
451 // Wait some seconds in observation of our new resolution
452 this.isAutoResolutionObservation = true
454 this.qualityObservationTimer = setTimeout(() => {
455 this.isAutoResolutionObservation = false
456 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
458 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
461 private isPlayerWaiting () {
462 return this.player && this.player.hasClass('vjs-waiting')
465 private runTorrentInfoScheduler () {
466 this.torrentInfoInterval = setInterval(() => {
467 // Not initialized yet
468 if (this.torrent === undefined) return
471 if (this.torrent === null) return this.trigger('torrentInfo', false)
473 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
474 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
476 return this.trigger('torrentInfo', {
477 downloadSpeed: this.torrent.downloadSpeed,
478 numPeers: this.torrent.numPeers,
479 uploadSpeed: this.torrent.uploadSpeed
481 }, this.CONSTANTS.INFO_SCHEDULER)
484 private runViewAdd () {
485 this.clearVideoViewInterval()
487 // After 30 seconds (or 3/4 of the video), add a view to the video
488 let minSecondsToView = 30
490 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
492 let secondsViewed = 0
493 this.videoViewInterval = setInterval(() => {
494 if (this.player && !this.player.paused()) {
497 if (secondsViewed > minSecondsToView) {
498 this.clearVideoViewInterval()
500 this.addViewToVideo().catch(err => console.error(err))
506 private clearVideoViewInterval () {
507 if (this.videoViewInterval !== undefined) {
508 clearInterval(this.videoViewInterval)
509 this.videoViewInterval = undefined
513 private addViewToVideo () {
514 return fetch(this.videoViewUrl, { method: 'POST' })
517 private fallbackToHttp (done?: Function, play = true) {
518 this.flushVideoFile(this.currentVideoFile, true)
521 // Enable error display now this is our last fallback
522 this.player.one('error', () => this.enableErrorDisplay())
524 const httpUrl = this.currentVideoFile.fileUrl
525 this.player.src = this.savePlayerSrcFunction
526 this.player.src(httpUrl)
527 if (play) this.tryToPlay()
529 if (done) return done()
532 private handleError (err: Error | string) {
533 return this.player.trigger('customError', { err })
536 private enableErrorDisplay () {
537 this.player.addClass('vjs-error-display-enabled')
540 private disableErrorDisplay () {
541 this.player.removeClass('vjs-error-display-enabled')
545 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
548 private alterInactivity () {
549 let saveInactivityTimeout: number
551 const disableInactivity = () => {
552 saveInactivityTimeout = this.player.options_.inactivityTimeout
553 this.player.options_.inactivityTimeout = 0
555 const enableInactivity = () => {
556 this.player.options_.inactivityTimeout = saveInactivityTimeout
559 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
561 this.player.controlBar.on('mouseenter', () => disableInactivity())
562 settingsDialog.on('mouseenter', () => disableInactivity())
563 this.player.controlBar.on('mouseleave', () => enableInactivity())
564 settingsDialog.on('mouseleave', () => enableInactivity())
567 private pickAverageVideoFile () {
568 if (this.videoFiles.length === 1) return this.videoFiles[0]
570 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
573 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
574 private initSmoothProgressBar () {
575 const SeekBar = videojsUntyped.getComponent('SeekBar')
576 SeekBar.prototype.getPercent = function getPercent () {
577 // Allows for smooth scrubbing, when player can't keep up.
578 // const time = (this.player_.scrubbing()) ?
579 // this.player_.getCache().currentTime :
580 // this.player_.currentTime()
581 const time = this.player_.currentTime()
582 const percent = time / this.player_.duration()
583 return percent >= 1 ? 1 : percent
585 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
586 let newTime = this.calculateDistance(event) * this.player_.duration()
587 if (newTime === this.player_.duration()) {
588 newTime = newTime - 0.1
590 this.player_.currentTime(newTime)
596 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
597 export { PeerTubePlugin }