Fix playback rate
[oweals/peertube.git] / client / src / assets / player / peertube-videojs-plugin.ts
1 // Big thanks to: https://github.com/kmoskwiak/videojs-resolution-switcher
2
3 import * as videojs from 'video.js'
4 import * as WebTorrent from 'webtorrent'
5 import { VideoFile } from '../../../../shared/models/videos/video.model'
6 import { renderVideo } from './video-renderer'
7
8 declare module 'video.js' {
9   interface Player {
10     peertube (): PeerTubePlugin
11   }
12 }
13
14 interface VideoJSComponentInterface {
15   _player: videojs.Player
16
17   new (player: videojs.Player, options?: any)
18
19   registerComponent (name: string, obj: any)
20 }
21
22 type PeertubePluginOptions = {
23   videoFiles: VideoFile[]
24   playerElement: HTMLVideoElement
25   peerTubeLink: boolean
26   videoViewUrl: string
27   videoDuration: number
28 }
29
30 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
31 // Don't import all Angular stuff, just copy the code with shame
32 const dictionaryBytes: Array<{max: number, type: string}> = [
33   { max: 1024, type: 'B' },
34   { max: 1048576, type: 'KB' },
35   { max: 1073741824, type: 'MB' },
36   { max: 1.0995116e12, type: 'GB' }
37 ]
38 function bytes (value) {
39   const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
40   const calc = Math.floor(value / (format.max / 1024)).toString()
41
42   return [ calc, format.type ]
43 }
44
45 // videojs typings don't have some method we need
46 const videojsUntyped = videojs as any
47 const webtorrent = new WebTorrent({ dht: false })
48
49 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
50 class ResolutionMenuItem extends MenuItem {
51
52   constructor (player: videojs.Player, options) {
53     options.selectable = true
54     super(player, options)
55
56     const currentResolution = this.player_.peertube().getCurrentResolution()
57     this.selected(this.options_.id === currentResolution)
58   }
59
60   handleClick (event) {
61     super.handleClick(event)
62
63     this.player_.peertube().updateResolution(this.options_.id)
64   }
65 }
66 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
67
68 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
69 class ResolutionMenuButton extends MenuButton {
70   label: HTMLElement
71
72   constructor (player: videojs.Player, options) {
73     options.label = 'Quality'
74     super(player, options)
75
76     this.label = document.createElement('span')
77
78     this.el().setAttribute('aria-label', 'Quality')
79     this.controlText('Quality')
80
81     videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
82     this.el().appendChild(this.label)
83
84     player.peertube().on('videoFileUpdate', () => this.update())
85   }
86
87   createItems () {
88     const menuItems = []
89     for (const videoFile of this.player_.peertube().videoFiles) {
90       menuItems.push(new ResolutionMenuItem(
91         this.player_,
92         {
93           id: videoFile.resolution,
94           label: videoFile.resolutionLabel,
95           src: videoFile.magnetUri,
96           selected: videoFile.resolution === this.currentSelection
97         })
98       )
99     }
100
101     return menuItems
102   }
103
104   update () {
105     if (!this.label) return
106
107     this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
108     this.hide()
109     return super.update()
110   }
111
112   buildCSSClass () {
113     return super.buildCSSClass() + ' vjs-resolution-button'
114   }
115
116   dispose () {
117     this.parentNode.removeChild(this)
118   }
119 }
120 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
121
122 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
123 class PeertubeLinkButton extends Button {
124
125   createEl () {
126     const link = document.createElement('a')
127     link.href = window.location.href.replace('embed', 'watch')
128     link.innerHTML = 'PeerTube'
129     link.title = 'Go to the video page'
130     link.className = 'vjs-peertube-link'
131     link.target = '_blank'
132
133     return link
134   }
135
136   handleClick () {
137     this.player_.pause()
138   }
139
140   dispose () {
141     this.parentNode.removeChild(this)
142   }
143 }
144 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
145
146 class WebTorrentButton extends Button {
147   createEl () {
148     const div = document.createElement('div')
149     const subDivWebtorrent = document.createElement('div')
150     div.appendChild(subDivWebtorrent)
151
152     const downloadIcon = document.createElement('span')
153     downloadIcon.classList.add('icon', 'icon-download')
154     subDivWebtorrent.appendChild(downloadIcon)
155
156     const downloadSpeedText = document.createElement('span')
157     downloadSpeedText.classList.add('download-speed-text')
158     const downloadSpeedNumber = document.createElement('span')
159     downloadSpeedNumber.classList.add('download-speed-number')
160     const downloadSpeedUnit = document.createElement('span')
161     downloadSpeedText.appendChild(downloadSpeedNumber)
162     downloadSpeedText.appendChild(downloadSpeedUnit)
163     subDivWebtorrent.appendChild(downloadSpeedText)
164
165     const uploadIcon = document.createElement('span')
166     uploadIcon.classList.add('icon', 'icon-upload')
167     subDivWebtorrent.appendChild(uploadIcon)
168
169     const uploadSpeedText = document.createElement('span')
170     uploadSpeedText.classList.add('upload-speed-text')
171     const uploadSpeedNumber = document.createElement('span')
172     uploadSpeedNumber.classList.add('upload-speed-number')
173     const uploadSpeedUnit = document.createElement('span')
174     uploadSpeedText.appendChild(uploadSpeedNumber)
175     uploadSpeedText.appendChild(uploadSpeedUnit)
176     subDivWebtorrent.appendChild(uploadSpeedText)
177
178     const peersText = document.createElement('span')
179     peersText.classList.add('peers-text')
180     const peersNumber = document.createElement('span')
181     peersNumber.classList.add('peers-number')
182     subDivWebtorrent.appendChild(peersNumber)
183     subDivWebtorrent.appendChild(peersText)
184
185     div.className = 'vjs-peertube'
186     // Hide the stats before we get the info
187     subDivWebtorrent.className = 'vjs-peertube-hidden'
188
189     const subDivHttp = document.createElement('div')
190     subDivHttp.className = 'vjs-peertube-hidden'
191     const subDivHttpText = document.createElement('span')
192     subDivHttpText.classList.add('peers-number')
193     subDivHttpText.textContent = 'HTTP'
194     const subDivFallbackText = document.createElement('span')
195     subDivFallbackText.classList.add('peers-text')
196     subDivFallbackText.textContent = ' fallback'
197
198     subDivHttp.appendChild(subDivHttpText)
199     subDivHttp.appendChild(subDivFallbackText)
200     div.appendChild(subDivHttp)
201
202     this.player_.peertube().on('torrentInfo', (event, data) => {
203       // We are in HTTP fallback
204       if (!data) {
205         subDivHttp.className = 'vjs-peertube-displayed'
206         subDivWebtorrent.className = 'vjs-peertube-hidden'
207
208         return
209       }
210
211       const downloadSpeed = bytes(data.downloadSpeed)
212       const uploadSpeed = bytes(data.uploadSpeed)
213       const numPeers = data.numPeers
214
215       downloadSpeedNumber.textContent = downloadSpeed[ 0 ]
216       downloadSpeedUnit.textContent = ' ' + downloadSpeed[ 1 ]
217
218       uploadSpeedNumber.textContent = uploadSpeed[ 0 ]
219       uploadSpeedUnit.textContent = ' ' + uploadSpeed[ 1 ]
220
221       peersNumber.textContent = numPeers
222       peersText.textContent = ' peers'
223
224       subDivHttp.className = 'vjs-peertube-hidden'
225       subDivWebtorrent.className = 'vjs-peertube-displayed'
226     })
227
228     return div
229   }
230
231   dispose () {
232     this.parentNode.removeChild(this)
233   }
234 }
235 Button.registerComponent('WebTorrentButton', WebTorrentButton)
236
237 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
238 class PeerTubePlugin extends Plugin {
239   private player: any
240   private currentVideoFile: VideoFile
241   private playerElement: HTMLVideoElement
242   private videoFiles: VideoFile[]
243   private torrent: WebTorrent.Torrent
244   private autoplay = false
245   private videoViewUrl: string
246   private videoDuration: number
247   private videoViewInterval
248   private torrentInfoInterval
249   private savePlayerSrcFunction: Function
250
251   constructor (player: videojs.Player, options: PeertubePluginOptions) {
252     super(player, options)
253
254     // Fix canplay event on google chrome by disabling default videojs autoplay
255     this.autoplay = this.player.options_.autoplay
256     this.player.options_.autoplay = false
257
258     this.videoFiles = options.videoFiles
259     this.videoViewUrl = options.videoViewUrl
260     this.videoDuration = options.videoDuration
261
262     this.savePlayerSrcFunction = this.player.src
263     // Hack to "simulate" src link in video.js >= 6
264     // Without this, we can't play the video after pausing it
265     // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
266     this.player.src = () => true
267
268     this.playerElement = options.playerElement
269
270     this.player.ready(() => {
271       this.initializePlayer(options)
272       this.runTorrentInfoScheduler()
273       this.runViewAdd()
274     })
275   }
276
277   dispose () {
278     clearInterval(this.videoViewInterval)
279     clearInterval(this.torrentInfoInterval)
280
281     // Don't need to destroy renderer, video player will be destroyed
282     this.flushVideoFile(this.currentVideoFile, false)
283   }
284
285   getCurrentResolution () {
286     return this.currentVideoFile ? this.currentVideoFile.resolution : -1
287   }
288
289   getCurrentResolutionLabel () {
290     return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
291   }
292
293   updateVideoFile (videoFile?: VideoFile, done?: () => void) {
294     if (done === undefined) {
295       done = () => { /* empty */ }
296     }
297
298     // Pick the first one
299     if (videoFile === undefined) {
300       videoFile = this.videoFiles[0]
301     }
302
303     // Don't add the same video file once again
304     if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
305       return
306     }
307
308     // Do not display error to user because we will have multiple fallbacks
309     this.disableErrorDisplay()
310
311     this.player.src = () => true
312     this.player.playbackRate(1)
313
314     const previousVideoFile = this.currentVideoFile
315     this.currentVideoFile = videoFile
316
317     console.log('Adding ' + videoFile.magnetUri + '.')
318     this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
319       console.log('Added ' + videoFile.magnetUri + '.')
320
321       this.flushVideoFile(previousVideoFile)
322
323       const options = { autoplay: true, controls: true }
324       renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
325         if (err) return this.fallbackToHttp()
326
327         this.renderer = renderer
328         if (!this.player.paused()) {
329           const playPromise = this.player.play()
330           if (playPromise !== undefined) return playPromise.then(done)
331
332           return done()
333         }
334
335         return done()
336       })
337     })
338
339     this.torrent.on('error', err => this.handleError(err))
340     this.torrent.on('warning', (err: any) => {
341       // We don't support HTTP tracker but we don't care -> we use the web socket tracker
342       if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
343       // Users don't care about issues with WebRTC, but developers do so log it in the console
344       if (err.message.indexOf('Ice connection failed') !== -1) {
345         console.error(err)
346         return
347       }
348
349       return this.handleError(err)
350     })
351
352     this.trigger('videoFileUpdate')
353   }
354
355   updateResolution (resolution) {
356     // Remember player state
357     const currentTime = this.player.currentTime()
358     const isPaused = this.player.paused()
359
360     // Remove poster to have black background
361     this.playerElement.poster = ''
362
363     // Hide bigPlayButton
364     if (!isPaused) {
365       this.player.bigPlayButton.hide()
366     }
367
368     const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
369     this.updateVideoFile(newVideoFile, () => {
370       this.player.currentTime(currentTime)
371       this.player.handleTechSeeked_()
372     })
373   }
374
375   flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
376     if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
377       if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
378
379       webtorrent.remove(videoFile.magnetUri)
380       console.log('Removed ' + videoFile.magnetUri)
381     }
382   }
383
384   setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
385     this.videoViewUrl = videoViewUrl
386     this.videoDuration = videoDuration
387     this.videoFiles = files
388
389     // Re run view add for the new video
390     this.runViewAdd()
391     this.updateVideoFile(undefined, () => this.player.play())
392   }
393
394   private initializePlayer (options: PeertubePluginOptions) {
395     const controlBar = this.player.controlBar
396
397     const menuButton = new ResolutionMenuButton(this.player, options)
398     const fullscreenElement = controlBar.fullscreenToggle.el()
399     controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
400
401     if (options.peerTubeLink === true) {
402       const peerTubeLinkButton = new PeertubeLinkButton(this.player)
403       controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
404     }
405
406     const webTorrentButton = new WebTorrentButton(this.player)
407     controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
408
409     if (this.autoplay === true) {
410       this.updateVideoFile(undefined, () => this.player.play())
411     } else {
412       this.player.one('play', () => {
413         this.player.pause()
414         this.updateVideoFile(undefined, () => this.player.play())
415       })
416     }
417   }
418
419   private runTorrentInfoScheduler () {
420     this.torrentInfoInterval = setInterval(() => {
421       // Not initialized yet
422       if (this.torrent === undefined) return
423
424       // Http fallback
425       if (this.torrent === null) return this.trigger('torrentInfo', false)
426
427       return this.trigger('torrentInfo', {
428         downloadSpeed: this.torrent.downloadSpeed,
429         numPeers: this.torrent.numPeers,
430         uploadSpeed: this.torrent.uploadSpeed
431       })
432     }, 1000)
433   }
434
435   private runViewAdd () {
436     this.clearVideoViewInterval()
437
438     // After 30 seconds (or 3/4 of the video), add a view to the video
439     let minSecondsToView = 30
440
441     if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
442
443     let secondsViewed = 0
444     this.videoViewInterval = setInterval(() => {
445       if (this.player && !this.player.paused()) {
446         secondsViewed += 1
447
448         if (secondsViewed > minSecondsToView) {
449           this.clearVideoViewInterval()
450
451           this.addViewToVideo().catch(err => console.error(err))
452         }
453       }
454     }, 1000)
455   }
456
457   private clearVideoViewInterval () {
458     if (this.videoViewInterval !== undefined) {
459       clearInterval(this.videoViewInterval)
460       this.videoViewInterval = undefined
461     }
462   }
463
464   private addViewToVideo () {
465     return fetch(this.videoViewUrl, { method: 'POST' })
466   }
467
468   private fallbackToHttp () {
469     this.flushVideoFile(this.currentVideoFile, true)
470     this.torrent = null
471
472     // Enable error display now this is our last fallback
473     this.player.one('error', () => this.enableErrorDisplay())
474
475     const httpUrl = this.currentVideoFile.fileUrl
476     this.player.src = this.savePlayerSrcFunction
477     this.player.src(httpUrl)
478     this.player.play()
479   }
480
481   private handleError (err: Error | string) {
482     return this.player.trigger('customError', { err })
483   }
484
485   private enableErrorDisplay () {
486     this.player.addClass('vjs-error-display-enabled')
487   }
488
489   private disableErrorDisplay () {
490     this.player.removeClass('vjs-error-display-enabled')
491   }
492 }
493 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)