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'
16 import minBy from 'lodash-es/minBy'
17 import maxBy from 'lodash-es/maxBy'
18 import * as CacheChunkStore from 'cache-chunk-store'
19 import { PeertubeChunkStore } from './peertube-chunk-store'
21 const webtorrent = new WebTorrent({
26 urls: 'stun:stun.stunprotocol.org'
29 urls: 'stun:stun.framasoft.org'
37 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
38 class PeerTubePlugin extends Plugin {
39 private readonly playerElement: HTMLVideoElement
41 private readonly autoplay: boolean = false
42 private readonly startTime: number = 0
43 private readonly savePlayerSrcFunction: Function
44 private readonly videoFiles: VideoFile[]
45 private readonly videoViewUrl: string
46 private readonly videoDuration: number
47 private readonly CONSTANTS = {
48 INFO_SCHEDULER: 1000, // Don't change this
49 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
50 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
51 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
52 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
53 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
57 private currentVideoFile: VideoFile
58 private torrent: WebTorrent.Torrent
59 private autoResolution = true
60 private isAutoResolutionObservation = false
62 private videoViewInterval
63 private torrentInfoInterval
64 private autoQualityInterval
65 private addTorrentDelay
66 private qualityObservationTimer
67 private runAutoQualitySchedulerTimer
69 private downloadSpeeds: number[] = []
71 constructor (player: videojs.Player, options: PeertubePluginOptions) {
72 super(player, options)
74 // Disable auto play on iOS
75 this.autoplay = options.autoplay && this.isIOS() === false
77 this.startTime = options.startTime
78 this.videoFiles = options.videoFiles
79 this.videoViewUrl = options.videoViewUrl
80 this.videoDuration = options.videoDuration
82 this.savePlayerSrcFunction = this.player.src
83 // Hack to "simulate" src link in video.js >= 6
84 // Without this, we can't play the video after pausing it
85 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
86 this.player.src = () => true
88 this.playerElement = options.playerElement
90 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
92 this.player.ready(() => {
93 const volume = getStoredVolume()
94 if (volume !== undefined) this.player.volume(volume)
95 const muted = getStoredMute()
96 if (muted !== undefined) this.player.muted(muted)
98 this.initializePlayer()
99 this.runTorrentInfoScheduler()
102 this.player.one('play', () => {
103 // Don't run immediately scheduler, wait some seconds the TCP connections are made
104 this.runAutoQualitySchedulerTimer = setTimeout(() => {
105 this.runAutoQualityScheduler()
106 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
110 this.player.on('volumechange', () => {
111 saveVolumeInStore(this.player.volume())
112 saveMuteInStore(this.player.muted())
117 clearTimeout(this.addTorrentDelay)
118 clearTimeout(this.qualityObservationTimer)
119 clearTimeout(this.runAutoQualitySchedulerTimer)
121 clearInterval(this.videoViewInterval)
122 clearInterval(this.torrentInfoInterval)
123 clearInterval(this.autoQualityInterval)
125 // Don't need to destroy renderer, video player will be destroyed
126 this.flushVideoFile(this.currentVideoFile, false)
129 getCurrentResolutionId () {
130 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
133 getCurrentResolutionLabel () {
134 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
137 updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
138 if (done === undefined) {
139 done = () => { /* empty */ }
142 // Automatically choose the adapted video file
143 if (videoFile === undefined) {
144 const savedAverageBandwidth = getAverageBandwidth()
145 videoFile = savedAverageBandwidth
146 ? this.getAppropriateFile(savedAverageBandwidth)
150 // Don't add the same video file once again
151 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
155 // Do not display error to user because we will have multiple fallback
156 this.disableErrorDisplay()
158 this.player.src = () => true
159 const oldPlaybackRate = this.player.playbackRate()
161 const previousVideoFile = this.currentVideoFile
162 this.currentVideoFile = videoFile
164 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
165 this.player.playbackRate(oldPlaybackRate)
169 this.trigger('videoFileUpdate')
172 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
173 console.log('Adding ' + magnetOrTorrentUrl + '.')
175 const oldTorrent = this.torrent
177 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
182 this.torrent = webtorrent.add(magnetOrTorrentUrl, options, torrent => {
183 console.log('Added ' + magnetOrTorrentUrl + '.')
185 // Pause the old torrent
188 // Pause does not remove actual peers (in particular the webseed peer)
189 oldTorrent.removePeer(oldTorrent['ws'])
192 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
193 this.addTorrentDelay = setTimeout(() => {
194 this.flushVideoFile(previousVideoFile)
196 const options = { autoplay: true, controls: true }
197 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
198 this.renderer = renderer
200 if (err) return this.fallbackToHttp(done)
202 if (!this.player.paused()) return this.tryToPlay(done)
209 this.torrent.on('error', err => this.handleError(err))
211 this.torrent.on('warning', (err: any) => {
212 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
213 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
215 // Users don't care about issues with WebRTC, but developers do so log it in the console
216 if (err.message.indexOf('Ice connection failed') !== -1) {
221 // Magnet hash is not up to date with the torrent file, add directly the torrent file
222 if (err.message.indexOf('incorrect info hash') !== -1) {
223 console.error('Incorrect info hash detected, falling back to torrent file.')
224 return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
227 return this.handleError(err)
231 updateResolution (resolutionId: number, delay = 0) {
232 // Remember player state
233 const currentTime = this.player.currentTime()
234 const isPaused = this.player.paused()
236 // Remove poster to have black background
237 this.playerElement.poster = ''
239 // Hide bigPlayButton
241 this.player.bigPlayButton.hide()
244 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
245 this.updateVideoFile(newVideoFile, delay, () => this.seek(currentTime))
248 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
249 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
250 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
252 webtorrent.remove(videoFile.magnetUri)
253 console.log('Removed ' + videoFile.magnetUri)
257 isAutoResolutionOn () {
258 return this.autoResolution
261 enableAutoResolution () {
262 this.autoResolution = true
263 this.trigger('autoResolutionUpdate')
266 disableAutoResolution () {
267 this.autoResolution = false
268 this.trigger('autoResolutionUpdate')
271 getCurrentVideoFile () {
272 return this.currentVideoFile
275 private tryToPlay (done?: Function) {
276 if (!done) done = function () { /* empty */ }
278 const playPromise = this.player.play()
279 if (playPromise !== undefined) {
280 return playPromise.then(done)
284 this.player.posterImage.show()
285 this.player.removeClass('vjs-has-autoplay')
294 private seek (time: number) {
295 this.player.currentTime(time)
296 this.player.handleTechSeeked_()
299 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
300 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
301 if (this.videoFiles.length === 1) return this.videoFiles[0]
303 // Don't change the torrent is the play was ended
304 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
306 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
308 // Filter videos we can play according to our bandwidth
309 const filteredFiles = this.videoFiles.filter(f => {
310 const fileBitrate = (f.size / this.videoDuration)
311 let threshold = fileBitrate
313 // If this is for a higher resolution or an initial load: add a margin
314 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
315 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
318 return averageDownloadSpeed > threshold
321 // If the download speed is too bad, return the lowest resolution we have
322 if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
324 return maxBy(filteredFiles, 'resolution.id')
327 private getAndSaveActualDownloadSpeed () {
328 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
329 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
330 if (lastDownloadSpeeds.length === 0) return -1
332 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
333 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
335 // Save the average bandwidth for future use
336 saveAverageBandwidth(averageBandwidth)
338 return averageBandwidth
341 private initializePlayer () {
342 this.initSmoothProgressBar()
344 this.alterInactivity()
346 if (this.autoplay === true) {
347 this.player.posterImage.hide()
349 this.updateVideoFile(undefined, 0, () => {
350 this.seek(this.startTime)
354 // Don't try on iOS that does not support MediaSource
356 this.currentVideoFile = this.videoFiles[0]
357 return this.fallbackToHttp(undefined, false)
361 const oldPlay = this.player.play.bind(this.player)
362 this.player.play = () => {
363 this.player.addClass('vjs-has-big-play-button-clicked')
364 this.player.play = oldPlay
366 this.updateVideoFile(undefined, 0, () => this.seek(this.startTime))
371 private runAutoQualityScheduler () {
372 this.autoQualityInterval = setInterval(() => {
374 // Not initialized or in HTTP fallback
375 if (this.torrent === undefined || this.torrent === null) return
376 if (this.isAutoResolutionOn() === false) return
377 if (this.isAutoResolutionObservation === true) return
379 const file = this.getAppropriateFile()
380 let changeResolution = false
381 let changeResolutionDelay = 0
384 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
385 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
386 changeResolution = true
387 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
388 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
389 changeResolution = true
390 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
393 if (changeResolution === true) {
394 this.updateResolution(file.resolution.id, changeResolutionDelay)
396 // Wait some seconds in observation of our new resolution
397 this.isAutoResolutionObservation = true
399 this.qualityObservationTimer = setTimeout(() => {
400 this.isAutoResolutionObservation = false
401 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
403 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
406 private isPlayerWaiting () {
407 return this.player && this.player.hasClass('vjs-waiting')
410 private runTorrentInfoScheduler () {
411 this.torrentInfoInterval = setInterval(() => {
412 // Not initialized yet
413 if (this.torrent === undefined) return
416 if (this.torrent === null) return this.trigger('torrentInfo', false)
418 // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
419 if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
421 return this.trigger('torrentInfo', {
422 downloadSpeed: this.torrent.downloadSpeed,
423 numPeers: this.torrent.numPeers,
424 uploadSpeed: this.torrent.uploadSpeed
426 }, this.CONSTANTS.INFO_SCHEDULER)
429 private runViewAdd () {
430 this.clearVideoViewInterval()
432 // After 30 seconds (or 3/4 of the video), add a view to the video
433 let minSecondsToView = 30
435 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
437 let secondsViewed = 0
438 this.videoViewInterval = setInterval(() => {
439 if (this.player && !this.player.paused()) {
442 if (secondsViewed > minSecondsToView) {
443 this.clearVideoViewInterval()
445 this.addViewToVideo().catch(err => console.error(err))
451 private clearVideoViewInterval () {
452 if (this.videoViewInterval !== undefined) {
453 clearInterval(this.videoViewInterval)
454 this.videoViewInterval = undefined
458 private addViewToVideo () {
459 return fetch(this.videoViewUrl, { method: 'POST' })
462 private fallbackToHttp (done?: Function, play = true) {
463 this.flushVideoFile(this.currentVideoFile, true)
466 // Enable error display now this is our last fallback
467 this.player.one('error', () => this.enableErrorDisplay())
469 const httpUrl = this.currentVideoFile.fileUrl
470 this.player.src = this.savePlayerSrcFunction
471 this.player.src(httpUrl)
472 if (play) this.tryToPlay()
474 if (done) return done()
477 private handleError (err: Error | string) {
478 return this.player.trigger('customError', { err })
481 private enableErrorDisplay () {
482 this.player.addClass('vjs-error-display-enabled')
485 private disableErrorDisplay () {
486 this.player.removeClass('vjs-error-display-enabled')
490 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
493 private alterInactivity () {
494 let saveInactivityTimeout: number
496 const disableInactivity = () => {
497 saveInactivityTimeout = this.player.options_.inactivityTimeout
498 this.player.options_.inactivityTimeout = 0
500 const enableInactivity = () => {
501 this.player.options_.inactivityTimeout = saveInactivityTimeout
504 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
506 this.player.controlBar.on('mouseenter', () => disableInactivity())
507 settingsDialog.on('mouseenter', () => disableInactivity())
508 this.player.controlBar.on('mouseleave', () => enableInactivity())
509 settingsDialog.on('mouseleave', () => enableInactivity())
512 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
513 private initSmoothProgressBar () {
514 const SeekBar = videojsUntyped.getComponent('SeekBar')
515 SeekBar.prototype.getPercent = function getPercent () {
516 // Allows for smooth scrubbing, when player can't keep up.
517 // const time = (this.player_.scrubbing()) ?
518 // this.player_.getCache().currentTime :
519 // this.player_.currentTime()
520 const time = this.player_.currentTime()
521 const percent = time / this.player_.duration()
522 return percent >= 1 ? 1 : percent
524 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
525 let newTime = this.calculateDistance(event) * this.player_.duration()
526 if (newTime === this.player_.duration()) {
527 newTime = newTime - 0.1
529 this.player_.currentTime(newTime)
535 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
536 export { PeerTubePlugin }