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
28 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
29 // Don't import all Angular stuff, just copy the code with shame
30 const dictionaryBytes: Array<{max: number, type: string}> = [
31 { max: 1024, type: 'B' },
32 { max: 1048576, type: 'KB' },
33 { max: 1073741824, type: 'MB' },
34 { max: 1.0995116e12, type: 'GB' }
36 function bytes (value) {
37 const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
38 const calc = Math.floor(value / (format.max / 1024)).toString()
40 return [ calc, format.type ]
43 // videojs typings don't have some method we need
44 const videojsUntyped = videojs as any
45 const webtorrent = new WebTorrent({ dht: false })
47 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
48 class ResolutionMenuItem extends MenuItem {
50 constructor (player: videojs.Player, options) {
51 options.selectable = true
52 super(player, options)
54 const currentResolution = this.player_.peertube().getCurrentResolution()
55 this.selected(this.options_.id === currentResolution)
59 MenuItem.prototype.handleClick.call(this, event)
60 this.player_.peertube().updateResolution(this.options_.id)
63 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
65 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
66 class ResolutionMenuButton extends MenuButton {
69 constructor (player: videojs.Player, options) {
70 options.label = 'Quality'
71 super(player, options)
73 this.label = document.createElement('span')
75 this.el().setAttribute('aria-label', 'Quality')
76 this.controlText('Quality')
78 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
79 this.el().appendChild(this.label)
81 player.peertube().on('videoFileUpdate', () => this.update())
86 for (const videoFile of this.player_.peertube().videoFiles) {
87 menuItems.push(new ResolutionMenuItem(
90 id: videoFile.resolution,
91 label: videoFile.resolutionLabel,
92 src: videoFile.magnetUri,
93 selected: videoFile.resolution === this.currentSelection
102 if (!this.label) return
104 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
106 return super.update()
110 return super.buildCSSClass() + ' vjs-resolution-button'
114 this.parentNode.removeChild(this)
117 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
119 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
120 class PeertubeLinkButton extends Button {
123 const link = document.createElement('a')
124 link.href = window.location.href.replace('embed', 'watch')
125 link.innerHTML = 'PeerTube'
126 link.title = 'Go to the video page'
127 link.className = 'vjs-peertube-link'
128 link.target = '_blank'
138 this.parentNode.removeChild(this)
141 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
143 class WebTorrentButton extends Button {
145 const div = document.createElement('div')
146 const subDiv = document.createElement('div')
147 div.appendChild(subDiv)
149 const downloadIcon = document.createElement('span')
150 downloadIcon.classList.add('icon', 'icon-download')
151 subDiv.appendChild(downloadIcon)
153 const downloadSpeedText = document.createElement('span')
154 downloadSpeedText.classList.add('download-speed-text')
155 const downloadSpeedNumber = document.createElement('span')
156 downloadSpeedNumber.classList.add('download-speed-number')
157 const downloadSpeedUnit = document.createElement('span')
158 downloadSpeedText.appendChild(downloadSpeedNumber)
159 downloadSpeedText.appendChild(downloadSpeedUnit)
160 subDiv.appendChild(downloadSpeedText)
162 const uploadIcon = document.createElement('span')
163 uploadIcon.classList.add('icon', 'icon-upload')
164 subDiv.appendChild(uploadIcon)
166 const uploadSpeedText = document.createElement('span')
167 uploadSpeedText.classList.add('upload-speed-text')
168 const uploadSpeedNumber = document.createElement('span')
169 uploadSpeedNumber.classList.add('upload-speed-number')
170 const uploadSpeedUnit = document.createElement('span')
171 uploadSpeedText.appendChild(uploadSpeedNumber)
172 uploadSpeedText.appendChild(uploadSpeedUnit)
173 subDiv.appendChild(uploadSpeedText)
175 const peersText = document.createElement('span')
176 peersText.textContent = ' peers'
177 peersText.classList.add('peers-text')
178 const peersNumber = document.createElement('span')
179 peersNumber.classList.add('peers-number')
180 subDiv.appendChild(peersNumber)
181 subDiv.appendChild(peersText)
183 div.className = 'vjs-webtorrent'
184 // Hide the stats before we get the info
185 subDiv.className = 'vjs-webtorrent-hidden'
187 this.player_.peertube().on('torrentInfo', (event, data) => {
188 const downloadSpeed = bytes(data.downloadSpeed)
189 const uploadSpeed = bytes(data.uploadSpeed)
190 const numPeers = data.numPeers
192 downloadSpeedNumber.textContent = downloadSpeed[0]
193 downloadSpeedUnit.textContent = ' ' + downloadSpeed[1]
195 uploadSpeedNumber.textContent = uploadSpeed[0]
196 uploadSpeedUnit.textContent = ' ' + uploadSpeed[1]
198 peersNumber.textContent = numPeers
200 subDiv.className = 'vjs-webtorrent-displayed'
207 this.parentNode.removeChild(this)
210 Button.registerComponent('WebTorrentButton', WebTorrentButton)
212 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
213 class PeerTubePlugin extends Plugin {
215 private currentVideoFile: VideoFile
216 private playerElement: HTMLVideoElement
217 private videoFiles: VideoFile[]
218 private torrent: WebTorrent.Torrent
220 constructor (player: videojs.Player, options: PeertubePluginOptions) {
221 super(player, options)
223 this.videoFiles = options.videoFiles
225 // Hack to "simulate" src link in video.js >= 6
226 // Without this, we can't play the video after pausing it
227 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
228 this.player.src = function () {
232 this.playerElement = options.playerElement
234 this.player.ready(() => {
235 this.initializePlayer(options)
236 this.runTorrentInfoScheduler()
241 // Don't need to destroy renderer, video player will be destroyed
242 this.flushVideoFile(this.currentVideoFile, false)
245 getCurrentResolution () {
246 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
249 getCurrentResolutionLabel () {
250 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
253 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
254 if (done === undefined) {
255 done = () => { /* empty */ }
258 // Pick the first one
259 if (videoFile === undefined) {
260 videoFile = this.videoFiles[0]
263 // Don't add the same video file once again
264 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
268 const previousVideoFile = this.currentVideoFile
269 this.currentVideoFile = videoFile
271 console.log('Adding ' + videoFile.magnetUri + '.')
272 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
273 console.log('Added ' + videoFile.magnetUri + '.')
275 this.flushVideoFile(previousVideoFile)
277 const options = { autoplay: true, controls: true }
278 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
279 if (err) return this.handleError(err)
281 this.renderer = renderer
282 this.player.play().then(done)
286 this.torrent.on('error', err => this.handleError(err))
287 this.torrent.on('warning', (err: any) => {
288 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
289 if (err.message.indexOf('Unsupported tracker protocol: http') !== -1) return
290 // Users don't care about issues with WebRTC, but developers do so log it in the console
291 if (err.message.indexOf('Ice connection failed') !== -1) {
296 return this.handleError(err)
299 this.trigger('videoFileUpdate')
302 updateResolution (resolution) {
303 // Remember player state
304 const currentTime = this.player.currentTime()
305 const isPaused = this.player.paused()
307 // Hide bigPlayButton
309 this.player.bigPlayButton.hide()
312 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
313 this.updateVideoFile(newVideoFile, () => {
314 this.player.currentTime(currentTime)
315 this.player.handleTechSeeked_()
319 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
320 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
321 if (destroyRenderer === true) this.renderer.destroy()
322 webtorrent.remove(videoFile.magnetUri)
323 console.log('Removed ' + videoFile.magnetUri)
327 setVideoFiles (files: VideoFile[]) {
328 this.videoFiles = files
330 this.updateVideoFile(undefined, () => this.player.play())
333 private initializePlayer (options: PeertubePluginOptions) {
334 const controlBar = this.player.controlBar
336 const menuButton = new ResolutionMenuButton(this.player, options)
337 const fullscreenElement = controlBar.fullscreenToggle.el()
338 controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
340 if (options.peerTubeLink === true) {
341 const peerTubeLinkButton = new PeertubeLinkButton(this.player)
342 controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
345 const webTorrentButton = new WebTorrentButton(this.player)
346 controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
348 if (this.player.options_.autoplay === true) {
349 this.updateVideoFile()
351 this.player.one('play', () => {
352 // On firefox, we need to wait to load the video before playing
353 if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
355 this.updateVideoFile(undefined, () => this.player.play())
359 this.updateVideoFile(undefined)
364 private runTorrentInfoScheduler () {
366 if (this.torrent !== undefined) {
367 this.trigger('torrentInfo', {
368 downloadSpeed: this.torrent.downloadSpeed,
369 numPeers: this.torrent.numPeers,
370 uploadSpeed: this.torrent.uploadSpeed
376 private handleError (err: Error | string) {
377 return this.player.trigger('customError', { err })
380 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)