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 { VideoFile } from '../../../../shared/models/videos/video.model'
6 import { renderVideo } from './video-renderer'
8 declare module 'video.js' {
10 peertube (): PeerTubePlugin
14 interface VideoJSComponentInterface {
15 _player: videojs.Player
17 new (player: videojs.Player, options?: any)
19 registerComponent (name: string, obj: any)
22 type PeertubePluginOptions = {
23 videoFiles: VideoFile[]
24 playerElement: HTMLVideoElement
29 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
30 // Don't import all Angular stuff, just copy the code with shame
31 const dictionaryBytes: Array<{max: number, type: string}> = [
32 { max: 1024, type: 'B' },
33 { max: 1048576, type: 'KB' },
34 { max: 1073741824, type: 'MB' },
35 { max: 1.0995116e12, type: 'GB' }
37 function bytes (value) {
38 const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
39 const calc = Math.floor(value / (format.max / 1024)).toString()
41 return [ calc, format.type ]
44 // videojs typings don't have some method we need
45 const videojsUntyped = videojs as any
46 const webtorrent = new WebTorrent({ dht: false })
48 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
49 class ResolutionMenuItem extends MenuItem {
51 constructor (player: videojs.Player, options) {
52 options.selectable = true
53 super(player, options)
55 const currentResolution = this.player_.peertube().getCurrentResolution()
56 this.selected(this.options_.id === currentResolution)
60 super.handleClick(event)
62 this.player_.peertube().updateResolution(this.options_.id)
65 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
67 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
68 class ResolutionMenuButton extends MenuButton {
71 constructor (player: videojs.Player, options) {
72 options.label = 'Quality'
73 super(player, options)
75 this.label = document.createElement('span')
77 this.el().setAttribute('aria-label', 'Quality')
78 this.controlText('Quality')
80 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
81 this.el().appendChild(this.label)
83 player.peertube().on('videoFileUpdate', () => this.update())
88 for (const videoFile of this.player_.peertube().videoFiles) {
89 menuItems.push(new ResolutionMenuItem(
92 id: videoFile.resolution,
93 label: videoFile.resolutionLabel,
94 src: videoFile.magnetUri,
95 selected: videoFile.resolution === this.currentSelection
104 if (!this.label) return
106 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
108 return super.update()
112 return super.buildCSSClass() + ' vjs-resolution-button'
115 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
117 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
118 class PeerTubeLinkButton extends Button {
121 const link = document.createElement('a')
122 link.href = window.location.href.replace('embed', 'watch')
123 link.innerHTML = 'PeerTube'
124 link.title = 'Go to the video page'
125 link.className = 'vjs-peertube-link'
126 link.target = '_blank'
135 Button.registerComponent('PeerTubeLinkButton', PeerTubeLinkButton)
137 class WebTorrentButton extends Button {
139 const div = document.createElement('div')
140 const subDivWebtorrent = document.createElement('div')
141 div.appendChild(subDivWebtorrent)
143 const downloadIcon = document.createElement('span')
144 downloadIcon.classList.add('icon', 'icon-download')
145 subDivWebtorrent.appendChild(downloadIcon)
147 const downloadSpeedText = document.createElement('span')
148 downloadSpeedText.classList.add('download-speed-text')
149 const downloadSpeedNumber = document.createElement('span')
150 downloadSpeedNumber.classList.add('download-speed-number')
151 const downloadSpeedUnit = document.createElement('span')
152 downloadSpeedText.appendChild(downloadSpeedNumber)
153 downloadSpeedText.appendChild(downloadSpeedUnit)
154 subDivWebtorrent.appendChild(downloadSpeedText)
156 const uploadIcon = document.createElement('span')
157 uploadIcon.classList.add('icon', 'icon-upload')
158 subDivWebtorrent.appendChild(uploadIcon)
160 const uploadSpeedText = document.createElement('span')
161 uploadSpeedText.classList.add('upload-speed-text')
162 const uploadSpeedNumber = document.createElement('span')
163 uploadSpeedNumber.classList.add('upload-speed-number')
164 const uploadSpeedUnit = document.createElement('span')
165 uploadSpeedText.appendChild(uploadSpeedNumber)
166 uploadSpeedText.appendChild(uploadSpeedUnit)
167 subDivWebtorrent.appendChild(uploadSpeedText)
169 const peersText = document.createElement('span')
170 peersText.classList.add('peers-text')
171 const peersNumber = document.createElement('span')
172 peersNumber.classList.add('peers-number')
173 subDivWebtorrent.appendChild(peersNumber)
174 subDivWebtorrent.appendChild(peersText)
176 div.className = 'vjs-peertube'
177 // Hide the stats before we get the info
178 subDivWebtorrent.className = 'vjs-peertube-hidden'
180 const subDivHttp = document.createElement('div')
181 subDivHttp.className = 'vjs-peertube-hidden'
182 const subDivHttpText = document.createElement('span')
183 subDivHttpText.classList.add('peers-number')
184 subDivHttpText.textContent = 'HTTP'
185 const subDivFallbackText = document.createElement('span')
186 subDivFallbackText.classList.add('peers-text')
187 subDivFallbackText.textContent = ' fallback'
189 subDivHttp.appendChild(subDivHttpText)
190 subDivHttp.appendChild(subDivFallbackText)
191 div.appendChild(subDivHttp)
193 this.player_.peertube().on('torrentInfo', (event, data) => {
194 // We are in HTTP fallback
196 subDivHttp.className = 'vjs-peertube-displayed'
197 subDivWebtorrent.className = 'vjs-peertube-hidden'
202 const downloadSpeed = bytes(data.downloadSpeed)
203 const uploadSpeed = bytes(data.uploadSpeed)
204 const numPeers = data.numPeers
206 downloadSpeedNumber.textContent = downloadSpeed[ 0 ]
207 downloadSpeedUnit.textContent = ' ' + downloadSpeed[ 1 ]
209 uploadSpeedNumber.textContent = uploadSpeed[ 0 ]
210 uploadSpeedUnit.textContent = ' ' + uploadSpeed[ 1 ]
212 peersNumber.textContent = numPeers
213 peersText.textContent = ' peers'
215 subDivHttp.className = 'vjs-peertube-hidden'
216 subDivWebtorrent.className = 'vjs-peertube-displayed'
222 Button.registerComponent('WebTorrentButton', WebTorrentButton)
224 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
225 class PeerTubePlugin extends Plugin {
227 private currentVideoFile: VideoFile
228 private playerElement: HTMLVideoElement
229 private videoFiles: VideoFile[]
230 private torrent: WebTorrent.Torrent
231 private autoplay = false
232 private videoViewUrl: string
233 private videoDuration: number
234 private videoViewInterval
235 private torrentInfoInterval
236 private savePlayerSrcFunction: Function
238 constructor (player: videojs.Player, options: PeertubePluginOptions) {
239 super(player, options)
241 // Fix canplay event on google chrome by disabling default videojs autoplay
242 this.autoplay = this.player.options_.autoplay
243 this.player.options_.autoplay = false
245 this.videoFiles = options.videoFiles
246 this.videoViewUrl = options.videoViewUrl
247 this.videoDuration = options.videoDuration
249 this.savePlayerSrcFunction = this.player.src
250 // Hack to "simulate" src link in video.js >= 6
251 // Without this, we can't play the video after pausing it
252 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
253 this.player.src = () => true
255 this.playerElement = options.playerElement
257 this.player.ready(() => {
258 this.initializePlayer(options)
259 this.runTorrentInfoScheduler()
265 clearInterval(this.videoViewInterval)
266 clearInterval(this.torrentInfoInterval)
268 // Don't need to destroy renderer, video player will be destroyed
269 this.flushVideoFile(this.currentVideoFile, false)
272 getCurrentResolution () {
273 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
276 getCurrentResolutionLabel () {
277 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
280 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
281 if (done === undefined) {
282 done = () => { /* empty */ }
285 // Pick the first one
286 if (videoFile === undefined) {
287 videoFile = this.videoFiles[0]
290 // Don't add the same video file once again
291 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
295 // Do not display error to user because we will have multiple fallbacks
296 this.disableErrorDisplay()
298 this.player.src = () => true
299 this.player.playbackRate(1)
301 const previousVideoFile = this.currentVideoFile
302 this.currentVideoFile = videoFile
304 console.log('Adding ' + videoFile.magnetUri + '.')
305 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
306 console.log('Added ' + videoFile.magnetUri + '.')
308 this.flushVideoFile(previousVideoFile)
310 const options = { autoplay: true, controls: true }
311 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
312 if (err) return this.fallbackToHttp()
314 this.renderer = renderer
315 if (!this.player.paused()) {
316 const playPromise = this.player.play()
317 if (playPromise !== undefined) return playPromise.then(done)
326 this.torrent.on('error', err => this.handleError(err))
327 this.torrent.on('warning', (err: any) => {
328 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
329 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
330 // Users don't care about issues with WebRTC, but developers do so log it in the console
331 if (err.message.indexOf('Ice connection failed') !== -1) {
336 return this.handleError(err)
339 this.trigger('videoFileUpdate')
342 updateResolution (resolution) {
343 // Remember player state
344 const currentTime = this.player.currentTime()
345 const isPaused = this.player.paused()
347 // Remove poster to have black background
348 this.playerElement.poster = ''
350 // Hide bigPlayButton
352 this.player.bigPlayButton.hide()
355 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
356 this.updateVideoFile(newVideoFile, () => {
357 this.player.currentTime(currentTime)
358 this.player.handleTechSeeked_()
362 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
363 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
364 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
366 webtorrent.remove(videoFile.magnetUri)
367 console.log('Removed ' + videoFile.magnetUri)
371 setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
372 this.videoViewUrl = videoViewUrl
373 this.videoDuration = videoDuration
374 this.videoFiles = files
376 // Re run view add for the new video
378 this.updateVideoFile(undefined, () => this.player.play())
381 private initializePlayer (options: PeertubePluginOptions) {
382 if (this.autoplay === true) {
383 this.updateVideoFile(undefined, () => this.player.play())
385 this.player.one('play', () => {
387 this.updateVideoFile(undefined, () => this.player.play())
392 private runTorrentInfoScheduler () {
393 this.torrentInfoInterval = setInterval(() => {
394 // Not initialized yet
395 if (this.torrent === undefined) return
398 if (this.torrent === null) return this.trigger('torrentInfo', false)
400 return this.trigger('torrentInfo', {
401 downloadSpeed: this.torrent.downloadSpeed,
402 numPeers: this.torrent.numPeers,
403 uploadSpeed: this.torrent.uploadSpeed
408 private runViewAdd () {
409 this.clearVideoViewInterval()
411 // After 30 seconds (or 3/4 of the video), add a view to the video
412 let minSecondsToView = 30
414 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
416 let secondsViewed = 0
417 this.videoViewInterval = setInterval(() => {
418 if (this.player && !this.player.paused()) {
421 if (secondsViewed > minSecondsToView) {
422 this.clearVideoViewInterval()
424 this.addViewToVideo().catch(err => console.error(err))
430 private clearVideoViewInterval () {
431 if (this.videoViewInterval !== undefined) {
432 clearInterval(this.videoViewInterval)
433 this.videoViewInterval = undefined
437 private addViewToVideo () {
438 return fetch(this.videoViewUrl, { method: 'POST' })
441 private fallbackToHttp () {
442 this.flushVideoFile(this.currentVideoFile, true)
445 // Enable error display now this is our last fallback
446 this.player.one('error', () => this.enableErrorDisplay())
448 const httpUrl = this.currentVideoFile.fileUrl
449 this.player.src = this.savePlayerSrcFunction
450 this.player.src(httpUrl)
454 private handleError (err: Error | string) {
455 return this.player.trigger('customError', { err })
458 private enableErrorDisplay () {
459 this.player.addClass('vjs-error-display-enabled')
462 private disableErrorDisplay () {
463 this.player.removeClass('vjs-error-display-enabled')
466 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)