Cleanup peertube plugin after dispose
[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,
11   saveAverageBandwidth,
12   saveMuteInStore,
13   saveVolumeInStore
14 } from './utils'
15 import minBy from 'lodash-es/minBy'
16 import maxBy from 'lodash-es/maxBy'
17
18 const webtorrent = new WebTorrent({
19   tracker: {
20     rtcConfig: {
21       iceServers: [
22         {
23           urls: 'stun:stun.stunprotocol.org'
24         },
25         {
26           urls: 'stun:stun.framasoft.org'
27         }
28       ]
29     }
30   },
31   dht: false
32 })
33
34 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
35 class PeerTubePlugin extends Plugin {
36   private readonly playerElement: HTMLVideoElement
37
38   private readonly autoplay: boolean = false
39   private readonly savePlayerSrcFunction: Function
40   private readonly videoFiles: VideoFile[]
41   private readonly videoViewUrl: string
42   private readonly videoDuration: number
43   private readonly CONSTANTS = {
44     INFO_SCHEDULER: 1000, // Don't change this
45     AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
46     AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
47     AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
48     AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
49     BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
50   }
51
52   private player: any
53   private currentVideoFile: VideoFile
54   private torrent: WebTorrent.Torrent
55   private autoResolution = true
56   private isAutoResolutionObservation = false
57
58   private videoViewInterval
59   private torrentInfoInterval
60   private autoQualityInterval
61   private addTorrentDelay
62   private qualityObservationTimer
63   private runAutoQualitySchedulerTimer
64
65   private downloadSpeeds: number[] = []
66
67   constructor (player: videojs.Player, options: PeertubePluginOptions) {
68     super(player, options)
69
70     // Fix canplay event on google chrome by disabling default videojs autoplay
71     this.autoplay = this.player.options_.autoplay
72     this.player.options_.autoplay = false
73
74     this.videoFiles = options.videoFiles
75     this.videoViewUrl = options.videoViewUrl
76     this.videoDuration = options.videoDuration
77
78     this.savePlayerSrcFunction = this.player.src
79     // Hack to "simulate" src link in video.js >= 6
80     // Without this, we can't play the video after pausing it
81     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
82     this.player.src = () => true
83
84     this.playerElement = options.playerElement
85
86     this.player.ready(() => {
87       const volume = getStoredVolume()
88       if (volume !== undefined) this.player.volume(volume)
89       const muted = getStoredMute()
90       if (muted !== undefined) this.player.muted(muted)
91
92       this.initializePlayer()
93       this.runTorrentInfoScheduler()
94       this.runViewAdd()
95
96       this.player.one('play', () => {
97         // Don't run immediately scheduler, wait some seconds the TCP connections are maid
98         this.runAutoQualitySchedulerTimer = setTimeout(() => {
99           this.runAutoQualityScheduler()
100         }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
101       })
102     })
103
104     this.player.on('volumechange', () => {
105       saveVolumeInStore(this.player.volume())
106       saveMuteInStore(this.player.muted())
107     })
108   }
109
110   dispose () {
111     clearTimeout(this.addTorrentDelay)
112     clearTimeout(this.qualityObservationTimer)
113     clearTimeout(this.runAutoQualitySchedulerTimer)
114
115     clearInterval(this.videoViewInterval)
116     clearInterval(this.torrentInfoInterval)
117     clearInterval(this.autoQualityInterval)
118
119     // Don't need to destroy renderer, video player will be destroyed
120     this.flushVideoFile(this.currentVideoFile, false)
121   }
122
123   getCurrentResolutionId () {
124     return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
125   }
126
127   getCurrentResolutionLabel () {
128     return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
129   }
130
131   updateVideoFile (videoFile?: VideoFile, delay = 0, done?: () => void) {
132     if (done === undefined) {
133       done = () => { /* empty */ }
134     }
135
136     // Automatically choose the adapted video file
137     if (videoFile === undefined) {
138       const savedAverageBandwidth = getAverageBandwidth()
139       videoFile = savedAverageBandwidth
140         ? this.getAppropriateFile(savedAverageBandwidth)
141         : this.videoFiles[0]
142     }
143
144     // Don't add the same video file once again
145     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
146       return
147     }
148
149     // Do not display error to user because we will have multiple fallback
150     this.disableErrorDisplay()
151
152     this.player.src = () => true
153     const oldPlaybackRate = this.player.playbackRate()
154
155     const previousVideoFile = this.currentVideoFile
156     this.currentVideoFile = videoFile
157
158     this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, delay, () => {
159       this.player.playbackRate(oldPlaybackRate)
160       return done()
161     })
162
163     this.trigger('videoFileUpdate')
164   }
165
166   addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, delay = 0, done: Function) {
167     console.log('Adding ' + magnetOrTorrentUrl + '.')
168
169     const oldTorrent = this.torrent
170     this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
171       console.log('Added ' + magnetOrTorrentUrl + '.')
172
173       // Pause the old torrent
174       if (oldTorrent) {
175         oldTorrent.pause()
176         // Pause does not remove actual peers (in particular the webseed peer)
177         oldTorrent.removePeer(oldTorrent['ws'])
178       }
179
180       this.addTorrentDelay = setTimeout(() => {
181         this.flushVideoFile(previousVideoFile)
182
183         const options = { autoplay: true, controls: true }
184         renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
185           this.renderer = renderer
186
187           if (err) return this.fallbackToHttp(done)
188
189           if (!this.player.paused()) {
190             const playPromise = this.player.play()
191             if (playPromise !== undefined) return playPromise.then(done)
192
193             return done()
194           }
195
196           return done()
197         })
198       }, delay)
199     })
200
201     this.torrent.on('error', err => this.handleError(err))
202
203     this.torrent.on('warning', (err: any) => {
204       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
205       if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
206
207       // Users don't care about issues with WebRTC, but developers do so log it in the console
208       if (err.message.indexOf('Ice connection failed') !== -1) {
209         console.error(err)
210         return
211       }
212
213       // Magnet hash is not up to date with the torrent file, add directly the torrent file
214       if (err.message.indexOf('incorrect info hash') !== -1) {
215         console.error('Incorrect info hash detected, falling back to torrent file.')
216         return this.addTorrent(this.torrent['xs'], previousVideoFile, 0, done)
217       }
218
219       return this.handleError(err)
220     })
221   }
222
223   updateResolution (resolutionId: number, delay = 0) {
224     // Remember player state
225     const currentTime = this.player.currentTime()
226     const isPaused = this.player.paused()
227
228     // Remove poster to have black background
229     this.playerElement.poster = ''
230
231     // Hide bigPlayButton
232     if (!isPaused) {
233       this.player.bigPlayButton.hide()
234     }
235
236     const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
237     this.updateVideoFile(newVideoFile, delay, () => {
238       this.player.currentTime(currentTime)
239       this.player.handleTechSeeked_()
240     })
241   }
242
243   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
244     if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
245       if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
246
247       webtorrent.remove(videoFile.magnetUri)
248       console.log('Removed ' + videoFile.magnetUri)
249     }
250   }
251
252   isAutoResolutionOn () {
253     return this.autoResolution
254   }
255
256   enableAutoResolution () {
257     this.autoResolution = true
258     this.trigger('autoResolutionUpdate')
259   }
260
261   disableAutoResolution () {
262     this.autoResolution = false
263     this.trigger('autoResolutionUpdate')
264   }
265
266   private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
267     if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
268     if (this.videoFiles.length === 1) return this.videoFiles[0]
269     if (this.torrent && this.torrent.progress === 1) return this.currentVideoFile
270
271     if (!averageDownloadSpeed) averageDownloadSpeed = this.getActualDownloadSpeed()
272
273     // Filter videos we can play according to our bandwidth
274     const filteredFiles = this.videoFiles.filter(f => {
275       const fileBitrate = (f.size / this.videoDuration)
276       let threshold = fileBitrate
277
278       // If this is for a higher resolution or an initial load: add a margin
279       if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
280         threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
281       }
282
283       return averageDownloadSpeed > threshold
284     })
285
286     // If the download speed is too bad, return the lowest resolution we have
287     if (filteredFiles.length === 0) return minBy(this.videoFiles, 'resolution.id')
288
289     return maxBy(filteredFiles, 'resolution.id')
290   }
291
292   private getActualDownloadSpeed () {
293     const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
294     const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
295     if (lastDownloadSpeeds.length === 0) return -1
296
297     const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
298     const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
299
300     // Save the average bandwidth for future use
301     saveAverageBandwidth(averageBandwidth)
302
303     return averageBandwidth
304   }
305
306   private initializePlayer () {
307     this.initSmoothProgressBar()
308
309     this.alterInactivity()
310
311     if (this.autoplay === true) {
312       this.player.posterImage.hide()
313       this.updateVideoFile(undefined, 0, () => this.player.play())
314     } else {
315       // Proxy first play
316       const oldPlay = this.player.play.bind(this.player)
317       this.player.play = () => {
318         this.updateVideoFile(undefined, 0, () => oldPlay)
319         this.player.play = oldPlay
320       }
321     }
322   }
323
324   private runAutoQualityScheduler () {
325     this.autoQualityInterval = setInterval(() => {
326
327       // Not initialized or in HTTP fallback
328       if (this.torrent === undefined || this.torrent === null) return
329       if (this.isAutoResolutionOn() === false) return
330       if (this.isAutoResolutionObservation === true) return
331
332       const file = this.getAppropriateFile()
333       let changeResolution = false
334       let changeResolutionDelay = 0
335
336       // Lower resolution
337       if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
338         console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
339         changeResolution = true
340       } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
341         console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
342         changeResolution = true
343         changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
344       }
345
346       if (changeResolution === true) {
347         this.updateResolution(file.resolution.id, changeResolutionDelay)
348
349         // Wait some seconds in observation of our new resolution
350         this.isAutoResolutionObservation = true
351
352         this.qualityObservationTimer = setTimeout(() => {
353           this.isAutoResolutionObservation = false
354         }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
355       }
356     }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
357   }
358
359   private isPlayerWaiting () {
360     return this.player && this.player.hasClass('vjs-waiting')
361   }
362
363   private runTorrentInfoScheduler () {
364     this.torrentInfoInterval = setInterval(() => {
365       // Not initialized yet
366       if (this.torrent === undefined) return
367
368       // Http fallback
369       if (this.torrent === null) return this.trigger('torrentInfo', false)
370
371       // webtorrent.downloadSpeed because we need to take into account the potential old torrent too
372       if (webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(webtorrent.downloadSpeed)
373
374       return this.trigger('torrentInfo', {
375         downloadSpeed: this.torrent.downloadSpeed,
376         numPeers: this.torrent.numPeers,
377         uploadSpeed: this.torrent.uploadSpeed
378       })
379     }, this.CONSTANTS.INFO_SCHEDULER)
380   }
381
382   private runViewAdd () {
383     this.clearVideoViewInterval()
384
385     // After 30 seconds (or 3/4 of the video), add a view to the video
386     let minSecondsToView = 30
387
388     if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
389
390     let secondsViewed = 0
391     this.videoViewInterval = setInterval(() => {
392       if (this.player && !this.player.paused()) {
393         secondsViewed += 1
394
395         if (secondsViewed > minSecondsToView) {
396           this.clearVideoViewInterval()
397
398           this.addViewToVideo().catch(err => console.error(err))
399         }
400       }
401     }, 1000)
402   }
403
404   private clearVideoViewInterval () {
405     if (this.videoViewInterval !== undefined) {
406       clearInterval(this.videoViewInterval)
407       this.videoViewInterval = undefined
408     }
409   }
410
411   private addViewToVideo () {
412     return fetch(this.videoViewUrl, { method: 'POST' })
413   }
414
415   private fallbackToHttp (done: Function) {
416     this.flushVideoFile(this.currentVideoFile, true)
417     this.torrent = null
418
419     // Enable error display now this is our last fallback
420     this.player.one('error', () => this.enableErrorDisplay())
421
422     const httpUrl = this.currentVideoFile.fileUrl
423     this.player.src = this.savePlayerSrcFunction
424     this.player.src(httpUrl)
425     this.player.play()
426
427     return done()
428   }
429
430   private handleError (err: Error | string) {
431     return this.player.trigger('customError', { err })
432   }
433
434   private enableErrorDisplay () {
435     this.player.addClass('vjs-error-display-enabled')
436   }
437
438   private disableErrorDisplay () {
439     this.player.removeClass('vjs-error-display-enabled')
440   }
441
442   private alterInactivity () {
443     let saveInactivityTimeout: number
444
445     const disableInactivity = () => {
446       saveInactivityTimeout = this.player.options_.inactivityTimeout
447       this.player.options_.inactivityTimeout = 0
448     }
449     const enableInactivity = () => {
450       this.player.options_.inactivityTimeout = saveInactivityTimeout
451     }
452
453     const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
454
455     this.player.controlBar.on('mouseenter', () => disableInactivity())
456     settingsDialog.on('mouseenter', () => disableInactivity())
457     this.player.controlBar.on('mouseleave', () => enableInactivity())
458     settingsDialog.on('mouseleave', () => enableInactivity())
459   }
460
461   // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
462   private initSmoothProgressBar () {
463     const SeekBar = videojsUntyped.getComponent('SeekBar')
464     SeekBar.prototype.getPercent = function getPercent () {
465       // Allows for smooth scrubbing, when player can't keep up.
466       // const time = (this.player_.scrubbing()) ?
467       //   this.player_.getCache().currentTime :
468       //   this.player_.currentTime()
469       const time = this.player_.currentTime()
470       const percent = time / this.player_.duration()
471       return percent >= 1 ? 1 : percent
472     }
473     SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
474       let newTime = this.calculateDistance(event) * this.player_.duration()
475       if (newTime === this.player_.duration()) {
476         newTime = newTime - 0.1
477       }
478       this.player_.currentTime(newTime)
479       this.update()
480     }
481   }
482 }
483
484 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
485 export { PeerTubePlugin }