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