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