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({ dht: false })
49 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
50 class ResolutionMenuItem extends MenuItem {
52 constructor (player: videojs.Player, options) {
53 options.selectable = true
54 super(player, options)
56 const currentResolutionId = this.player_.peertube().getCurrentResolutionId()
57 this.selected(this.options_.id === currentResolutionId)
61 super.handleClick(event)
63 this.player_.peertube().updateResolution(this.options_.id)
66 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
68 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
69 class ResolutionMenuButton extends MenuButton {
72 constructor (player: videojs.Player, options) {
73 options.label = 'Quality'
74 super(player, options)
76 this.label = document.createElement('span')
78 this.el().setAttribute('aria-label', 'Quality')
79 this.controlText('Quality')
81 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
82 this.el().appendChild(this.label)
84 player.peertube().on('videoFileUpdate', () => this.update())
89 for (const videoFile of this.player_.peertube().videoFiles) {
90 menuItems.push(new ResolutionMenuItem(
93 id: videoFile.resolution.id,
94 label: videoFile.resolution.label,
95 src: videoFile.magnetUri,
96 selected: videoFile.resolution.id === this.currentSelectionId
105 if (!this.label) return
107 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
109 return super.update()
113 return super.buildCSSClass() + ' vjs-resolution-button'
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'
136 Button.registerComponent('PeerTubeLinkButton', PeerTubeLinkButton)
138 class WebTorrentButton extends Button {
140 const div = document.createElement('div')
141 const subDivWebtorrent = document.createElement('div')
142 div.appendChild(subDivWebtorrent)
144 const downloadIcon = document.createElement('span')
145 downloadIcon.classList.add('icon', 'icon-download')
146 subDivWebtorrent.appendChild(downloadIcon)
148 const downloadSpeedText = document.createElement('span')
149 downloadSpeedText.classList.add('download-speed-text')
150 const downloadSpeedNumber = document.createElement('span')
151 downloadSpeedNumber.classList.add('download-speed-number')
152 const downloadSpeedUnit = document.createElement('span')
153 downloadSpeedText.appendChild(downloadSpeedNumber)
154 downloadSpeedText.appendChild(downloadSpeedUnit)
155 subDivWebtorrent.appendChild(downloadSpeedText)
157 const uploadIcon = document.createElement('span')
158 uploadIcon.classList.add('icon', 'icon-upload')
159 subDivWebtorrent.appendChild(uploadIcon)
161 const uploadSpeedText = document.createElement('span')
162 uploadSpeedText.classList.add('upload-speed-text')
163 const uploadSpeedNumber = document.createElement('span')
164 uploadSpeedNumber.classList.add('upload-speed-number')
165 const uploadSpeedUnit = document.createElement('span')
166 uploadSpeedText.appendChild(uploadSpeedNumber)
167 uploadSpeedText.appendChild(uploadSpeedUnit)
168 subDivWebtorrent.appendChild(uploadSpeedText)
170 const peersText = document.createElement('span')
171 peersText.classList.add('peers-text')
172 const peersNumber = document.createElement('span')
173 peersNumber.classList.add('peers-number')
174 subDivWebtorrent.appendChild(peersNumber)
175 subDivWebtorrent.appendChild(peersText)
177 div.className = 'vjs-peertube'
178 // Hide the stats before we get the info
179 subDivWebtorrent.className = 'vjs-peertube-hidden'
181 const subDivHttp = document.createElement('div')
182 subDivHttp.className = 'vjs-peertube-hidden'
183 const subDivHttpText = document.createElement('span')
184 subDivHttpText.classList.add('peers-number')
185 subDivHttpText.textContent = 'HTTP'
186 const subDivFallbackText = document.createElement('span')
187 subDivFallbackText.classList.add('peers-text')
188 subDivFallbackText.textContent = ' fallback'
190 subDivHttp.appendChild(subDivHttpText)
191 subDivHttp.appendChild(subDivFallbackText)
192 div.appendChild(subDivHttp)
194 this.player_.peertube().on('torrentInfo', (event, data) => {
195 // We are in HTTP fallback
197 subDivHttp.className = 'vjs-peertube-displayed'
198 subDivWebtorrent.className = 'vjs-peertube-hidden'
203 const downloadSpeed = bytes(data.downloadSpeed)
204 const uploadSpeed = bytes(data.uploadSpeed)
205 const numPeers = data.numPeers
207 downloadSpeedNumber.textContent = downloadSpeed[ 0 ]
208 downloadSpeedUnit.textContent = ' ' + downloadSpeed[ 1 ]
210 uploadSpeedNumber.textContent = uploadSpeed[ 0 ]
211 uploadSpeedUnit.textContent = ' ' + uploadSpeed[ 1 ]
213 peersNumber.textContent = numPeers
214 peersText.textContent = ' peers'
216 subDivHttp.className = 'vjs-peertube-hidden'
217 subDivWebtorrent.className = 'vjs-peertube-displayed'
223 Button.registerComponent('WebTorrentButton', WebTorrentButton)
225 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
226 class PeerTubePlugin extends Plugin {
228 private currentVideoFile: VideoFile
229 private playerElement: HTMLVideoElement
230 private videoFiles: VideoFile[]
231 private torrent: WebTorrent.Torrent
232 private autoplay = false
233 private videoViewUrl: string
234 private videoDuration: number
235 private videoViewInterval
236 private torrentInfoInterval
237 private savePlayerSrcFunction: Function
239 constructor (player: videojs.Player, options: PeertubePluginOptions) {
240 super(player, options)
242 // Fix canplay event on google chrome by disabling default videojs autoplay
243 this.autoplay = this.player.options_.autoplay
244 this.player.options_.autoplay = false
246 this.videoFiles = options.videoFiles
247 this.videoViewUrl = options.videoViewUrl
248 this.videoDuration = options.videoDuration
250 this.savePlayerSrcFunction = this.player.src
251 // Hack to "simulate" src link in video.js >= 6
252 // Without this, we can't play the video after pausing it
253 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
254 this.player.src = () => true
256 this.playerElement = options.playerElement
258 this.player.ready(() => {
259 this.initializePlayer(options)
260 this.runTorrentInfoScheduler()
266 clearInterval(this.videoViewInterval)
267 clearInterval(this.torrentInfoInterval)
269 // Don't need to destroy renderer, video player will be destroyed
270 this.flushVideoFile(this.currentVideoFile, false)
273 getCurrentResolutionId () {
274 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
277 getCurrentResolutionLabel () {
278 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
281 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
282 if (done === undefined) {
283 done = () => { /* empty */ }
286 // Pick the first one
287 if (videoFile === undefined) {
288 videoFile = this.videoFiles[0]
291 // Don't add the same video file once again
292 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
296 // Do not display error to user because we will have multiple fallbacks
297 this.disableErrorDisplay()
299 this.player.src = () => true
300 this.player.playbackRate(1)
302 const previousVideoFile = this.currentVideoFile
303 this.currentVideoFile = videoFile
305 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, done)
307 this.trigger('videoFileUpdate')
310 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, done: Function) {
311 console.log('Adding ' + magnetOrTorrentUrl + '.')
313 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
314 console.log('Added ' + magnetOrTorrentUrl + '.')
316 this.flushVideoFile(previousVideoFile)
318 const options = { autoplay: true, controls: true }
319 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
320 if (err) return this.fallbackToHttp()
322 this.renderer = renderer
323 if (!this.player.paused()) {
324 const playPromise = this.player.play()
325 if (playPromise !== undefined) return playPromise.then(done)
334 this.torrent.on('error', err => this.handleError(err))
336 this.torrent.on('warning', (err: any) => {
337 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
338 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
340 // Users don't care about issues with WebRTC, but developers do so log it in the console
341 if (err.message.indexOf('Ice connection failed') !== -1) {
346 // Magnet hash is not up to date with the torrent file, add directly the torrent file
347 if (err.message.indexOf('incorrect info hash') !== -1) {
348 console.error('Incorrect info hash detected, falling back to torrent file.')
349 return this.addTorrent(this.torrent['xs'], previousVideoFile, done)
352 return this.handleError(err)
356 updateResolution (resolutionId: number) {
357 // Remember player state
358 const currentTime = this.player.currentTime()
359 const isPaused = this.player.paused()
361 // Remove poster to have black background
362 this.playerElement.poster = ''
364 // Hide bigPlayButton
366 this.player.bigPlayButton.hide()
369 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
370 this.updateVideoFile(newVideoFile, () => {
371 this.player.currentTime(currentTime)
372 this.player.handleTechSeeked_()
376 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
377 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
378 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
380 webtorrent.remove(videoFile.magnetUri)
381 console.log('Removed ' + videoFile.magnetUri)
385 setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
386 this.videoViewUrl = videoViewUrl
387 this.videoDuration = videoDuration
388 this.videoFiles = files
390 // Re run view add for the new video
392 this.updateVideoFile(undefined, () => this.player.play())
395 private initializePlayer (options: PeertubePluginOptions) {
396 if (this.autoplay === true) {
397 this.updateVideoFile(undefined, () => this.player.play())
399 this.player.one('play', () => {
401 this.updateVideoFile(undefined, () => this.player.play())
406 private runTorrentInfoScheduler () {
407 this.torrentInfoInterval = setInterval(() => {
408 // Not initialized yet
409 if (this.torrent === undefined) return
412 if (this.torrent === null) return this.trigger('torrentInfo', false)
414 return this.trigger('torrentInfo', {
415 downloadSpeed: this.torrent.downloadSpeed,
416 numPeers: this.torrent.numPeers,
417 uploadSpeed: this.torrent.uploadSpeed
422 private runViewAdd () {
423 this.clearVideoViewInterval()
425 // After 30 seconds (or 3/4 of the video), add a view to the video
426 let minSecondsToView = 30
428 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
430 let secondsViewed = 0
431 this.videoViewInterval = setInterval(() => {
432 if (this.player && !this.player.paused()) {
435 if (secondsViewed > minSecondsToView) {
436 this.clearVideoViewInterval()
438 this.addViewToVideo().catch(err => console.error(err))
444 private clearVideoViewInterval () {
445 if (this.videoViewInterval !== undefined) {
446 clearInterval(this.videoViewInterval)
447 this.videoViewInterval = undefined
451 private addViewToVideo () {
452 return fetch(this.videoViewUrl, { method: 'POST' })
455 private fallbackToHttp () {
456 this.flushVideoFile(this.currentVideoFile, true)
459 // Enable error display now this is our last fallback
460 this.player.one('error', () => this.enableErrorDisplay())
462 const httpUrl = this.currentVideoFile.fileUrl
463 this.player.src = this.savePlayerSrcFunction
464 this.player.src(httpUrl)
468 private handleError (err: Error | string) {
469 return this.player.trigger('customError', { err })
472 private enableErrorDisplay () {
473 this.player.addClass('vjs-error-display-enabled')
476 private disableErrorDisplay () {
477 this.player.removeClass('vjs-error-display-enabled')
480 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)