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 super.handleClick(event)
61 this.player_.peertube().updateResolution(this.options_.id)
64 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
66 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
67 class ResolutionMenuButton extends MenuButton {
70 constructor (player: videojs.Player, options) {
71 options.label = 'Quality'
72 super(player, options)
74 this.label = document.createElement('span')
76 this.el().setAttribute('aria-label', 'Quality')
77 this.controlText('Quality')
79 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
80 this.el().appendChild(this.label)
82 player.peertube().on('videoFileUpdate', () => this.update())
87 for (const videoFile of this.player_.peertube().videoFiles) {
88 menuItems.push(new ResolutionMenuItem(
91 id: videoFile.resolution,
92 label: videoFile.resolutionLabel,
93 src: videoFile.magnetUri,
94 selected: videoFile.resolution === this.currentSelection
103 if (!this.label) return
105 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
107 return super.update()
111 return super.buildCSSClass() + ' vjs-resolution-button'
115 this.parentNode.removeChild(this)
118 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
120 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
121 class PeertubeLinkButton extends Button {
124 const link = document.createElement('a')
125 link.href = window.location.href.replace('embed', 'watch')
126 link.innerHTML = 'PeerTube'
127 link.title = 'Go to the video page'
128 link.className = 'vjs-peertube-link'
129 link.target = '_blank'
139 this.parentNode.removeChild(this)
142 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
144 class WebTorrentButton extends Button {
146 const div = document.createElement('div')
147 const subDiv = document.createElement('div')
148 div.appendChild(subDiv)
150 const downloadIcon = document.createElement('span')
151 downloadIcon.classList.add('icon', 'icon-download')
152 subDiv.appendChild(downloadIcon)
154 const downloadSpeedText = document.createElement('span')
155 downloadSpeedText.classList.add('download-speed-text')
156 const downloadSpeedNumber = document.createElement('span')
157 downloadSpeedNumber.classList.add('download-speed-number')
158 const downloadSpeedUnit = document.createElement('span')
159 downloadSpeedText.appendChild(downloadSpeedNumber)
160 downloadSpeedText.appendChild(downloadSpeedUnit)
161 subDiv.appendChild(downloadSpeedText)
163 const uploadIcon = document.createElement('span')
164 uploadIcon.classList.add('icon', 'icon-upload')
165 subDiv.appendChild(uploadIcon)
167 const uploadSpeedText = document.createElement('span')
168 uploadSpeedText.classList.add('upload-speed-text')
169 const uploadSpeedNumber = document.createElement('span')
170 uploadSpeedNumber.classList.add('upload-speed-number')
171 const uploadSpeedUnit = document.createElement('span')
172 uploadSpeedText.appendChild(uploadSpeedNumber)
173 uploadSpeedText.appendChild(uploadSpeedUnit)
174 subDiv.appendChild(uploadSpeedText)
176 const peersText = document.createElement('span')
177 peersText.textContent = ' peers'
178 peersText.classList.add('peers-text')
179 const peersNumber = document.createElement('span')
180 peersNumber.classList.add('peers-number')
181 subDiv.appendChild(peersNumber)
182 subDiv.appendChild(peersText)
184 div.className = 'vjs-webtorrent'
185 // Hide the stats before we get the info
186 subDiv.className = 'vjs-webtorrent-hidden'
188 this.player_.peertube().on('torrentInfo', (event, data) => {
189 const downloadSpeed = bytes(data.downloadSpeed)
190 const uploadSpeed = bytes(data.uploadSpeed)
191 const numPeers = data.numPeers
193 downloadSpeedNumber.textContent = downloadSpeed[0]
194 downloadSpeedUnit.textContent = ' ' + downloadSpeed[1]
196 uploadSpeedNumber.textContent = uploadSpeed[0]
197 uploadSpeedUnit.textContent = ' ' + uploadSpeed[1]
199 peersNumber.textContent = numPeers
201 subDiv.className = 'vjs-webtorrent-displayed'
208 this.parentNode.removeChild(this)
211 Button.registerComponent('WebTorrentButton', WebTorrentButton)
213 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
214 class PeerTubePlugin extends Plugin {
216 private currentVideoFile: VideoFile
217 private playerElement: HTMLVideoElement
218 private videoFiles: VideoFile[]
219 private torrent: WebTorrent.Torrent
220 private autoplay = false
222 constructor (player: videojs.Player, options: PeertubePluginOptions) {
223 super(player, options)
225 // Fix canplay event on google chrome by disabling default videojs autoplay
226 this.autoplay = this.player.options_.autoplay
227 this.player.options_.autoplay = false
229 this.videoFiles = options.videoFiles
231 // Hack to "simulate" src link in video.js >= 6
232 // Without this, we can't play the video after pausing it
233 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
234 this.player.src = function () {
238 this.playerElement = options.playerElement
240 this.player.ready(() => {
241 this.initializePlayer(options)
242 this.runTorrentInfoScheduler()
247 // Don't need to destroy renderer, video player will be destroyed
248 this.flushVideoFile(this.currentVideoFile, false)
251 getCurrentResolution () {
252 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
255 getCurrentResolutionLabel () {
256 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
259 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
260 if (done === undefined) {
261 done = () => { /* empty */ }
264 // Pick the first one
265 if (videoFile === undefined) {
266 videoFile = this.videoFiles[0]
269 // Don't add the same video file once again
270 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
274 const previousVideoFile = this.currentVideoFile
275 this.currentVideoFile = videoFile
277 console.log('Adding ' + videoFile.magnetUri + '.')
278 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
279 console.log('Added ' + videoFile.magnetUri + '.')
281 this.flushVideoFile(previousVideoFile)
283 const options = { autoplay: true, controls: true }
284 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
285 if (err) return this.handleError(err)
287 this.renderer = renderer
288 if (!this.player.paused()) this.player.play().then(done)
293 this.torrent.on('error', err => this.handleError(err))
294 this.torrent.on('warning', (err: any) => {
295 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
296 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
297 // Users don't care about issues with WebRTC, but developers do so log it in the console
298 if (err.message.indexOf('Ice connection failed') !== -1) {
303 return this.handleError(err)
306 this.trigger('videoFileUpdate')
309 updateResolution (resolution) {
310 // Remember player state
311 const currentTime = this.player.currentTime()
312 const isPaused = this.player.paused()
314 // Remove poster to have black background
315 this.playerElement.poster = ''
317 // Hide bigPlayButton
319 this.player.bigPlayButton.hide()
322 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
323 this.updateVideoFile(newVideoFile, () => {
324 this.player.currentTime(currentTime)
325 this.player.handleTechSeeked_()
329 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
330 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
331 if (destroyRenderer === true) this.renderer.destroy()
332 webtorrent.remove(videoFile.magnetUri)
333 console.log('Removed ' + videoFile.magnetUri)
337 setVideoFiles (files: VideoFile[]) {
338 this.videoFiles = files
340 this.updateVideoFile(undefined, () => this.player.play())
343 private initializePlayer (options: PeertubePluginOptions) {
344 const controlBar = this.player.controlBar
346 const menuButton = new ResolutionMenuButton(this.player, options)
347 const fullscreenElement = controlBar.fullscreenToggle.el()
348 controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
350 if (options.peerTubeLink === true) {
351 const peerTubeLinkButton = new PeertubeLinkButton(this.player)
352 controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
355 const webTorrentButton = new WebTorrentButton(this.player)
356 controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
358 if (this.autoplay === true) {
359 this.updateVideoFile(undefined, () => this.player.play())
361 this.player.one('play', () => {
363 this.updateVideoFile(undefined, () => this.player.play())
368 private runTorrentInfoScheduler () {
370 if (this.torrent !== undefined) {
371 this.trigger('torrentInfo', {
372 downloadSpeed: this.torrent.downloadSpeed,
373 numPeers: this.torrent.numPeers,
374 uploadSpeed: this.torrent.uploadSpeed
380 private handleError (err: Error | string) {
381 return this.player.trigger('customError', { err })
384 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)