Upgrade client dependencies
[oweals/peertube.git] / client / src / assets / player / peertube-videojs-plugin.ts
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, VideoJSCaption, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { isMobile, timeToInt, videoFileMaxByResolution, videoFileMinByResolution } from './utils'
8 import * as CacheChunkStore from 'cache-chunk-store'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
10 import {
11   getAverageBandwidthInStore,
12   getStoredMute,
13   getStoredVolume,
14   saveAverageBandwidth,
15   saveMuteInStore,
16   saveVolumeInStore
17 } from './peertube-player-local-storage'
18
19 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
20 class PeerTubePlugin extends Plugin {
21   private readonly playerElement: HTMLVideoElement
22
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
36   }
37
38   private readonly webtorrent = new WebTorrent({
39     tracker: {
40       rtcConfig: {
41         iceServers: [
42           {
43             urls: 'stun:stun.stunprotocol.org'
44           },
45           {
46             urls: 'stun:stun.framasoft.org'
47           }
48         ]
49       }
50     },
51     dht: false
52   })
53
54   private player: any
55   private currentVideoFile: VideoFile
56   private torrent: WebTorrent.Torrent
57   private videoCaptions: VideoJSCaption[]
58   private renderer
59   private fakeRenderer
60   private autoResolution = true
61   private forbidAutoResolution = false
62   private isAutoResolutionObservation = false
63
64   private videoViewInterval
65   private torrentInfoInterval
66   private autoQualityInterval
67   private addTorrentDelay
68   private qualityObservationTimer
69   private runAutoQualitySchedulerTimer
70
71   private downloadSpeeds: number[] = []
72
73   constructor (player: videojs.Player, options: PeertubePluginOptions) {
74     super(player, options)
75
76     // Disable auto play on iOS
77     this.autoplay = options.autoplay && this.isIOS() === false
78
79     this.startTime = timeToInt(options.startTime)
80     this.videoFiles = options.videoFiles
81     this.videoViewUrl = options.videoViewUrl
82     this.videoDuration = options.videoDuration
83     this.videoCaptions = options.videoCaptions
84
85     this.savePlayerSrcFunction = this.player.src
86     this.playerElement = options.playerElement
87
88     if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
89
90     this.player.ready(() => {
91       const volume = getStoredVolume()
92       if (volume !== undefined) this.player.volume(volume)
93       const muted = getStoredMute()
94       if (muted !== undefined) this.player.muted(muted)
95
96       this.initializePlayer()
97       this.runTorrentInfoScheduler()
98       this.runViewAdd()
99
100       this.player.one('play', () => {
101         // Don't run immediately scheduler, wait some seconds the TCP connections are made
102         this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
103       })
104     })
105
106     this.player.on('volumechange', () => {
107       saveVolumeInStore(this.player.volume())
108       saveMuteInStore(this.player.muted())
109     })
110   }
111
112   dispose () {
113     clearTimeout(this.addTorrentDelay)
114     clearTimeout(this.qualityObservationTimer)
115     clearTimeout(this.runAutoQualitySchedulerTimer)
116
117     clearInterval(this.videoViewInterval)
118     clearInterval(this.torrentInfoInterval)
119     clearInterval(this.autoQualityInterval)
120
121     // Don't need to destroy renderer, video player will be destroyed
122     this.flushVideoFile(this.currentVideoFile, false)
123
124     this.destroyFakeRenderer()
125   }
126
127   getCurrentResolutionId () {
128     return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
129   }
130
131   getCurrentResolutionLabel () {
132     if (!this.currentVideoFile) return ''
133
134     const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
135     return this.currentVideoFile.resolution.label + fps
136   }
137
138   updateVideoFile (
139     videoFile?: VideoFile,
140     options: {
141       forcePlay?: boolean,
142       seek?: number,
143       delay?: number
144     } = {},
145     done: () => void = () => { /* empty */ }
146   ) {
147     // Automatically choose the adapted video file
148     if (videoFile === undefined) {
149       const savedAverageBandwidth = getAverageBandwidthInStore()
150       videoFile = savedAverageBandwidth
151         ? this.getAppropriateFile(savedAverageBandwidth)
152         : this.pickAverageVideoFile()
153     }
154
155     // Don't add the same video file once again
156     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
157       return
158     }
159
160     // Do not display error to user because we will have multiple fallback
161     this.disableErrorDisplay()
162
163     // Hack to "simulate" src link in video.js >= 6
164     // Without this, we can't play the video after pausing it
165     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
166     this.player.src = () => true
167     const oldPlaybackRate = this.player.playbackRate()
168
169     const previousVideoFile = this.currentVideoFile
170     this.currentVideoFile = videoFile
171
172     this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
173       this.player.playbackRate(oldPlaybackRate)
174       return done()
175     })
176
177     this.trigger('videoFileUpdate')
178   }
179
180   updateResolution (resolutionId: number, delay = 0) {
181     // Remember player state
182     const currentTime = this.player.currentTime()
183     const isPaused = this.player.paused()
184
185     // Remove poster to have black background
186     this.playerElement.poster = ''
187
188     // Hide bigPlayButton
189     if (!isPaused) {
190       this.player.bigPlayButton.hide()
191     }
192
193     const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
194     const options = {
195       forcePlay: false,
196       delay,
197       seek: currentTime + (delay / 1000)
198     }
199     this.updateVideoFile(newVideoFile, options)
200   }
201
202   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
203     if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
204       if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
205
206       this.webtorrent.remove(videoFile.magnetUri)
207       console.log('Removed ' + videoFile.magnetUri)
208     }
209   }
210
211   isAutoResolutionOn () {
212     return this.autoResolution
213   }
214
215   enableAutoResolution () {
216     this.autoResolution = true
217     this.trigger('autoResolutionUpdate')
218   }
219
220   disableAutoResolution (forbid = false) {
221     if (forbid === true) this.forbidAutoResolution = true
222
223     this.autoResolution = false
224     this.trigger('autoResolutionUpdate')
225   }
226
227   isAutoResolutionForbidden () {
228     return this.forbidAutoResolution === true
229   }
230
231   getCurrentVideoFile () {
232     return this.currentVideoFile
233   }
234
235   getTorrent () {
236     return this.torrent
237   }
238
239   private addTorrent (
240     magnetOrTorrentUrl: string,
241     previousVideoFile: VideoFile,
242     options: {
243       forcePlay?: boolean,
244       seek?: number,
245       delay?: number
246     },
247     done: Function
248   ) {
249     console.log('Adding ' + magnetOrTorrentUrl + '.')
250
251     const oldTorrent = this.torrent
252     const torrentOptions = {
253       store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
254         max: 100
255       })
256     }
257
258     this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
259       console.log('Added ' + magnetOrTorrentUrl + '.')
260
261       if (oldTorrent) {
262         // Pause the old torrent
263         this.stopTorrent(oldTorrent)
264
265         // We use a fake renderer so we download correct pieces of the next file
266         if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
267       }
268
269       // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
270       this.addTorrentDelay = setTimeout(() => {
271         // We don't need the fake renderer anymore
272         this.destroyFakeRenderer()
273
274         const paused = this.player.paused()
275
276         this.flushVideoFile(previousVideoFile)
277
278         const renderVideoOptions = { autoplay: false, controls: true }
279         renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
280           this.renderer = renderer
281
282           if (err) return this.fallbackToHttp(done)
283
284           return this.tryToPlay(err => {
285             if (err) return done(err)
286
287             if (options.seek) this.seek(options.seek)
288             if (options.forcePlay === false && paused === true) this.player.pause()
289
290             return done(err)
291           })
292         })
293       }, options.delay || 0)
294     })
295
296     this.torrent.on('error', err => console.error(err))
297
298     this.torrent.on('warning', (err: any) => {
299       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
300       if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
301
302       // Users don't care about issues with WebRTC, but developers do so log it in the console
303       if (err.message.indexOf('Ice connection failed') !== -1) {
304         console.log(err)
305         return
306       }
307
308       // Magnet hash is not up to date with the torrent file, add directly the torrent file
309       if (err.message.indexOf('incorrect info hash') !== -1) {
310         console.error('Incorrect info hash detected, falling back to torrent file.')
311         const newOptions = { forcePlay: true, seek: options.seek }
312         return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
313       }
314
315       // Remote instance is down
316       if (err.message.indexOf('from xs param') !== -1) {
317         this.handleError(err)
318       }
319
320       console.warn(err)
321     })
322   }
323
324   private tryToPlay (done?: Function) {
325     if (!done) done = function () { /* empty */ }
326
327     const playPromise = this.player.play()
328     if (playPromise !== undefined) {
329       return playPromise.then(done)
330                         .catch(err => {
331                           if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
332                             return
333                           }
334
335                           console.error(err)
336                           this.player.pause()
337                           this.player.posterImage.show()
338                           this.player.removeClass('vjs-has-autoplay')
339                           this.player.removeClass('vjs-has-big-play-button-clicked')
340
341                           return done()
342                         })
343     }
344
345     return done()
346   }
347
348   private seek (time: number) {
349     this.player.currentTime(time)
350     this.player.handleTechSeeked_()
351   }
352
353   private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
354     if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
355     if (this.videoFiles.length === 1) return this.videoFiles[0]
356
357     // Don't change the torrent is the play was ended
358     if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
359
360     if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
361
362     // Limit resolution according to player height
363     const playerHeight = this.playerElement.offsetHeight as number
364
365     // We take the first resolution just above the player height
366     // Example: player height is 530px, we want the 720p file instead of 480p
367     let maxResolution = this.videoFiles[0].resolution.id
368     for (let i = this.videoFiles.length - 1; i >= 0; i--) {
369       const resolutionId = this.videoFiles[i].resolution.id
370       if (resolutionId >= playerHeight) {
371         maxResolution = resolutionId
372         break
373       }
374     }
375
376     // Filter videos we can play according to our screen resolution and bandwidth
377     const filteredFiles = this.videoFiles
378                               .filter(f => f.resolution.id <= maxResolution)
379                               .filter(f => {
380                                 const fileBitrate = (f.size / this.videoDuration)
381                                 let threshold = fileBitrate
382
383                                 // If this is for a higher resolution or an initial load: add a margin
384                                 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
385                                   threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
386                                 }
387
388                                 return averageDownloadSpeed > threshold
389                               })
390
391     // If the download speed is too bad, return the lowest resolution we have
392     if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
393
394     return videoFileMaxByResolution(filteredFiles)
395   }
396
397   private getAndSaveActualDownloadSpeed () {
398     const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
399     const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
400     if (lastDownloadSpeeds.length === 0) return -1
401
402     const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
403     const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
404
405     // Save the average bandwidth for future use
406     saveAverageBandwidth(averageBandwidth)
407
408     return averageBandwidth
409   }
410
411   private initializePlayer () {
412     if (isMobile()) this.player.addClass('vjs-is-mobile')
413
414     this.initSmoothProgressBar()
415
416     this.initCaptions()
417
418     this.alterInactivity()
419
420     if (this.autoplay === true) {
421       this.player.posterImage.hide()
422
423       return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
424     }
425
426     // Don't try on iOS that does not support MediaSource
427     if (this.isIOS()) {
428       this.currentVideoFile = this.pickAverageVideoFile()
429       return this.fallbackToHttp(undefined, false)
430     }
431
432     // Proxy first play
433     const oldPlay = this.player.play.bind(this.player)
434     this.player.play = () => {
435       this.player.addClass('vjs-has-big-play-button-clicked')
436       this.player.play = oldPlay
437
438       this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
439     }
440   }
441
442   private runAutoQualityScheduler () {
443     this.autoQualityInterval = setInterval(() => {
444
445       // Not initialized or in HTTP fallback
446       if (this.torrent === undefined || this.torrent === null) return
447       if (this.isAutoResolutionOn() === false) return
448       if (this.isAutoResolutionObservation === true) return
449
450       const file = this.getAppropriateFile()
451       let changeResolution = false
452       let changeResolutionDelay = 0
453
454       // Lower resolution
455       if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
456         console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
457         changeResolution = true
458       } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
459         console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
460         changeResolution = true
461         changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
462       }
463
464       if (changeResolution === true) {
465         this.updateResolution(file.resolution.id, changeResolutionDelay)
466
467         // Wait some seconds in observation of our new resolution
468         this.isAutoResolutionObservation = true
469
470         this.qualityObservationTimer = setTimeout(() => {
471           this.isAutoResolutionObservation = false
472         }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
473       }
474     }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
475   }
476
477   private isPlayerWaiting () {
478     return this.player && this.player.hasClass('vjs-waiting')
479   }
480
481   private runTorrentInfoScheduler () {
482     this.torrentInfoInterval = setInterval(() => {
483       // Not initialized yet
484       if (this.torrent === undefined) return
485
486       // Http fallback
487       if (this.torrent === null) return this.trigger('torrentInfo', false)
488
489       // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
490       if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
491
492       return this.trigger('torrentInfo', {
493         downloadSpeed: this.torrent.downloadSpeed,
494         numPeers: this.torrent.numPeers,
495         uploadSpeed: this.torrent.uploadSpeed,
496         downloaded: this.torrent.downloaded,
497         uploaded: this.torrent.uploaded
498       })
499     }, this.CONSTANTS.INFO_SCHEDULER)
500   }
501
502   private runViewAdd () {
503     this.clearVideoViewInterval()
504
505     // After 30 seconds (or 3/4 of the video), add a view to the video
506     let minSecondsToView = 30
507
508     if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
509
510     let secondsViewed = 0
511     this.videoViewInterval = setInterval(() => {
512       if (this.player && !this.player.paused()) {
513         secondsViewed += 1
514
515         if (secondsViewed > minSecondsToView) {
516           this.clearVideoViewInterval()
517
518           this.addViewToVideo().catch(err => console.error(err))
519         }
520       }
521     }, 1000)
522   }
523
524   private clearVideoViewInterval () {
525     if (this.videoViewInterval !== undefined) {
526       clearInterval(this.videoViewInterval)
527       this.videoViewInterval = undefined
528     }
529   }
530
531   private addViewToVideo () {
532     if (!this.videoViewUrl) return Promise.resolve(undefined)
533
534     return fetch(this.videoViewUrl, { method: 'POST' })
535   }
536
537   private fallbackToHttp (done?: Function, play = true) {
538     this.disableAutoResolution(true)
539
540     this.flushVideoFile(this.currentVideoFile, true)
541     this.torrent = null
542
543     // Enable error display now this is our last fallback
544     this.player.one('error', () => this.enableErrorDisplay())
545
546     const httpUrl = this.currentVideoFile.fileUrl
547     this.player.src = this.savePlayerSrcFunction
548     this.player.src(httpUrl)
549     if (play) this.tryToPlay()
550
551     if (done) return done()
552   }
553
554   private handleError (err: Error | string) {
555     return this.player.trigger('customError', { err })
556   }
557
558   private enableErrorDisplay () {
559     this.player.addClass('vjs-error-display-enabled')
560   }
561
562   private disableErrorDisplay () {
563     this.player.removeClass('vjs-error-display-enabled')
564   }
565
566   private isIOS () {
567     return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
568   }
569
570   private alterInactivity () {
571     let saveInactivityTimeout: number
572
573     const disableInactivity = () => {
574       saveInactivityTimeout = this.player.options_.inactivityTimeout
575       this.player.options_.inactivityTimeout = 0
576     }
577     const enableInactivity = () => {
578       this.player.options_.inactivityTimeout = saveInactivityTimeout
579     }
580
581     const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
582
583     this.player.controlBar.on('mouseenter', () => disableInactivity())
584     settingsDialog.on('mouseenter', () => disableInactivity())
585     this.player.controlBar.on('mouseleave', () => enableInactivity())
586     settingsDialog.on('mouseleave', () => enableInactivity())
587   }
588
589   private pickAverageVideoFile () {
590     if (this.videoFiles.length === 1) return this.videoFiles[0]
591
592     return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
593   }
594
595   private stopTorrent (torrent: WebTorrent.Torrent) {
596     torrent.pause()
597     // Pause does not remove actual peers (in particular the webseed peer)
598     torrent.removePeer(torrent[ 'ws' ])
599   }
600
601   private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
602     const fakeVideoElem = document.createElement('video')
603     renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
604       this.fakeRenderer = renderer
605
606       if (err) console.error('Cannot render new torrent in fake video element.', err)
607
608       // Load the future file at the correct time (in delay MS - 2 seconds)
609       fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
610     })
611   }
612
613   private destroyFakeRenderer () {
614     if (this.fakeRenderer) {
615       if (this.fakeRenderer.destroy) {
616         try {
617           this.fakeRenderer.destroy()
618         } catch (err) {
619           console.log('Cannot destroy correctly fake renderer.', err)
620         }
621       }
622       this.fakeRenderer = undefined
623     }
624   }
625
626   private initCaptions () {
627     for (const caption of this.videoCaptions) {
628       this.player.addRemoteTextTrack({
629         kind: 'captions',
630         label: caption.label,
631         language: caption.language,
632         id: caption.language,
633         src: caption.src
634       }, false)
635     }
636   }
637
638   // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
639   private initSmoothProgressBar () {
640     const SeekBar = videojsUntyped.getComponent('SeekBar')
641     SeekBar.prototype.getPercent = function getPercent () {
642       // Allows for smooth scrubbing, when player can't keep up.
643       // const time = (this.player_.scrubbing()) ?
644       //   this.player_.getCache().currentTime :
645       //   this.player_.currentTime()
646       const time = this.player_.currentTime()
647       const percent = time / this.player_.duration()
648       return percent >= 1 ? 1 : percent
649     }
650     SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
651       let newTime = this.calculateDistance(event) * this.player_.duration()
652       if (newTime === this.player_.duration()) {
653         newTime = newTime - 0.1
654       }
655       this.player_.currentTime(newTime)
656       this.update()
657     }
658   }
659 }
660
661 videojs.registerPlugin('peertube', PeerTubePlugin)
662 export { PeerTubePlugin }