1 // Big thanks to: https://github.com/kmoskwiak/videojs-resolution-switcher
3 import * as videojs from 'video.js'
4 import * as WebTorrent from 'webtorrent'
5 import { VideoConstant, VideoResolution } from '../../../../shared/models/videos'
6 import { VideoFile } from '../../../../shared/models/videos/video.model'
7 import { renderVideo } from './video-renderer'
9 declare module 'video.js' {
11 peertube (): PeerTubePlugin
15 interface VideoJSComponentInterface {
16 _player: videojs.Player
18 new (player: videojs.Player, options?: any)
20 registerComponent (name: string, obj: any)
23 type PeertubePluginOptions = {
24 videoFiles: VideoFile[]
25 playerElement: HTMLVideoElement
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' }
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()
42 return [ calc, format.type ]
45 // videojs typings don't have some method we need
46 const videojsUntyped = videojs as any
47 const webtorrent = new WebTorrent({
52 urls: 'stun:stun.stunprotocol.org'
55 urls: 'stun:stun.framasoft.org'
63 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
64 class ResolutionMenuItem extends MenuItem {
66 constructor (player: videojs.Player, options) {
67 options.selectable = true
68 super(player, options)
70 const currentResolutionId = this.player_.peertube().getCurrentResolutionId()
71 this.selected(this.options_.id === currentResolutionId)
75 super.handleClick(event)
77 this.player_.peertube().updateResolution(this.options_.id)
80 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
82 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
83 class ResolutionMenuButton extends MenuButton {
86 constructor (player: videojs.Player, options) {
87 options.label = 'Quality'
88 super(player, options)
90 this.label = document.createElement('span')
92 this.el().setAttribute('aria-label', 'Quality')
93 this.controlText('Quality')
95 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
96 this.el().appendChild(this.label)
98 player.peertube().on('videoFileUpdate', () => this.update())
103 for (const videoFile of this.player_.peertube().videoFiles) {
104 menuItems.push(new ResolutionMenuItem(
107 id: videoFile.resolution.id,
108 label: videoFile.resolution.label,
109 src: videoFile.magnetUri,
110 selected: videoFile.resolution.id === this.currentSelectionId
119 if (!this.label) return
121 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
123 return super.update()
127 return super.buildCSSClass() + ' vjs-resolution-button'
130 buildWrapperCSSClass () {
131 return 'vjs-resolution-control ' + super.buildWrapperCSSClass()
134 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
136 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
137 class PeerTubeLinkButton extends Button {
140 const link = document.createElement('a')
141 link.href = window.location.href.replace('embed', 'watch')
142 link.innerHTML = 'PeerTube'
143 link.title = 'Go to the video page'
144 link.className = 'vjs-peertube-link'
145 link.target = '_blank'
154 Button.registerComponent('PeerTubeLinkButton', PeerTubeLinkButton)
156 class WebTorrentButton extends Button {
158 const div = document.createElement('div')
159 const subDivWebtorrent = document.createElement('div')
160 div.appendChild(subDivWebtorrent)
162 const downloadIcon = document.createElement('span')
163 downloadIcon.classList.add('icon', 'icon-download')
164 subDivWebtorrent.appendChild(downloadIcon)
166 const downloadSpeedText = document.createElement('span')
167 downloadSpeedText.classList.add('download-speed-text')
168 const downloadSpeedNumber = document.createElement('span')
169 downloadSpeedNumber.classList.add('download-speed-number')
170 const downloadSpeedUnit = document.createElement('span')
171 downloadSpeedText.appendChild(downloadSpeedNumber)
172 downloadSpeedText.appendChild(downloadSpeedUnit)
173 subDivWebtorrent.appendChild(downloadSpeedText)
175 const uploadIcon = document.createElement('span')
176 uploadIcon.classList.add('icon', 'icon-upload')
177 subDivWebtorrent.appendChild(uploadIcon)
179 const uploadSpeedText = document.createElement('span')
180 uploadSpeedText.classList.add('upload-speed-text')
181 const uploadSpeedNumber = document.createElement('span')
182 uploadSpeedNumber.classList.add('upload-speed-number')
183 const uploadSpeedUnit = document.createElement('span')
184 uploadSpeedText.appendChild(uploadSpeedNumber)
185 uploadSpeedText.appendChild(uploadSpeedUnit)
186 subDivWebtorrent.appendChild(uploadSpeedText)
188 const peersText = document.createElement('span')
189 peersText.classList.add('peers-text')
190 const peersNumber = document.createElement('span')
191 peersNumber.classList.add('peers-number')
192 subDivWebtorrent.appendChild(peersNumber)
193 subDivWebtorrent.appendChild(peersText)
195 div.className = 'vjs-peertube'
196 // Hide the stats before we get the info
197 subDivWebtorrent.className = 'vjs-peertube-hidden'
199 const subDivHttp = document.createElement('div')
200 subDivHttp.className = 'vjs-peertube-hidden'
201 const subDivHttpText = document.createElement('span')
202 subDivHttpText.classList.add('peers-number')
203 subDivHttpText.textContent = 'HTTP'
204 const subDivFallbackText = document.createElement('span')
205 subDivFallbackText.classList.add('peers-text')
206 subDivFallbackText.textContent = ' fallback'
208 subDivHttp.appendChild(subDivHttpText)
209 subDivHttp.appendChild(subDivFallbackText)
210 div.appendChild(subDivHttp)
212 this.player_.peertube().on('torrentInfo', (event, data) => {
213 // We are in HTTP fallback
215 subDivHttp.className = 'vjs-peertube-displayed'
216 subDivWebtorrent.className = 'vjs-peertube-hidden'
221 const downloadSpeed = bytes(data.downloadSpeed)
222 const uploadSpeed = bytes(data.uploadSpeed)
223 const numPeers = data.numPeers
225 downloadSpeedNumber.textContent = downloadSpeed[ 0 ]
226 downloadSpeedUnit.textContent = ' ' + downloadSpeed[ 1 ]
228 uploadSpeedNumber.textContent = uploadSpeed[ 0 ]
229 uploadSpeedUnit.textContent = ' ' + uploadSpeed[ 1 ]
231 peersNumber.textContent = numPeers
232 peersText.textContent = ' peers'
234 subDivHttp.className = 'vjs-peertube-hidden'
235 subDivWebtorrent.className = 'vjs-peertube-displayed'
241 Button.registerComponent('WebTorrentButton', WebTorrentButton)
243 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
244 class PeerTubePlugin extends Plugin {
246 private currentVideoFile: VideoFile
247 private playerElement: HTMLVideoElement
248 private videoFiles: VideoFile[]
249 private torrent: WebTorrent.Torrent
250 private autoplay = false
251 private videoViewUrl: string
252 private videoDuration: number
253 private videoViewInterval
254 private torrentInfoInterval
255 private savePlayerSrcFunction: Function
257 constructor (player: videojs.Player, options: PeertubePluginOptions) {
258 super(player, options)
260 // Fix canplay event on google chrome by disabling default videojs autoplay
261 this.autoplay = this.player.options_.autoplay
262 this.player.options_.autoplay = false
264 this.videoFiles = options.videoFiles
265 this.videoViewUrl = options.videoViewUrl
266 this.videoDuration = options.videoDuration
268 this.savePlayerSrcFunction = this.player.src
269 // Hack to "simulate" src link in video.js >= 6
270 // Without this, we can't play the video after pausing it
271 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
272 this.player.src = () => true
274 this.playerElement = options.playerElement
276 this.player.ready(() => {
277 this.initializePlayer()
278 this.runTorrentInfoScheduler()
284 clearInterval(this.videoViewInterval)
285 clearInterval(this.torrentInfoInterval)
287 // Don't need to destroy renderer, video player will be destroyed
288 this.flushVideoFile(this.currentVideoFile, false)
291 getCurrentResolutionId () {
292 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
295 getCurrentResolutionLabel () {
296 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
299 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
300 if (done === undefined) {
301 done = () => { /* empty */ }
304 // Pick the first one
305 if (videoFile === undefined) {
306 videoFile = this.videoFiles[0]
309 // Don't add the same video file once again
310 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
314 // Do not display error to user because we will have multiple fallbacks
315 this.disableErrorDisplay()
317 this.player.src = () => true
318 this.player.playbackRate(1)
320 const previousVideoFile = this.currentVideoFile
321 this.currentVideoFile = videoFile
323 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, done)
325 this.trigger('videoFileUpdate')
328 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, done: Function) {
329 console.log('Adding ' + magnetOrTorrentUrl + '.')
331 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
332 console.log('Added ' + magnetOrTorrentUrl + '.')
334 this.flushVideoFile(previousVideoFile)
336 const options = { autoplay: true, controls: true }
337 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
338 this.renderer = renderer
340 if (err) return this.fallbackToHttp()
342 if (!this.player.paused()) {
343 const playPromise = this.player.play()
344 if (playPromise !== undefined) return playPromise.then(done)
353 this.torrent.on('error', err => this.handleError(err))
355 this.torrent.on('warning', (err: any) => {
356 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
357 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
359 // Users don't care about issues with WebRTC, but developers do so log it in the console
360 if (err.message.indexOf('Ice connection failed') !== -1) {
365 // Magnet hash is not up to date with the torrent file, add directly the torrent file
366 if (err.message.indexOf('incorrect info hash') !== -1) {
367 console.error('Incorrect info hash detected, falling back to torrent file.')
368 return this.addTorrent(this.torrent['xs'], previousVideoFile, done)
371 return this.handleError(err)
375 updateResolution (resolutionId: number) {
376 // Remember player state
377 const currentTime = this.player.currentTime()
378 const isPaused = this.player.paused()
380 // Remove poster to have black background
381 this.playerElement.poster = ''
383 // Hide bigPlayButton
385 this.player.bigPlayButton.hide()
388 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
389 this.updateVideoFile(newVideoFile, () => {
390 this.player.currentTime(currentTime)
391 this.player.handleTechSeeked_()
395 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
396 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
397 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
399 webtorrent.remove(videoFile.magnetUri)
400 console.log('Removed ' + videoFile.magnetUri)
404 setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
405 this.videoViewUrl = videoViewUrl
406 this.videoDuration = videoDuration
407 this.videoFiles = files
409 // Re run view add for the new video
411 this.updateVideoFile(undefined, () => this.player.play())
414 private initializePlayer () {
415 this.initSmoothProgressBar()
417 if (this.autoplay === true) {
418 this.updateVideoFile(undefined, () => this.player.play())
420 this.player.one('play', () => {
422 this.updateVideoFile(undefined, () => this.player.play())
427 private runTorrentInfoScheduler () {
428 this.torrentInfoInterval = setInterval(() => {
429 // Not initialized yet
430 if (this.torrent === undefined) return
433 if (this.torrent === null) return this.trigger('torrentInfo', false)
435 return this.trigger('torrentInfo', {
436 downloadSpeed: this.torrent.downloadSpeed,
437 numPeers: this.torrent.numPeers,
438 uploadSpeed: this.torrent.uploadSpeed
443 private runViewAdd () {
444 this.clearVideoViewInterval()
446 // After 30 seconds (or 3/4 of the video), add a view to the video
447 let minSecondsToView = 30
449 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
451 let secondsViewed = 0
452 this.videoViewInterval = setInterval(() => {
453 if (this.player && !this.player.paused()) {
456 if (secondsViewed > minSecondsToView) {
457 this.clearVideoViewInterval()
459 this.addViewToVideo().catch(err => console.error(err))
465 private clearVideoViewInterval () {
466 if (this.videoViewInterval !== undefined) {
467 clearInterval(this.videoViewInterval)
468 this.videoViewInterval = undefined
472 private addViewToVideo () {
473 return fetch(this.videoViewUrl, { method: 'POST' })
476 private fallbackToHttp () {
477 this.flushVideoFile(this.currentVideoFile, true)
480 // Enable error display now this is our last fallback
481 this.player.one('error', () => this.enableErrorDisplay())
483 const httpUrl = this.currentVideoFile.fileUrl
484 this.player.src = this.savePlayerSrcFunction
485 this.player.src(httpUrl)
489 private handleError (err: Error | string) {
490 return this.player.trigger('customError', { err })
493 private enableErrorDisplay () {
494 this.player.addClass('vjs-error-display-enabled')
497 private disableErrorDisplay () {
498 this.player.removeClass('vjs-error-display-enabled')
501 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
502 private initSmoothProgressBar () {
503 const SeekBar = videojsUntyped.getComponent('SeekBar')
504 SeekBar.prototype.getPercent = function getPercent () {
505 // Allows for smooth scrubbing, when player can't keep up.
506 // const time = (this.player_.scrubbing()) ?
507 // this.player_.getCache().currentTime :
508 // this.player_.currentTime()
509 const time = this.player_.currentTime()
510 const percent = time / this.player_.duration()
511 return percent >= 1 ? 1 : percent
513 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
514 let newTime = this.calculateDistance(event) * this.player_.duration()
515 if (newTime === this.player_.duration()) {
516 newTime = newTime - 0.1
518 this.player_.currentTime(newTime)
523 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)