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 + '.')
199 // 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
206 const fakeVideoElem = document.createElement('video')
207 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
208 fakeRenderer = renderer
210 if (err) console.error('Cannot render new torrent in fake video element.', err)
212 // Load the future file at the correct time
213 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
218 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
219 this.addTorrentDelay = setTimeout(() => {
221 if (fakeRenderer.destroy) {
223 fakeRenderer.destroy()
225 console.log('Cannot destroy correctly fake renderer.', err)
228 fakeRenderer = undefined
231 const paused = this.player.paused()
233 this.flushVideoFile(previousVideoFile)
235 const renderVideoOptions = { autoplay: false, controls: true }
236 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
237 this.renderer = renderer
239 if (err) return this.fallbackToHttp(done)
241 return this.tryToPlay(err => {
242 if (err) return done(err)
244 if (options.seek) this.seek(options.seek)
245 if (options.forcePlay === false && paused === true) this.player.pause()
248 }, options.delay || 0)
251 this.torrent.on('error', err => this.handleError(err))
253 this.torrent.on('warning', (err: any) => {
254 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
255 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
257 // Users don't care about issues with WebRTC, but developers do so log it in the console
258 if (err.message.indexOf('Ice connection failed') !== -1) {
263 // Magnet hash is not up to date with the torrent file, add directly the torrent file
264 if (err.message.indexOf('incorrect info hash') !== -1) {
265 console.error('Incorrect info hash detected, falling back to torrent file.')
266 const options = { forcePlay: true }
267 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
270 return this.handleError(err)
274 updateResolution (resolutionId: number, delay = 0) {
275 // Remember player state
276 const currentTime = this.player.currentTime()
277 const isPaused = this.player.paused()
279 // Remove poster to have black background
280 this.playerElement.poster = ''
282 // Hide bigPlayButton
284 this.player.bigPlayButton.hide()
287 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
291 seek: currentTime + (delay / 1000)
293 this.updateVideoFile(newVideoFile, options)
296 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
297 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
298 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
300 webtorrent.remove(videoFile.magnetUri)
301 console.log('Removed ' + videoFile.magnetUri)
305 isAutoResolutionOn () {
306 return this.autoResolution
309 enableAutoResolution () {
310 this.autoResolution = true
311 this.trigger('autoResolutionUpdate')
314 disableAutoResolution () {
315 this.autoResolution = false
316 this.trigger('autoResolutionUpdate')
319 getCurrentVideoFile () {
320 return this.currentVideoFile
327 private tryToPlay (done?: Function) {
328 if (!done) done = function () { /* empty */ }
330 const playPromise = this.player.play()
331 if (playPromise !== undefined) {
332 return playPromise.then(done)
336 this.player.posterImage.show()
337 this.player.removeClass('vjs-has-autoplay')
338 this.player.removeClass('vjs-has-big-play-button-clicked')
347 private seek (time: number) {
348 this.player.currentTime(time)
349 this.player.handleTechSeeked_()
352 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
353 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
354 if (this.videoFiles.length === 1) return this.videoFiles[0]
356 // Don't change the torrent is the play was ended
357 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
359 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
361 // Filter videos we can play according to our bandwidth
362 const filteredFiles = this.videoFiles.filter(f => {
363 const fileBitrate = (f.size / this.videoDuration)
364 let threshold = fileBitrate
366 // If this is for a higher resolution or an initial load: add a margin
367 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
368 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
371 return averageDownloadSpeed > threshold
374 // If the download speed is too bad, return the lowest resolution we have
375 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
377 return videoFileMaxByResolution(filteredFiles)
380 private getAndSaveActualDownloadSpeed () {
381 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
382 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
383 if (lastDownloadSpeeds.length === 0) return -1
385 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
386 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
388 // Save the average bandwidth for future use
389 saveAverageBandwidth(averageBandwidth)
391 return averageBandwidth
394 private initializePlayer () {
395 if (isMobile()) this.player.addClass('vjs-is-mobile')
397 this.initSmoothProgressBar()
399 this.alterInactivity()
401 if (this.autoplay === true) {
402 this.player.posterImage.hide()
404 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
406 // Don't try on iOS that does not support MediaSource
408 this.currentVideoFile = this.pickAverageVideoFile()
409 return this.fallbackToHttp(undefined, false)
413 const oldPlay = this.player.play.bind(this.player)
414 this.player.play = () => {
415 this.player.addClass('vjs-has-big-play-button-clicked')
416 this.player.play = oldPlay
418 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
423 private runAutoQualityScheduler () {
424 this.autoQualityInterval = setInterval(() => {
426 // Not initialized or in HTTP fallback
427 if (this.torrent === undefined || this.torrent === null) return
428 if (this.isAutoResolutionOn() === false) return
429 if (this.isAutoResolutionObservation === true) return
431 const file = this.getAppropriateFile()
432 let changeResolution = false
433 let changeResolutionDelay = 0
436 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
437 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
438 changeResolution = true
439 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
440 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
441 changeResolution = true
442 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
445 if (changeResolution === true) {
446 this.updateResolution(file.resolution.id, changeResolutionDelay)
448 // Wait some seconds in observation of our new resolution
449 this.isAutoResolutionObservation = true
451 this.qualityObservationTimer = setTimeout(() => {
452 this.isAutoResolutionObservation = false
453 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
455 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
458 private isPlayerWaiting () {
459 return this.player && this.player.hasClass('vjs-waiting')
462 private runTorrentInfoScheduler () {
463 this.torrentInfoInterval = setInterval(() => {
464 // Not initialized yet
465 if (this.torrent === undefined) return
468 if (this.torrent === null) return this.trigger('torrentInfo', false)
470 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
471 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
473 return this.trigger('torrentInfo', {
474 downloadSpeed: this.torrent.downloadSpeed,
475 numPeers: this.torrent.numPeers,
476 uploadSpeed: this.torrent.uploadSpeed
478 }, this.CONSTANTS.INFO_SCHEDULER)
481 private runViewAdd () {
482 this.clearVideoViewInterval()
484 // After 30 seconds (or 3/4 of the video), add a view to the video
485 let minSecondsToView = 30
487 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
489 let secondsViewed = 0
490 this.videoViewInterval = setInterval(() => {
491 if (this.player && !this.player.paused()) {
494 if (secondsViewed > minSecondsToView) {
495 this.clearVideoViewInterval()
497 this.addViewToVideo().catch(err => console.error(err))
503 private clearVideoViewInterval () {
504 if (this.videoViewInterval !== undefined) {
505 clearInterval(this.videoViewInterval)
506 this.videoViewInterval = undefined
510 private addViewToVideo () {
511 return fetch(this.videoViewUrl, { method: 'POST' })
514 private fallbackToHttp (done?: Function, play = true) {
515 this.flushVideoFile(this.currentVideoFile, true)
518 // Enable error display now this is our last fallback
519 this.player.one('error', () => this.enableErrorDisplay())
521 const httpUrl = this.currentVideoFile.fileUrl
522 this.player.src = this.savePlayerSrcFunction
523 this.player.src(httpUrl)
524 if (play) this.tryToPlay()
526 if (done) return done()
529 private handleError (err: Error | string) {
530 return this.player.trigger('customError', { err })
533 private enableErrorDisplay () {
534 this.player.addClass('vjs-error-display-enabled')
537 private disableErrorDisplay () {
538 this.player.removeClass('vjs-error-display-enabled')
542 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
545 private alterInactivity () {
546 let saveInactivityTimeout: number
548 const disableInactivity = () => {
549 saveInactivityTimeout = this.player.options_.inactivityTimeout
550 this.player.options_.inactivityTimeout = 0
552 const enableInactivity = () => {
553 this.player.options_.inactivityTimeout = saveInactivityTimeout
556 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
558 this.player.controlBar.on('mouseenter', () => disableInactivity())
559 settingsDialog.on('mouseenter', () => disableInactivity())
560 this.player.controlBar.on('mouseleave', () => enableInactivity())
561 settingsDialog.on('mouseleave', () => enableInactivity())
564 private pickAverageVideoFile () {
565 if (this.videoFiles.length === 1) return this.videoFiles[0]
567 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
570 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
571 private initSmoothProgressBar () {
572 const SeekBar = videojsUntyped.getComponent('SeekBar')
573 SeekBar.prototype.getPercent = function getPercent () {
574 // Allows for smooth scrubbing, when player can't keep up.
575 // const time = (this.player_.scrubbing()) ?
576 // this.player_.getCache().currentTime :
577 // this.player_.currentTime()
578 const time = this.player_.currentTime()
579 const percent = time / this.player_.duration()
580 return percent >= 1 ? 1 : percent
582 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
583 let newTime = this.calculateDistance(event) * this.player_.duration()
584 if (newTime === this.player_.duration()) {
585 newTime = newTime - 0.1
587 this.player_.currentTime(newTime)
593 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
594 export { PeerTubePlugin }