1 // FIXME: something weird with our path definition in tsconfig and typings
3 import * as videojs from 'video.js'
5 import * as WebTorrent from 'webtorrent'
6 import { renderVideo } from './video-renderer'
7 import { LoadedQualityData, PlayerNetworkInfo, VideoJSComponentInterface, WebtorrentPluginOptions } from '../peertube-videojs-typings'
8 import { getRtcConfig, timeToInt, videoFileMaxByResolution, videoFileMinByResolution } from '../utils'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
11 getAverageBandwidthInStore,
14 getStoredWebTorrentEnabled,
16 } from '../peertube-player-local-storage'
17 import { VideoFile } from '@shared/models'
19 const CacheChunkStore = require('cache-chunk-store')
27 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
28 class WebTorrentPlugin extends Plugin {
29 private readonly playerElement: HTMLVideoElement
31 private readonly autoplay: boolean = false
32 private readonly startTime: number = 0
33 private readonly savePlayerSrcFunction: Function
34 private readonly videoFiles: VideoFile[]
35 private readonly videoDuration: number
36 private readonly CONSTANTS = {
37 INFO_SCHEDULER: 1000, // Don't change this
38 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
39 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
40 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
41 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
42 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
45 private readonly webtorrent = new WebTorrent({
47 rtcConfig: getRtcConfig()
53 private currentVideoFile: VideoFile
54 private torrent: WebTorrent.Torrent
57 private fakeRenderer: any
58 private destroyingFakeRenderer = false
60 private autoResolution = true
61 private autoResolutionPossible = true
62 private isAutoResolutionObservation = false
63 private playerRefusedP2P = false
65 private torrentInfoInterval: any
66 private autoQualityInterval: any
67 private addTorrentDelay: any
68 private qualityObservationTimer: any
69 private runAutoQualitySchedulerTimer: any
71 private downloadSpeeds: number[] = []
73 constructor (player: videojs.Player, options: WebtorrentPluginOptions) {
74 super(player, options)
76 this.startTime = timeToInt(options.startTime)
78 // Disable auto play on iOS
79 this.autoplay = options.autoplay && this.isIOS() === false
80 this.playerRefusedP2P = !getStoredWebTorrentEnabled()
82 this.videoFiles = options.videoFiles
83 this.videoDuration = options.videoDuration
85 this.savePlayerSrcFunction = this.player.src
86 this.playerElement = options.playerElement
88 this.player.ready(() => {
89 const playerOptions = this.player.options_
91 const volume = getStoredVolume()
92 if (volume !== undefined) this.player.volume(volume)
94 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
95 if (muted !== undefined) this.player.muted(muted)
97 this.player.duration(options.videoDuration)
99 this.initializePlayer()
100 this.runTorrentInfoScheduler()
102 this.player.one('play', () => {
103 // Don't run immediately scheduler, wait some seconds the TCP connections are made
104 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
110 clearTimeout(this.addTorrentDelay)
111 clearTimeout(this.qualityObservationTimer)
112 clearTimeout(this.runAutoQualitySchedulerTimer)
114 clearInterval(this.torrentInfoInterval)
115 clearInterval(this.autoQualityInterval)
117 // Don't need to destroy renderer, video player will be destroyed
118 this.flushVideoFile(this.currentVideoFile, false)
120 this.destroyFakeRenderer()
123 getCurrentResolutionId () {
124 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
128 videoFile?: VideoFile,
134 done: () => void = () => { /* empty */ }
136 // Automatically choose the adapted video file
137 if (videoFile === undefined) {
138 const savedAverageBandwidth = getAverageBandwidthInStore()
139 videoFile = savedAverageBandwidth
140 ? this.getAppropriateFile(savedAverageBandwidth)
141 : this.pickAverageVideoFile()
144 // Don't add the same video file once again
145 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
149 // Do not display error to user because we will have multiple fallback
150 this.disableErrorDisplay()
152 // Hack to "simulate" src link in video.js >= 6
153 // Without this, we can't play the video after pausing it
154 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
155 this.player.src = () => true
156 const oldPlaybackRate = this.player.playbackRate()
158 const previousVideoFile = this.currentVideoFile
159 this.currentVideoFile = videoFile
161 // Don't try on iOS that does not support MediaSource
162 // Or don't use P2P if webtorrent is disabled
163 if (this.isIOS() || this.playerRefusedP2P) {
164 return this.fallbackToHttp(options, () => {
165 this.player.playbackRate(oldPlaybackRate)
170 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
171 this.player.playbackRate(oldPlaybackRate)
176 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.currentVideoFile.resolution.id })
179 updateResolution (resolutionId: number, delay = 0) {
180 // Remember player state
181 const currentTime = this.player.currentTime()
182 const isPaused = this.player.paused()
184 // Remove poster to have black background
185 this.playerElement.poster = ''
187 // Hide bigPlayButton
189 this.player.bigPlayButton.hide()
192 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
196 seek: currentTime + (delay / 1000)
198 this.updateVideoFile(newVideoFile, options)
201 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
202 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
203 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
205 this.webtorrent.remove(videoFile.magnetUri)
206 console.log('Removed ' + videoFile.magnetUri)
210 enableAutoResolution () {
211 this.autoResolution = true
212 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
215 disableAutoResolution (forbid = false) {
216 if (forbid === true) this.autoResolutionPossible = false
218 this.autoResolution = false
219 this.trigger('autoResolutionChange', { possible: this.autoResolutionPossible })
220 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
228 magnetOrTorrentUrl: string,
229 previousVideoFile: VideoFile,
230 options: PlayOptions,
233 console.log('Adding ' + magnetOrTorrentUrl + '.')
235 const oldTorrent = this.torrent
236 const torrentOptions = {
237 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
238 store: function (chunkLength: number, storeOpts: any) {
239 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
245 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
246 console.log('Added ' + magnetOrTorrentUrl + '.')
249 // Pause the old torrent
250 this.stopTorrent(oldTorrent)
252 // We use a fake renderer so we download correct pieces of the next file
253 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
256 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
257 this.addTorrentDelay = setTimeout(() => {
258 // We don't need the fake renderer anymore
259 this.destroyFakeRenderer()
261 const paused = this.player.paused()
263 this.flushVideoFile(previousVideoFile)
265 // Update progress bar (just for the UI), do not wait rendering
266 if (options.seek) this.player.currentTime(options.seek)
268 const renderVideoOptions = { autoplay: false, controls: true }
269 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
270 this.renderer = renderer
272 if (err) return this.fallbackToHttp(options, done)
274 return this.tryToPlay(err => {
275 if (err) return done(err)
277 if (options.seek) this.seek(options.seek)
278 if (options.forcePlay === false && paused === true) this.player.pause()
283 }, options.delay || 0)
286 this.torrent.on('error', (err: any) => console.error(err))
288 this.torrent.on('warning', (err: any) => {
289 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
290 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
292 // Users don't care about issues with WebRTC, but developers do so log it in the console
293 if (err.message.indexOf('Ice connection failed') !== -1) {
298 // Magnet hash is not up to date with the torrent file, add directly the torrent file
299 if (err.message.indexOf('incorrect info hash') !== -1) {
300 console.error('Incorrect info hash detected, falling back to torrent file.')
301 const newOptions = { forcePlay: true, seek: options.seek }
302 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
305 // Remote instance is down
306 if (err.message.indexOf('from xs param') !== -1) {
307 this.handleError(err)
314 private tryToPlay (done?: (err?: Error) => void) {
315 if (!done) done = function () { /* empty */ }
317 const playPromise = this.player.play()
318 if (playPromise !== undefined) {
319 return playPromise.then(done)
320 .catch((err: Error) => {
321 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
327 this.player.posterImage.show()
328 this.player.removeClass('vjs-has-autoplay')
329 this.player.removeClass('vjs-has-big-play-button-clicked')
338 private seek (time: number) {
339 this.player.currentTime(time)
340 this.player.handleTechSeeked_()
343 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
344 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
345 if (this.videoFiles.length === 1) return this.videoFiles[0]
347 // Don't change the torrent is the play was ended
348 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
350 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
352 // Limit resolution according to player height
353 const playerHeight = this.playerElement.offsetHeight
355 // We take the first resolution just above the player height
356 // Example: player height is 530px, we want the 720p file instead of 480p
357 let maxResolution = this.videoFiles[0].resolution.id
358 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
359 const resolutionId = this.videoFiles[i].resolution.id
360 if (resolutionId >= playerHeight) {
361 maxResolution = resolutionId
366 // Filter videos we can play according to our screen resolution and bandwidth
367 const filteredFiles = this.videoFiles
368 .filter(f => f.resolution.id <= maxResolution)
370 const fileBitrate = (f.size / this.videoDuration)
371 let threshold = fileBitrate
373 // If this is for a higher resolution or an initial load: add a margin
374 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
375 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
378 return averageDownloadSpeed > threshold
381 // If the download speed is too bad, return the lowest resolution we have
382 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
384 return videoFileMaxByResolution(filteredFiles)
387 private getAndSaveActualDownloadSpeed () {
388 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
389 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
390 if (lastDownloadSpeeds.length === 0) return -1
392 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
393 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
395 // Save the average bandwidth for future use
396 saveAverageBandwidth(averageBandwidth)
398 return averageBandwidth
401 private initializePlayer () {
402 this.buildQualities()
404 if (this.autoplay === true) {
405 this.player.posterImage.hide()
407 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
411 const oldPlay = this.player.play.bind(this.player)
412 this.player.play = () => {
413 this.player.addClass('vjs-has-big-play-button-clicked')
414 this.player.play = oldPlay
416 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
420 private runAutoQualityScheduler () {
421 this.autoQualityInterval = setInterval(() => {
423 // Not initialized or in HTTP fallback
424 if (this.torrent === undefined || this.torrent === null) return
425 if (this.autoResolution === false) return
426 if (this.isAutoResolutionObservation === true) return
428 const file = this.getAppropriateFile()
429 let changeResolution = false
430 let changeResolutionDelay = 0
433 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
434 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
435 changeResolution = true
436 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
437 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
438 changeResolution = true
439 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
442 if (changeResolution === true) {
443 this.updateResolution(file.resolution.id, changeResolutionDelay)
445 // Wait some seconds in observation of our new resolution
446 this.isAutoResolutionObservation = true
448 this.qualityObservationTimer = setTimeout(() => {
449 this.isAutoResolutionObservation = false
450 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
452 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
455 private isPlayerWaiting () {
456 return this.player && this.player.hasClass('vjs-waiting')
459 private runTorrentInfoScheduler () {
460 this.torrentInfoInterval = setInterval(() => {
461 // Not initialized yet
462 if (this.torrent === undefined) return
465 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
467 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
468 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
470 return this.player.trigger('p2pInfo', {
478 downloadSpeed: this.torrent.downloadSpeed,
479 numPeers: this.torrent.numPeers,
480 uploadSpeed: this.torrent.uploadSpeed,
481 downloaded: this.torrent.downloaded,
482 uploaded: this.torrent.uploaded
484 } as PlayerNetworkInfo)
485 }, this.CONSTANTS.INFO_SCHEDULER)
488 private fallbackToHttp (options: PlayOptions, done?: Function) {
489 const paused = this.player.paused()
491 this.disableAutoResolution(true)
493 this.flushVideoFile(this.currentVideoFile, true)
496 // Enable error display now this is our last fallback
497 this.player.one('error', () => this.enableErrorDisplay())
499 const httpUrl = this.currentVideoFile.fileUrl
500 this.player.src = this.savePlayerSrcFunction
501 this.player.src(httpUrl)
505 // We changed the source, so reinit captions
506 this.player.trigger('sourcechange')
508 return this.tryToPlay(err => {
509 if (err && done) return done(err)
511 if (options.seek) this.seek(options.seek)
512 if (options.forcePlay === false && paused === true) this.player.pause()
514 if (done) return done()
518 private handleError (err: Error | string) {
519 return this.player.trigger('customError', { err })
522 private enableErrorDisplay () {
523 this.player.addClass('vjs-error-display-enabled')
526 private disableErrorDisplay () {
527 this.player.removeClass('vjs-error-display-enabled')
531 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
534 private pickAverageVideoFile () {
535 if (this.videoFiles.length === 1) return this.videoFiles[0]
537 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
540 private stopTorrent (torrent: WebTorrent.Torrent) {
542 // Pause does not remove actual peers (in particular the webseed peer)
543 torrent.removePeer(torrent[ 'ws' ])
546 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
547 this.destroyingFakeRenderer = false
549 const fakeVideoElem = document.createElement('video')
550 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
551 this.fakeRenderer = renderer
553 // The renderer returns an error when we destroy it, so skip them
554 if (this.destroyingFakeRenderer === false && err) {
555 console.error('Cannot render new torrent in fake video element.', err)
558 // Load the future file at the correct time (in delay MS - 2 seconds)
559 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
563 private destroyFakeRenderer () {
564 if (this.fakeRenderer) {
565 this.destroyingFakeRenderer = true
567 if (this.fakeRenderer.destroy) {
569 this.fakeRenderer.destroy()
571 console.log('Cannot destroy correctly fake renderer.', err)
574 this.fakeRenderer = undefined
578 private buildQualities () {
579 const qualityLevelsPayload = []
581 for (const file of this.videoFiles) {
582 const representation = {
583 id: file.resolution.id,
584 label: this.buildQualityLabel(file),
585 height: file.resolution.id,
589 this.player.qualityLevels().addQualityLevel(representation)
591 qualityLevelsPayload.push({
592 id: representation.id,
593 label: representation.label,
598 const payload: LoadedQualityData = {
599 qualitySwitchCallback: (d: any) => this.qualitySwitchCallback(d),
601 video: qualityLevelsPayload
604 this.player.tech_.trigger('loadedqualitydata', payload)
607 private buildQualityLabel (file: VideoFile) {
608 let label = file.resolution.label
610 if (file.fps && file.fps >= 50) {
617 private qualitySwitchCallback (id: number) {
619 if (this.autoResolutionPossible === true) this.enableAutoResolution()
623 this.disableAutoResolution()
624 this.updateResolution(id)
627 private changeQuality () {
628 const resolutionId = this.currentVideoFile.resolution.id
629 const qualityLevels = this.player.qualityLevels()
631 if (resolutionId === -1) {
632 qualityLevels.selectedIndex = -1
636 for (let i = 0; i < qualityLevels; i++) {
637 const q = this.player.qualityLevels[i]
638 if (q.height === resolutionId) qualityLevels.selectedIndex = i
643 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
644 export { WebTorrentPlugin }