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