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