Improve first play
[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.player.posterImage.hide()
216       this.updateVideoFile(undefined, () => this.player.play())
217     } else {
218       // Proxify first play
219       const oldPlay = this.player.play.bind(this.player)
220       this.player.play = () => {
221         this.updateVideoFile(undefined, () => oldPlay)
222         this.player.play = oldPlay
223       }
224     }
225   }
226
227   private runTorrentInfoScheduler () {
228     this.torrentInfoInterval = setInterval(() => {
229       // Not initialized yet
230       if (this.torrent === undefined) return
231
232       // Http fallback
233       if (this.torrent === null) return this.trigger('torrentInfo', false)
234
235       return this.trigger('torrentInfo', {
236         downloadSpeed: this.torrent.downloadSpeed,
237         numPeers: this.torrent.numPeers,
238         uploadSpeed: this.torrent.uploadSpeed
239       })
240     }, 1000)
241   }
242
243   private runViewAdd () {
244     this.clearVideoViewInterval()
245
246     // After 30 seconds (or 3/4 of the video), add a view to the video
247     let minSecondsToView = 30
248
249     if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
250
251     let secondsViewed = 0
252     this.videoViewInterval = setInterval(() => {
253       if (this.player && !this.player.paused()) {
254         secondsViewed += 1
255
256         if (secondsViewed > minSecondsToView) {
257           this.clearVideoViewInterval()
258
259           this.addViewToVideo().catch(err => console.error(err))
260         }
261       }
262     }, 1000)
263   }
264
265   private clearVideoViewInterval () {
266     if (this.videoViewInterval !== undefined) {
267       clearInterval(this.videoViewInterval)
268       this.videoViewInterval = undefined
269     }
270   }
271
272   private addViewToVideo () {
273     return fetch(this.videoViewUrl, { method: 'POST' })
274   }
275
276   private fallbackToHttp (done: Function) {
277     this.flushVideoFile(this.currentVideoFile, true)
278     this.torrent = null
279
280     // Enable error display now this is our last fallback
281     this.player.one('error', () => this.enableErrorDisplay())
282
283     const httpUrl = this.currentVideoFile.fileUrl
284     this.player.src = this.savePlayerSrcFunction
285     this.player.src(httpUrl)
286     this.player.play()
287
288     return done()
289   }
290
291   private handleError (err: Error | string) {
292     return this.player.trigger('customError', { err })
293   }
294
295   private enableErrorDisplay () {
296     this.player.addClass('vjs-error-display-enabled')
297   }
298
299   private disableErrorDisplay () {
300     this.player.removeClass('vjs-error-display-enabled')
301   }
302
303   private alterInactivity () {
304     let saveInactivityTimeout: number
305
306     const disableInactivity = () => {
307       saveInactivityTimeout = this.player.options_.inactivityTimeout
308       this.player.options_.inactivityTimeout = 0
309     }
310     const enableInactivity = () => {
311       // this.player.options_.inactivityTimeout = saveInactivityTimeout
312     }
313
314     const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
315
316     this.player.controlBar.on('mouseenter', () => disableInactivity())
317     settingsDialog.on('mouseenter', () => disableInactivity())
318     this.player.controlBar.on('mouseleave', () => enableInactivity())
319     settingsDialog.on('mouseleave', () => enableInactivity())
320   }
321
322   // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
323   private initSmoothProgressBar () {
324     const SeekBar = videojsUntyped.getComponent('SeekBar')
325     SeekBar.prototype.getPercent = function getPercent () {
326       // Allows for smooth scrubbing, when player can't keep up.
327       // const time = (this.player_.scrubbing()) ?
328       //   this.player_.getCache().currentTime :
329       //   this.player_.currentTime()
330       const time = this.player_.currentTime()
331       const percent = time / this.player_.duration()
332       return percent >= 1 ? 1 : percent
333     }
334     SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
335       let newTime = this.calculateDistance(event) * this.player_.duration()
336       if (newTime === this.player_.duration()) {
337         newTime = newTime - 0.1
338       }
339       this.player_.currentTime(newTime)
340       this.update()
341     }
342   }
343 }
344
345 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
346 export { PeerTubePlugin }