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