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