1 import * as videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { VideoFile } from '../../../../shared/models/videos/video.model'
4 import { renderVideo } from './video-renderer'
5 import './settings-menu-button'
6 import { PeertubePluginOptions, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { getStoredMute, getStoredVolume, saveMuteInStore, saveVolumeInStore } from './utils'
9 const webtorrent = new WebTorrent({
14 urls: 'stun:stun.stunprotocol.org'
17 urls: 'stun:stun.framasoft.org'
25 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
26 class PeerTubePlugin extends Plugin {
27 private readonly playerElement: HTMLVideoElement
28 private readonly autoplay: boolean = false
29 private readonly savePlayerSrcFunction: Function
31 private currentVideoFile: VideoFile
32 private videoFiles: VideoFile[]
33 private torrent: WebTorrent.Torrent
34 private videoViewUrl: string
35 private videoDuration: number
36 private videoViewInterval
37 private torrentInfoInterval
39 constructor (player: videojs.Player, options: PeertubePluginOptions) {
40 super(player, options)
42 // Fix canplay event on google chrome by disabling default videojs autoplay
43 this.autoplay = this.player.options_.autoplay
44 this.player.options_.autoplay = false
46 this.videoFiles = options.videoFiles
47 this.videoViewUrl = options.videoViewUrl
48 this.videoDuration = options.videoDuration
50 this.savePlayerSrcFunction = this.player.src
51 // Hack to "simulate" src link in video.js >= 6
52 // Without this, we can't play the video after pausing it
53 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
54 this.player.src = () => true
56 this.playerElement = options.playerElement
58 this.player.ready(() => {
59 const volume = getStoredVolume()
60 if (volume !== undefined) this.player.volume(volume)
61 const muted = getStoredMute()
62 if (muted !== undefined) this.player.muted(muted)
64 this.initializePlayer()
65 this.runTorrentInfoScheduler()
69 this.player.on('volumechange', () => {
70 saveVolumeInStore(this.player.volume())
71 saveMuteInStore(this.player.muted())
76 clearInterval(this.videoViewInterval)
77 clearInterval(this.torrentInfoInterval)
79 // Don't need to destroy renderer, video player will be destroyed
80 this.flushVideoFile(this.currentVideoFile, false)
83 getCurrentResolutionId () {
84 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
87 getCurrentResolutionLabel () {
88 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
91 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
92 if (done === undefined) {
93 done = () => { /* empty */ }
97 if (videoFile === undefined) {
98 videoFile = this.videoFiles[0]
101 // Don't add the same video file once again
102 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
106 // Do not display error to user because we will have multiple fallback
107 this.disableErrorDisplay()
109 this.player.src = () => true
110 const oldPlaybackRate = this.player.playbackRate()
112 const previousVideoFile = this.currentVideoFile
113 this.currentVideoFile = videoFile
115 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, () => {
116 this.player.playbackRate(oldPlaybackRate)
120 this.trigger('videoFileUpdate')
123 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, done: Function) {
124 console.log('Adding ' + magnetOrTorrentUrl + '.')
126 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
127 console.log('Added ' + magnetOrTorrentUrl + '.')
129 this.flushVideoFile(previousVideoFile)
131 const options = { autoplay: true, controls: true }
132 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
133 this.renderer = renderer
135 if (err) return this.fallbackToHttp(done)
137 if (!this.player.paused()) {
138 const playPromise = this.player.play()
139 if (playPromise !== undefined) return playPromise.then(done)
148 this.torrent.on('error', err => this.handleError(err))
150 this.torrent.on('warning', (err: any) => {
151 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
152 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
154 // Users don't care about issues with WebRTC, but developers do so log it in the console
155 if (err.message.indexOf('Ice connection failed') !== -1) {
160 // Magnet hash is not up to date with the torrent file, add directly the torrent file
161 if (err.message.indexOf('incorrect info hash') !== -1) {
162 console.error('Incorrect info hash detected, falling back to torrent file.')
163 return this.addTorrent(this.torrent['xs'], previousVideoFile, done)
166 return this.handleError(err)
170 updateResolution (resolutionId: number) {
171 // Remember player state
172 const currentTime = this.player.currentTime()
173 const isPaused = this.player.paused()
175 // Remove poster to have black background
176 this.playerElement.poster = ''
178 // Hide bigPlayButton
180 this.player.bigPlayButton.hide()
183 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
184 this.updateVideoFile(newVideoFile, () => {
185 this.player.currentTime(currentTime)
186 this.player.handleTechSeeked_()
190 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
191 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
192 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
194 webtorrent.remove(videoFile.magnetUri)
195 console.log('Removed ' + videoFile.magnetUri)
199 setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
200 this.videoViewUrl = videoViewUrl
201 this.videoDuration = videoDuration
202 this.videoFiles = files
204 // Re run view add for the new video
206 this.updateVideoFile(undefined, () => this.player.play())
209 private initializePlayer () {
210 this.initSmoothProgressBar()
212 this.alterInactivity()
214 if (this.autoplay === true) {
215 this.player.posterImage.hide()
216 this.updateVideoFile(undefined, () => this.player.play())
219 const oldPlay = this.player.play.bind(this.player)
220 this.player.play = () => {
221 this.updateVideoFile(undefined, () => oldPlay)
222 this.player.play = oldPlay
227 private runTorrentInfoScheduler () {
228 this.torrentInfoInterval = setInterval(() => {
229 // Not initialized yet
230 if (this.torrent === undefined) return
233 if (this.torrent === null) return this.trigger('torrentInfo', false)
235 return this.trigger('torrentInfo', {
236 downloadSpeed: this.torrent.downloadSpeed,
237 numPeers: this.torrent.numPeers,
238 uploadSpeed: this.torrent.uploadSpeed
243 private runViewAdd () {
244 this.clearVideoViewInterval()
246 // After 30 seconds (or 3/4 of the video), add a view to the video
247 let minSecondsToView = 30
249 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
251 let secondsViewed = 0
252 this.videoViewInterval = setInterval(() => {
253 if (this.player && !this.player.paused()) {
256 if (secondsViewed > minSecondsToView) {
257 this.clearVideoViewInterval()
259 this.addViewToVideo().catch(err => console.error(err))
265 private clearVideoViewInterval () {
266 if (this.videoViewInterval !== undefined) {
267 clearInterval(this.videoViewInterval)
268 this.videoViewInterval = undefined
272 private addViewToVideo () {
273 return fetch(this.videoViewUrl, { method: 'POST' })
276 private fallbackToHttp (done: Function) {
277 this.flushVideoFile(this.currentVideoFile, true)
280 // Enable error display now this is our last fallback
281 this.player.one('error', () => this.enableErrorDisplay())
283 const httpUrl = this.currentVideoFile.fileUrl
284 this.player.src = this.savePlayerSrcFunction
285 this.player.src(httpUrl)
291 private handleError (err: Error | string) {
292 return this.player.trigger('customError', { err })
295 private enableErrorDisplay () {
296 this.player.addClass('vjs-error-display-enabled')
299 private disableErrorDisplay () {
300 this.player.removeClass('vjs-error-display-enabled')
303 private alterInactivity () {
304 let saveInactivityTimeout: number
306 const disableInactivity = () => {
307 saveInactivityTimeout = this.player.options_.inactivityTimeout
308 this.player.options_.inactivityTimeout = 0
310 const enableInactivity = () => {
311 this.player.options_.inactivityTimeout = saveInactivityTimeout
314 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
316 this.player.controlBar.on('mouseenter', () => disableInactivity())
317 settingsDialog.on('mouseenter', () => disableInactivity())
318 this.player.controlBar.on('mouseleave', () => enableInactivity())
319 settingsDialog.on('mouseleave', () => enableInactivity())
322 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
323 private initSmoothProgressBar () {
324 const SeekBar = videojsUntyped.getComponent('SeekBar')
325 SeekBar.prototype.getPercent = function getPercent () {
326 // Allows for smooth scrubbing, when player can't keep up.
327 // const time = (this.player_.scrubbing()) ?
328 // this.player_.getCache().currentTime :
329 // this.player_.currentTime()
330 const time = this.player_.currentTime()
331 const percent = time / this.player_.duration()
332 return percent >= 1 ? 1 : percent
334 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
335 let newTime = this.calculateDistance(event) * this.player_.duration()
336 if (newTime === this.player_.duration()) {
337 newTime = newTime - 0.1
339 this.player_.currentTime(newTime)
345 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
346 export { PeerTubePlugin }