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