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'
7 import { renderVideo } from './video-renderer'
9 interface VideoJSComponentInterface {
10 _player: VideoJSPlayer
12 new (player: VideoJSPlayer, options?: any)
14 registerComponent (name: string, obj: any)
17 interface VideoJSPlayer extends videojs.Player {
18 peertube (): PeerTubePlugin
21 type PeertubePluginOptions = {
22 videoFiles: VideoFile[]
23 playerElement: HTMLVideoElement
27 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
28 // Don't import all Angular stuff, just copy the code with shame
29 const dictionaryBytes: Array<{max: number, type: string}> = [
30 { max: 1024, type: 'B' },
31 { max: 1048576, type: 'KB' },
32 { max: 1073741824, type: 'MB' },
33 { max: 1.0995116e12, type: 'GB' }
35 function bytes (value) {
36 const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
37 const calc = Math.floor(value / (format.max / 1024)).toString()
39 return [ calc, format.type ]
42 // videojs typings don't have some method we need
43 const videojsUntyped = videojs as any
44 const webtorrent = new WebTorrent({ dht: false })
46 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
47 class ResolutionMenuItem extends MenuItem {
49 constructor (player: VideoJSPlayer, options) {
50 options.selectable = true
51 super(player, options)
53 const currentResolution = this.player_.peertube().getCurrentResolution()
54 this.selected(this.options_.id === currentResolution)
58 MenuItem.prototype.handleClick.call(this, event)
59 this.player_.peertube().updateResolution(this.options_.id)
62 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
64 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
65 class ResolutionMenuButton extends MenuButton {
68 constructor (player: VideoJSPlayer, options) {
69 options.label = 'Quality'
70 super(player, options)
72 this.label = document.createElement('span')
74 this.el().setAttribute('aria-label', 'Quality')
75 this.controlText('Quality')
77 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
78 this.el().appendChild(this.label)
80 player.peertube().on('videoFileUpdate', () => this.update())
85 for (const videoFile of this.player_.peertube().videoFiles) {
86 menuItems.push(new ResolutionMenuItem(
89 id: videoFile.resolution,
90 label: videoFile.resolutionLabel,
91 src: videoFile.magnetUri,
92 selected: videoFile.resolution === this.currentSelection
101 if (!this.label) return
103 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
105 return super.update()
109 return super.buildCSSClass() + ' vjs-resolution-button'
113 this.parentNode.removeChild(this)
116 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
118 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
119 class PeertubeLinkButton extends Button {
122 const link = document.createElement('a')
123 link.href = window.location.href.replace('embed', 'watch')
124 link.innerHTML = 'PeerTube'
125 link.title = 'Go to the video page'
126 link.className = 'vjs-peertube-link'
127 link.target = '_blank'
137 this.parentNode.removeChild(this)
140 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
142 class WebTorrentButton extends Button {
144 const div = document.createElement('div')
145 const subDiv = document.createElement('div')
146 div.appendChild(subDiv)
148 const downloadIcon = document.createElement('span')
149 downloadIcon.classList.add('icon', 'icon-download')
150 subDiv.appendChild(downloadIcon)
152 const downloadSpeedText = document.createElement('span')
153 downloadSpeedText.classList.add('download-speed-text')
154 const downloadSpeedNumber = document.createElement('span')
155 downloadSpeedNumber.classList.add('download-speed-number')
156 const downloadSpeedUnit = document.createElement('span')
157 downloadSpeedText.appendChild(downloadSpeedNumber)
158 downloadSpeedText.appendChild(downloadSpeedUnit)
159 subDiv.appendChild(downloadSpeedText)
161 const uploadIcon = document.createElement('span')
162 uploadIcon.classList.add('icon', 'icon-upload')
163 subDiv.appendChild(uploadIcon)
165 const uploadSpeedText = document.createElement('span')
166 uploadSpeedText.classList.add('upload-speed-text')
167 const uploadSpeedNumber = document.createElement('span')
168 uploadSpeedNumber.classList.add('upload-speed-number')
169 const uploadSpeedUnit = document.createElement('span')
170 uploadSpeedText.appendChild(uploadSpeedNumber)
171 uploadSpeedText.appendChild(uploadSpeedUnit)
172 subDiv.appendChild(uploadSpeedText)
174 const peersText = document.createElement('span')
175 peersText.textContent = ' peers'
176 peersText.classList.add('peers-text')
177 const peersNumber = document.createElement('span')
178 peersNumber.classList.add('peers-number')
179 subDiv.appendChild(peersNumber)
180 subDiv.appendChild(peersText)
182 div.className = 'vjs-webtorrent'
183 // Hide the stats before we get the info
184 subDiv.className = 'vjs-webtorrent-hidden'
186 this.player_.peertube().on('torrentInfo', (event, data) => {
187 const downloadSpeed = bytes(data.downloadSpeed)
188 const uploadSpeed = bytes(data.uploadSpeed)
189 const numPeers = data.numPeers
191 downloadSpeedNumber.textContent = downloadSpeed[0]
192 downloadSpeedUnit.textContent = ' ' + downloadSpeed[1]
194 uploadSpeedNumber.textContent = uploadSpeed[0]
195 uploadSpeedUnit.textContent = ' ' + uploadSpeed[1]
197 peersNumber.textContent = numPeers
199 subDiv.className = 'vjs-webtorrent-displayed'
206 this.parentNode.removeChild(this)
209 Button.registerComponent('WebTorrentButton', WebTorrentButton)
211 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
212 class PeerTubePlugin extends Plugin {
214 private currentVideoFile: VideoFile
215 private playerElement: HTMLVideoElement
216 private videoFiles: VideoFile[]
217 private torrent: WebTorrent.Torrent
219 constructor (player: VideoJSPlayer, options: PeertubePluginOptions) {
220 super(player, options)
222 this.videoFiles = options.videoFiles
224 // Hack to "simulate" src link in video.js >= 6
225 // Without this, we can't play the video after pausing it
226 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
227 this.player.src = function () {
231 this.playerElement = options.playerElement
233 this.player.ready(() => {
234 this.initializePlayer(options)
235 this.runTorrentInfoScheduler()
240 // Don't need to destroy renderer, video player will be destroyed
241 this.flushVideoFile(this.currentVideoFile, false)
244 getCurrentResolution () {
245 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
248 getCurrentResolutionLabel () {
249 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
252 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
253 if (done === undefined) {
254 done = () => { /* empty */ }
257 // Pick the first one
258 if (videoFile === undefined) {
259 videoFile = this.videoFiles[0]
262 // Don't add the same video file once again
263 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
267 const previousVideoFile = this.currentVideoFile
268 this.currentVideoFile = videoFile
270 console.log('Adding ' + videoFile.magnetUri + '.')
271 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
272 console.log('Added ' + videoFile.magnetUri + '.')
274 this.flushVideoFile(previousVideoFile)
276 const options = { autoplay: true, controls: true }
277 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
278 if (err) return this.handleError(err)
280 this.renderer = renderer
281 this.player.play().then(done)
285 this.torrent.on('error', err => this.handleError(err))
286 this.torrent.on('warning', (err: any) => {
287 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
288 if (err.message.indexOf('Unsupported tracker protocol: http') !== -1) return
289 // Users don't care about issues with WebRTC, but developers do so log it in the console
290 if (err.message.indexOf('Ice connection failed') !== -1) {
295 return this.handleError(err)
298 this.trigger('videoFileUpdate')
301 updateResolution (resolution) {
302 // Remember player state
303 const currentTime = this.player.currentTime()
304 const isPaused = this.player.paused()
306 // Hide bigPlayButton
308 this.player.bigPlayButton.hide()
311 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
312 this.updateVideoFile(newVideoFile, () => {
313 this.player.currentTime(currentTime)
314 this.player.handleTechSeeked_()
318 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
319 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
320 if (destroyRenderer === true) this.renderer.destroy()
321 webtorrent.remove(videoFile.magnetUri)
322 console.log('Removed ' + videoFile.magnetUri)
326 setVideoFiles (files: VideoFile[]) {
327 this.videoFiles = files
329 this.updateVideoFile(undefined, () => this.player.play())
332 private initializePlayer (options: PeertubePluginOptions) {
333 const controlBar = this.player.controlBar
335 const menuButton = new ResolutionMenuButton(this.player, options)
336 const fullscreenElement = controlBar.fullscreenToggle.el()
337 controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
339 if (options.peerTubeLink === true) {
340 const peerTubeLinkButton = new PeertubeLinkButton(this.player)
341 controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
344 const webTorrentButton = new WebTorrentButton(this.player)
345 controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
347 if (this.player.options_.autoplay === true) {
348 this.updateVideoFile()
350 this.player.one('play', () => {
351 // On firefox, we need to wait to load the video before playing
352 if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
354 this.updateVideoFile(undefined, () => this.player.play())
358 this.updateVideoFile(undefined)
363 private runTorrentInfoScheduler () {
365 if (this.torrent !== undefined) {
366 this.trigger('torrentInfo', {
367 downloadSpeed: this.torrent.downloadSpeed,
368 numPeers: this.torrent.numPeers,
369 uploadSpeed: this.torrent.uploadSpeed
375 private handleError (err: Error | string) {
376 return this.player.trigger('customError', { err })
379 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)