Improve 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, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { getStoredMute, getStoredVolume, saveMuteInStore, saveVolumeInStore } from './utils'
8
9 const webtorrent = new WebTorrent({
10   tracker: {
11     rtcConfig: {
12       iceServers: [
13         {
14           urls: 'stun:stun.stunprotocol.org'
15         },
16         {
17           urls: 'stun:stun.framasoft.org'
18         }
19       ]
20     }
21   },
22   dht: false
23 })
24
25 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
26 class PeerTubePlugin extends Plugin {
27   private readonly playerElement: HTMLVideoElement
28   private readonly autoplay: boolean = false
29   private readonly savePlayerSrcFunction: Function
30   private player: any
31   private currentVideoFile: VideoFile
32   private videoFiles: VideoFile[]
33   private torrent: WebTorrent.Torrent
34   private videoViewUrl: string
35   private videoDuration: number
36   private videoViewInterval
37   private torrentInfoInterval
38
39   constructor (player: videojs.Player, options: PeertubePluginOptions) {
40     super(player, options)
41
42     // Fix canplay event on google chrome by disabling default videojs autoplay
43     this.autoplay = this.player.options_.autoplay
44     this.player.options_.autoplay = false
45
46     this.videoFiles = options.videoFiles
47     this.videoViewUrl = options.videoViewUrl
48     this.videoDuration = options.videoDuration
49
50     this.savePlayerSrcFunction = this.player.src
51     // Hack to "simulate" src link in video.js >= 6
52     // Without this, we can't play the video after pausing it
53     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
54     this.player.src = () => true
55
56     this.playerElement = options.playerElement
57
58     this.player.ready(() => {
59       const volume = getStoredVolume()
60       if (volume !== undefined) this.player.volume(volume)
61       const muted = getStoredMute()
62       if (muted !== undefined) this.player.muted(muted)
63
64       this.initializePlayer()
65       this.runTorrentInfoScheduler()
66       this.runViewAdd()
67     })
68
69     this.player.on('volumechange', () => {
70       saveVolumeInStore(this.player.volume())
71       saveMuteInStore(this.player.muted())
72     })
73   }
74
75   dispose () {
76     clearInterval(this.videoViewInterval)
77     clearInterval(this.torrentInfoInterval)
78
79     // Don't need to destroy renderer, video player will be destroyed
80     this.flushVideoFile(this.currentVideoFile, false)
81   }
82
83   getCurrentResolutionId () {
84     return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
85   }
86
87   getCurrentResolutionLabel () {
88     return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
89   }
90
91   updateVideoFile (videoFile?: VideoFile, done?: () => void) {
92     if (done === undefined) {
93       done = () => { /* empty */ }
94     }
95
96     // Pick the first one
97     if (videoFile === undefined) {
98       videoFile = this.videoFiles[0]
99     }
100
101     // Don't add the same video file once again
102     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
103       return
104     }
105
106     // Do not display error to user because we will have multiple fallback
107     this.disableErrorDisplay()
108
109     this.player.src = () => true
110     const oldPlaybackRate = this.player.playbackRate()
111
112     const previousVideoFile = this.currentVideoFile
113     this.currentVideoFile = videoFile
114
115     this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, () => {
116       this.player.playbackRate(oldPlaybackRate)
117       return done()
118     })
119
120     this.trigger('videoFileUpdate')
121   }
122
123   addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, done: Function) {
124     console.log('Adding ' + magnetOrTorrentUrl + '.')
125
126     this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
127       console.log('Added ' + magnetOrTorrentUrl + '.')
128
129       this.flushVideoFile(previousVideoFile)
130
131       const options = { autoplay: true, controls: true }
132       renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
133         this.renderer = renderer
134
135         if (err) return this.fallbackToHttp(done)
136
137         if (!this.player.paused()) {
138           const playPromise = this.player.play()
139           if (playPromise !== undefined) return playPromise.then(done)
140
141           return done()
142         }
143
144         return done()
145       })
146     })
147
148     this.torrent.on('error', err => this.handleError(err))
149
150     this.torrent.on('warning', (err: any) => {
151       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
152       if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
153
154       // Users don't care about issues with WebRTC, but developers do so log it in the console
155       if (err.message.indexOf('Ice connection failed') !== -1) {
156         console.error(err)
157         return
158       }
159
160       // Magnet hash is not up to date with the torrent file, add directly the torrent file
161       if (err.message.indexOf('incorrect info hash') !== -1) {
162         console.error('Incorrect info hash detected, falling back to torrent file.')
163         return this.addTorrent(this.torrent['xs'], previousVideoFile, done)
164       }
165
166       return this.handleError(err)
167     })
168   }
169
170   updateResolution (resolutionId: number) {
171     // Remember player state
172     const currentTime = this.player.currentTime()
173     const isPaused = this.player.paused()
174
175     // Remove poster to have black background
176     this.playerElement.poster = ''
177
178     // Hide bigPlayButton
179     if (!isPaused) {
180       this.player.bigPlayButton.hide()
181     }
182
183     const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
184     this.updateVideoFile(newVideoFile, () => {
185       this.player.currentTime(currentTime)
186       this.player.handleTechSeeked_()
187     })
188   }
189
190   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
191     if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
192       if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
193
194       webtorrent.remove(videoFile.magnetUri)
195       console.log('Removed ' + videoFile.magnetUri)
196     }
197   }
198
199   setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
200     this.videoViewUrl = videoViewUrl
201     this.videoDuration = videoDuration
202     this.videoFiles = files
203
204     // Re run view add for the new video
205     this.runViewAdd()
206     this.updateVideoFile(undefined, () => this.player.play())
207   }
208
209   private initializePlayer () {
210     this.initSmoothProgressBar()
211
212     this.alterInactivity()
213
214     if (this.autoplay === true) {
215       this.updateVideoFile(undefined, () => this.player.play())
216     } else {
217       // Proxify first play
218       const oldPlay = this.player.play.bind(this.player)
219       this.player.play = () => {
220         this.updateVideoFile(undefined, () => oldPlay)
221         this.player.play = oldPlay
222       }
223     }
224   }
225
226   private runTorrentInfoScheduler () {
227     this.torrentInfoInterval = setInterval(() => {
228       // Not initialized yet
229       if (this.torrent === undefined) return
230
231       // Http fallback
232       if (this.torrent === null) return this.trigger('torrentInfo', false)
233
234       return this.trigger('torrentInfo', {
235         downloadSpeed: this.torrent.downloadSpeed,
236         numPeers: this.torrent.numPeers,
237         uploadSpeed: this.torrent.uploadSpeed
238       })
239     }, 1000)
240   }
241
242   private runViewAdd () {
243     this.clearVideoViewInterval()
244
245     // After 30 seconds (or 3/4 of the video), add a view to the video
246     let minSecondsToView = 30
247
248     if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
249
250     let secondsViewed = 0
251     this.videoViewInterval = setInterval(() => {
252       if (this.player && !this.player.paused()) {
253         secondsViewed += 1
254
255         if (secondsViewed > minSecondsToView) {
256           this.clearVideoViewInterval()
257
258           this.addViewToVideo().catch(err => console.error(err))
259         }
260       }
261     }, 1000)
262   }
263
264   private clearVideoViewInterval () {
265     if (this.videoViewInterval !== undefined) {
266       clearInterval(this.videoViewInterval)
267       this.videoViewInterval = undefined
268     }
269   }
270
271   private addViewToVideo () {
272     return fetch(this.videoViewUrl, { method: 'POST' })
273   }
274
275   private fallbackToHttp (done: Function) {
276     this.flushVideoFile(this.currentVideoFile, true)
277     this.torrent = null
278
279     // Enable error display now this is our last fallback
280     this.player.one('error', () => this.enableErrorDisplay())
281
282     const httpUrl = this.currentVideoFile.fileUrl
283     this.player.src = this.savePlayerSrcFunction
284     this.player.src(httpUrl)
285     this.player.play()
286
287     return done()
288   }
289
290   private handleError (err: Error | string) {
291     return this.player.trigger('customError', { err })
292   }
293
294   private enableErrorDisplay () {
295     this.player.addClass('vjs-error-display-enabled')
296   }
297
298   private disableErrorDisplay () {
299     this.player.removeClass('vjs-error-display-enabled')
300   }
301
302   private alterInactivity () {
303     let saveInactivityTimeout: number
304
305     const disableInactivity = () => {
306       saveInactivityTimeout = this.player.options_.inactivityTimeout
307       this.player.options_.inactivityTimeout = 0
308     }
309     const enableInactivity = () => {
310       // this.player.options_.inactivityTimeout = saveInactivityTimeout
311     }
312
313     const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
314
315     this.player.controlBar.on('mouseenter', () => disableInactivity())
316     settingsDialog.on('mouseenter', () => disableInactivity())
317     this.player.controlBar.on('mouseleave', () => enableInactivity())
318     settingsDialog.on('mouseleave', () => enableInactivity())
319   }
320
321   // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
322   private initSmoothProgressBar () {
323     const SeekBar = videojsUntyped.getComponent('SeekBar')
324     SeekBar.prototype.getPercent = function getPercent () {
325       // Allows for smooth scrubbing, when player can't keep up.
326       // const time = (this.player_.scrubbing()) ?
327       //   this.player_.getCache().currentTime :
328       //   this.player_.currentTime()
329       const time = this.player_.currentTime()
330       const percent = time / this.player_.duration()
331       return percent >= 1 ? 1 : percent
332     }
333     SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
334       let newTime = this.calculateDistance(event) * this.player_.duration()
335       if (newTime === this.player_.duration()) {
336         newTime = newTime - 0.1
337       }
338       this.player_.currentTime(newTime)
339       this.update()
340     }
341   }
342 }
343
344 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
345 export { PeerTubePlugin }