1 import videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { logger } from '@root-helpers/logger'
4 import { isIOS } from '@root-helpers/web-browser'
5 import { timeToInt } from '@shared/core-utils'
6 import { VideoFile } from '@shared/models'
7 import { getAverageBandwidthInStore, getStoredMute, getStoredVolume, saveAverageBandwidth } from '../../peertube-player-local-storage'
8 import { PeerTubeResolution, PlayerNetworkInfo, WebtorrentPluginOptions } from '../../types'
9 import { getRtcConfig, videoFileMaxByResolution, videoFileMinByResolution } from '../common'
10 import { PeertubeChunkStore } from './peertube-chunk-store'
11 import { renderVideo } from './video-renderer'
13 const CacheChunkStore = require('cache-chunk-store')
21 const Plugin = videojs.getPlugin('plugin')
23 class WebTorrentPlugin extends Plugin {
24 readonly videoFiles: VideoFile[]
26 private readonly playerElement: HTMLVideoElement
28 private readonly autoplay: boolean = false
29 private readonly startTime: number = 0
30 private readonly savePlayerSrcFunction: videojs.Player['src']
31 private readonly videoDuration: number
32 private readonly CONSTANTS = {
33 INFO_SCHEDULER: 1000, // Don't change this
34 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
35 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
36 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
37 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
38 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
41 private readonly webtorrent = new WebTorrent({
43 rtcConfig: getRtcConfig()
48 private currentVideoFile: VideoFile
49 private torrent: WebTorrent.Torrent
52 private fakeRenderer: any
53 private destroyingFakeRenderer = false
55 private autoResolution = true
56 private autoResolutionPossible = true
57 private isAutoResolutionObservation = false
58 private playerRefusedP2P = false
60 private torrentInfoInterval: any
61 private autoQualityInterval: any
62 private addTorrentDelay: any
63 private qualityObservationTimer: any
64 private runAutoQualitySchedulerTimer: any
66 private downloadSpeeds: number[] = []
68 constructor (player: videojs.Player, options?: WebtorrentPluginOptions) {
71 this.startTime = timeToInt(options.startTime)
73 // Custom autoplay handled by webtorrent because we lazy play the video
74 this.autoplay = options.autoplay
76 this.playerRefusedP2P = options.playerRefusedP2P
78 this.videoFiles = options.videoFiles
79 this.videoDuration = options.videoDuration
81 this.savePlayerSrcFunction = this.player.src
82 this.playerElement = options.playerElement
84 this.player.ready(() => {
85 const playerOptions = this.player.options_
87 const volume = getStoredVolume()
88 if (volume !== undefined) this.player.volume(volume)
90 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
91 if (muted !== undefined) this.player.muted(muted)
93 this.player.duration(options.videoDuration)
95 this.initializePlayer()
96 this.runTorrentInfoScheduler()
98 this.player.one('play', () => {
99 // Don't run immediately scheduler, wait some seconds the TCP connections are made
100 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
106 clearTimeout(this.addTorrentDelay)
107 clearTimeout(this.qualityObservationTimer)
108 clearTimeout(this.runAutoQualitySchedulerTimer)
110 clearInterval(this.torrentInfoInterval)
111 clearInterval(this.autoQualityInterval)
113 // Don't need to destroy renderer, video player will be destroyed
114 this.flushVideoFile(this.currentVideoFile, false)
116 this.destroyFakeRenderer()
119 getCurrentResolutionId () {
120 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
124 videoFile?: VideoFile,
130 done: () => void = () => { /* empty */ }
132 // Automatically choose the adapted video file
134 const savedAverageBandwidth = getAverageBandwidthInStore()
135 videoFile = savedAverageBandwidth
136 ? this.getAppropriateFile(savedAverageBandwidth)
137 : this.pickAverageVideoFile()
141 throw Error(`Can't update video file since videoFile is undefined.`)
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.player.peertube().hideFatalError();
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 as any).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 (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)
175 this.selectAppropriateResolution(true)
178 updateEngineResolution (resolutionId: number, delay = 0) {
179 // Remember player state
180 const currentTime = this.player.currentTime()
181 const isPaused = this.player.paused()
183 // Hide bigPlayButton
185 this.player.bigPlayButton.hide()
188 // Audio-only (resolutionId === 0) gets special treatment
189 if (resolutionId === 0) {
190 // Audio-only: show poster, do not auto-hide controls
191 this.player.addClass('vjs-playing-audio-only-content')
192 this.player.posterImage.show()
194 // Hide poster to have black background
195 this.player.removeClass('vjs-playing-audio-only-content')
196 this.player.posterImage.hide()
199 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
203 seek: currentTime + (delay / 1000)
206 this.updateVideoFile(newVideoFile, options)
209 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
210 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
211 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
213 this.webtorrent.remove(videoFile.magnetUri)
214 logger.info(`Removed ${videoFile.magnetUri}`)
218 disableAutoResolution () {
219 this.autoResolution = false
220 this.autoResolutionPossible = false
221 this.player.peertubeResolutions().disableAutoResolution()
224 isAutoResolutionPossible () {
225 return this.autoResolutionPossible
232 getCurrentVideoFile () {
233 return this.currentVideoFile
236 changeQuality (id: number) {
238 if (this.autoResolutionPossible === true) {
239 this.autoResolution = true
241 this.selectAppropriateResolution(false)
247 this.autoResolution = false
248 this.updateEngineResolution(id)
249 this.selectAppropriateResolution(false)
253 magnetOrTorrentUrl: string,
254 previousVideoFile: VideoFile,
255 options: PlayOptions,
256 done: (err?: Error) => void
258 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
260 logger.info(`Adding ${magnetOrTorrentUrl}.`)
262 const oldTorrent = this.torrent
263 const torrentOptions = {
264 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
265 store: function (chunkLength: number, storeOpts: any) {
266 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
272 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
273 logger.info(`Added ${magnetOrTorrentUrl}.`)
276 // Pause the old torrent
277 this.stopTorrent(oldTorrent)
279 // We use a fake renderer so we download correct pieces of the next file
280 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
283 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
284 this.addTorrentDelay = setTimeout(() => {
285 // We don't need the fake renderer anymore
286 this.destroyFakeRenderer()
288 const paused = this.player.paused()
290 this.flushVideoFile(previousVideoFile)
292 // Update progress bar (just for the UI), do not wait rendering
293 if (options.seek) this.player.currentTime(options.seek)
295 const renderVideoOptions = { autoplay: false, controls: true }
296 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
297 this.renderer = renderer
299 if (err) return this.fallbackToHttp(options, done)
301 return this.tryToPlay(err => {
302 if (err) return done(err)
304 if (options.seek) this.seek(options.seek)
305 if (options.forcePlay === false && paused === true) this.player.pause()
310 }, options.delay || 0)
313 this.torrent.on('error', (err: any) => logger.error(err))
315 this.torrent.on('warning', (err: any) => {
316 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
317 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
319 // Users don't care about issues with WebRTC, but developers do so log it in the console
320 if (err.message.indexOf('Ice connection failed') !== -1) {
325 // Magnet hash is not up to date with the torrent file, add directly the torrent file
326 if (err.message.indexOf('incorrect info hash') !== -1) {
327 logger.error('Incorrect info hash detected, falling back to torrent file.')
328 const newOptions = { forcePlay: true, seek: options.seek }
329 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
332 // Remote instance is down
333 if (err.message.indexOf('from xs param') !== -1) {
334 this.handleError(err)
341 private tryToPlay (done?: (err?: Error) => void) {
342 if (!done) done = function () { /* empty */ }
344 const playPromise = this.player.play()
345 if (playPromise !== undefined) {
346 return playPromise.then(() => done())
347 .catch((err: Error) => {
348 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
354 this.player.posterImage.show()
355 this.player.removeClass('vjs-has-autoplay')
356 this.player.removeClass('vjs-has-big-play-button-clicked')
357 this.player.removeClass('vjs-playing-audio-only-content')
366 private seek (time: number) {
367 this.player.currentTime(time)
368 this.player.handleTechSeeked_()
371 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
372 if (this.videoFiles === undefined) return undefined
373 if (this.videoFiles.length === 1) return this.videoFiles[0]
375 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
376 if (files.length === 0) return undefined
378 // Don't change the torrent if the player ended
379 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
381 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
383 // Limit resolution according to player height
384 const playerHeight = this.playerElement.offsetHeight
386 // We take the first resolution just above the player height
387 // Example: player height is 530px, we want the 720p file instead of 480p
388 let maxResolution = files[0].resolution.id
389 for (let i = files.length - 1; i >= 0; i--) {
390 const resolutionId = files[i].resolution.id
391 if (resolutionId !== 0 && resolutionId >= playerHeight) {
392 maxResolution = resolutionId
397 // Filter videos we can play according to our screen resolution and bandwidth
398 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
400 const fileBitrate = (f.size / this.videoDuration)
401 let threshold = fileBitrate
403 // If this is for a higher resolution or an initial load: add a margin
404 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
405 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
408 return averageDownloadSpeed > threshold
411 // If the download speed is too bad, return the lowest resolution we have
412 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
414 return videoFileMaxByResolution(filteredFiles)
417 private getAndSaveActualDownloadSpeed () {
418 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
419 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
420 if (lastDownloadSpeeds.length === 0) return -1
422 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
423 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
425 // Save the average bandwidth for future use
426 saveAverageBandwidth(averageBandwidth)
428 return averageBandwidth
431 private initializePlayer () {
432 this.buildQualities()
434 if (this.videoFiles.length === 0) {
435 this.player.addClass('disabled')
440 this.player.posterImage.hide()
442 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
446 const oldPlay = this.player.play.bind(this.player);
447 (this.player as any).play = () => {
448 this.player.addClass('vjs-has-big-play-button-clicked')
449 this.player.play = oldPlay
451 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
455 private runAutoQualityScheduler () {
456 this.autoQualityInterval = setInterval(() => {
458 // Not initialized or in HTTP fallback
459 if (this.torrent === undefined || this.torrent === null) return
460 if (this.autoResolution === false) return
461 if (this.isAutoResolutionObservation === true) return
463 const file = this.getAppropriateFile()
464 let changeResolution = false
465 let changeResolutionDelay = 0
468 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
469 logger.info(`Downgrading automatically the resolution to: ${file.resolution.label}`)
470 changeResolution = true
471 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
472 logger.info(`Upgrading automatically the resolution to: ${file.resolution.label}`)
473 changeResolution = true
474 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
477 if (changeResolution === true) {
478 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
480 // Wait some seconds in observation of our new resolution
481 this.isAutoResolutionObservation = true
483 this.qualityObservationTimer = setTimeout(() => {
484 this.isAutoResolutionObservation = false
485 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
487 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
490 private isPlayerWaiting () {
491 return this.player?.hasClass('vjs-waiting')
494 private runTorrentInfoScheduler () {
495 this.torrentInfoInterval = setInterval(() => {
496 // Not initialized yet
497 if (this.torrent === undefined) return
500 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
502 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
503 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
505 return this.player.trigger('p2pInfo', {
506 source: 'webtorrent',
514 downloadSpeed: this.torrent.downloadSpeed,
515 numPeers: this.torrent.numPeers,
516 uploadSpeed: this.torrent.uploadSpeed,
517 downloaded: this.torrent.downloaded,
518 uploaded: this.torrent.uploaded
520 bandwidthEstimate: this.webtorrent.downloadSpeed
521 } as PlayerNetworkInfo)
522 }, this.CONSTANTS.INFO_SCHEDULER)
525 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
526 const paused = this.player.paused()
528 this.disableAutoResolution()
530 this.flushVideoFile(this.currentVideoFile, true)
533 // Enable error display now this is our last fallback
534 this.player.one('error', () => this.player.peertube().displayFatalError())
536 const httpUrl = this.currentVideoFile.fileUrl
537 this.player.src = this.savePlayerSrcFunction
538 this.player.src(httpUrl)
540 this.selectAppropriateResolution(true)
542 // We changed the source, so reinit captions
543 this.player.trigger('sourcechange')
545 return this.tryToPlay(err => {
546 if (err && done) return done(err)
548 if (options.seek) this.seek(options.seek)
549 if (options.forcePlay === false && paused === true) this.player.pause()
551 if (done) return done()
555 private handleError (err: Error | string) {
556 return this.player.trigger('customError', { err })
559 private pickAverageVideoFile () {
560 if (this.videoFiles.length === 1) return this.videoFiles[0]
562 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
563 return files[Math.floor(files.length / 2)]
566 private stopTorrent (torrent: WebTorrent.Torrent) {
568 // Pause does not remove actual peers (in particular the webseed peer)
569 torrent.removePeer(torrent['ws'])
572 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
573 this.destroyingFakeRenderer = false
575 const fakeVideoElem = document.createElement('video')
576 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
577 this.fakeRenderer = renderer
579 // The renderer returns an error when we destroy it, so skip them
580 if (this.destroyingFakeRenderer === false && err) {
581 logger.error('Cannot render new torrent in fake video element.', err)
584 // Load the future file at the correct time (in delay MS - 2 seconds)
585 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
589 private destroyFakeRenderer () {
590 if (this.fakeRenderer) {
591 this.destroyingFakeRenderer = true
593 if (this.fakeRenderer.destroy) {
595 this.fakeRenderer.destroy()
597 logger.info('Cannot destroy correctly fake renderer.', err)
600 this.fakeRenderer = undefined
604 private buildQualities () {
605 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
606 id: file.resolution.id,
607 label: this.buildQualityLabel(file),
608 height: file.resolution.id,
610 selectCallback: () => this.changeQuality(file.resolution.id)
615 label: this.player.localize('Auto'),
617 selectCallback: () => this.changeQuality(-1)
620 this.player.peertubeResolutions().add(resolutions)
623 private buildQualityLabel (file: VideoFile) {
624 let label = file.resolution.label
626 if (file.fps && file.fps >= 50) {
633 private selectAppropriateResolution (byEngine: boolean) {
634 const resolution = this.autoResolution
636 : this.getCurrentResolutionId()
638 const autoResolutionChosen = this.autoResolution
639 ? this.getCurrentResolutionId()
642 this.player.peertubeResolutions().select({ id: resolution, autoResolutionChosenId: autoResolutionChosen, byEngine })
646 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
647 export { WebTorrentPlugin }