1 import videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { timeToInt } from '@shared/core-utils'
4 import { VideoFile } from '@shared/models'
6 getAverageBandwidthInStore,
11 } from '../peertube-player-local-storage'
12 import { PeerTubeResolution, PlayerNetworkInfo, WebtorrentPluginOptions } from '../peertube-videojs-typings'
13 import { getRtcConfig, isIOS, videoFileMaxByResolution, videoFileMinByResolution } from '../utils'
14 import { PeertubeChunkStore } from './peertube-chunk-store'
15 import { renderVideo } from './video-renderer'
17 const CacheChunkStore = require('cache-chunk-store')
25 const Plugin = videojs.getPlugin('plugin')
27 class WebTorrentPlugin extends Plugin {
28 readonly videoFiles: VideoFile[]
30 private readonly playerElement: HTMLVideoElement
32 private readonly autoplay: boolean = false
33 private readonly startTime: number = 0
34 private readonly savePlayerSrcFunction: videojs.Player['src']
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()
52 private currentVideoFile: VideoFile
53 private torrent: WebTorrent.Torrent
56 private fakeRenderer: any
57 private destroyingFakeRenderer = false
59 private autoResolution = true
60 private autoResolutionPossible = true
61 private isAutoResolutionObservation = false
62 private playerRefusedP2P = false
64 private torrentInfoInterval: any
65 private autoQualityInterval: any
66 private addTorrentDelay: any
67 private qualityObservationTimer: any
68 private runAutoQualitySchedulerTimer: any
70 private downloadSpeeds: number[] = []
72 constructor (player: videojs.Player, options?: WebtorrentPluginOptions) {
75 this.startTime = timeToInt(options.startTime)
77 // Disable auto play on iOS
78 this.autoplay = options.autoplay
79 this.playerRefusedP2P = !getStoredP2PEnabled()
81 this.videoFiles = options.videoFiles
82 this.videoDuration = options.videoDuration
84 this.savePlayerSrcFunction = this.player.src
85 this.playerElement = options.playerElement
87 this.player.ready(() => {
88 const playerOptions = this.player.options_
90 const volume = getStoredVolume()
91 if (volume !== undefined) this.player.volume(volume)
93 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
94 if (muted !== undefined) this.player.muted(muted)
96 this.player.duration(options.videoDuration)
98 this.initializePlayer()
99 this.runTorrentInfoScheduler()
101 this.player.one('play', () => {
102 // Don't run immediately scheduler, wait some seconds the TCP connections are made
103 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
109 clearTimeout(this.addTorrentDelay)
110 clearTimeout(this.qualityObservationTimer)
111 clearTimeout(this.runAutoQualitySchedulerTimer)
113 clearInterval(this.torrentInfoInterval)
114 clearInterval(this.autoQualityInterval)
116 // Don't need to destroy renderer, video player will be destroyed
117 this.flushVideoFile(this.currentVideoFile, false)
119 this.destroyFakeRenderer()
122 getCurrentResolutionId () {
123 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
127 videoFile?: VideoFile,
133 done: () => void = () => { /* empty */ }
135 // Automatically choose the adapted video file
137 const savedAverageBandwidth = getAverageBandwidthInStore()
138 videoFile = savedAverageBandwidth
139 ? this.getAppropriateFile(savedAverageBandwidth)
140 : this.pickAverageVideoFile()
144 throw Error(`Can't update video file since videoFile is undefined.`)
147 // Don't add the same video file once again
148 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
152 // Do not display error to user because we will have multiple fallback
153 this.disableErrorDisplay();
155 // Hack to "simulate" src link in video.js >= 6
156 // Without this, we can't play the video after pausing it
157 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
158 (this.player as any).src = () => true
159 const oldPlaybackRate = this.player.playbackRate()
161 const previousVideoFile = this.currentVideoFile
162 this.currentVideoFile = videoFile
164 // Don't try on iOS that does not support MediaSource
165 // Or don't use P2P if webtorrent is disabled
166 if (isIOS() || this.playerRefusedP2P) {
167 return this.fallbackToHttp(options, () => {
168 this.player.playbackRate(oldPlaybackRate)
173 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
174 this.player.playbackRate(oldPlaybackRate)
178 this.selectAppropriateResolution(true)
181 updateEngineResolution (resolutionId: number, delay = 0) {
182 // Remember player state
183 const currentTime = this.player.currentTime()
184 const isPaused = this.player.paused()
186 // Hide bigPlayButton
188 this.player.bigPlayButton.hide()
191 // Audio-only (resolutionId === 0) gets special treatment
192 if (resolutionId === 0) {
193 // Audio-only: show poster, do not auto-hide controls
194 this.player.addClass('vjs-playing-audio-only-content')
195 this.player.posterImage.show()
197 // Hide poster to have black background
198 this.player.removeClass('vjs-playing-audio-only-content')
199 this.player.posterImage.hide()
202 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
206 seek: currentTime + (delay / 1000)
209 this.updateVideoFile(newVideoFile, options)
212 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
213 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
214 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
216 this.webtorrent.remove(videoFile.magnetUri)
217 console.log('Removed ' + videoFile.magnetUri)
221 disableAutoResolution () {
222 this.autoResolution = false
223 this.autoResolutionPossible = false
224 this.player.peertubeResolutions().disableAutoResolution()
227 isAutoResolutionPossible () {
228 return this.autoResolutionPossible
235 getCurrentVideoFile () {
236 return this.currentVideoFile
239 changeQuality (id: number) {
241 if (this.autoResolutionPossible === true) {
242 this.autoResolution = true
244 this.selectAppropriateResolution(false)
250 this.autoResolution = false
251 this.updateEngineResolution(id)
252 this.selectAppropriateResolution(false)
256 magnetOrTorrentUrl: string,
257 previousVideoFile: VideoFile,
258 options: PlayOptions,
259 done: (err?: Error) => void
261 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
263 console.log('Adding ' + magnetOrTorrentUrl + '.')
265 const oldTorrent = this.torrent
266 const torrentOptions = {
267 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
268 store: function (chunkLength: number, storeOpts: any) {
269 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
275 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
276 console.log('Added ' + magnetOrTorrentUrl + '.')
279 // Pause the old torrent
280 this.stopTorrent(oldTorrent)
282 // We use a fake renderer so we download correct pieces of the next file
283 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
286 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
287 this.addTorrentDelay = setTimeout(() => {
288 // We don't need the fake renderer anymore
289 this.destroyFakeRenderer()
291 const paused = this.player.paused()
293 this.flushVideoFile(previousVideoFile)
295 // Update progress bar (just for the UI), do not wait rendering
296 if (options.seek) this.player.currentTime(options.seek)
298 const renderVideoOptions = { autoplay: false, controls: true }
299 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
300 this.renderer = renderer
302 if (err) return this.fallbackToHttp(options, done)
304 return this.tryToPlay(err => {
305 if (err) return done(err)
307 if (options.seek) this.seek(options.seek)
308 if (options.forcePlay === false && paused === true) this.player.pause()
313 }, options.delay || 0)
316 this.torrent.on('error', (err: any) => console.error(err))
318 this.torrent.on('warning', (err: any) => {
319 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
320 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
322 // Users don't care about issues with WebRTC, but developers do so log it in the console
323 if (err.message.indexOf('Ice connection failed') !== -1) {
328 // Magnet hash is not up to date with the torrent file, add directly the torrent file
329 if (err.message.indexOf('incorrect info hash') !== -1) {
330 console.error('Incorrect info hash detected, falling back to torrent file.')
331 const newOptions = { forcePlay: true, seek: options.seek }
332 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
335 // Remote instance is down
336 if (err.message.indexOf('from xs param') !== -1) {
337 this.handleError(err)
344 private tryToPlay (done?: (err?: Error) => void) {
345 if (!done) done = function () { /* empty */ }
347 const playPromise = this.player.play()
348 if (playPromise !== undefined) {
349 return playPromise.then(() => done())
350 .catch((err: Error) => {
351 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
357 this.player.posterImage.show()
358 this.player.removeClass('vjs-has-autoplay')
359 this.player.removeClass('vjs-has-big-play-button-clicked')
360 this.player.removeClass('vjs-playing-audio-only-content')
369 private seek (time: number) {
370 this.player.currentTime(time)
371 this.player.handleTechSeeked_()
374 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
375 if (this.videoFiles === undefined) return undefined
377 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
379 if (files.length === 0) return undefined
380 if (files.length === 1) return files[0]
382 // Don't change the torrent if the player ended
383 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
385 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
387 // Limit resolution according to player height
388 const playerHeight = this.playerElement.offsetHeight
390 // We take the first resolution just above the player height
391 // Example: player height is 530px, we want the 720p file instead of 480p
392 let maxResolution = files[0].resolution.id
393 for (let i = files.length - 1; i >= 0; i--) {
394 const resolutionId = files[i].resolution.id
395 if (resolutionId !== 0 && resolutionId >= playerHeight) {
396 maxResolution = resolutionId
401 // Filter videos we can play according to our screen resolution and bandwidth
402 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
404 const fileBitrate = (f.size / this.videoDuration)
405 let threshold = fileBitrate
407 // If this is for a higher resolution or an initial load: add a margin
408 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
409 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
412 return averageDownloadSpeed > threshold
415 // If the download speed is too bad, return the lowest resolution we have
416 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
418 return videoFileMaxByResolution(filteredFiles)
421 private getAndSaveActualDownloadSpeed () {
422 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
423 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
424 if (lastDownloadSpeeds.length === 0) return -1
426 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
427 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
429 // Save the average bandwidth for future use
430 saveAverageBandwidth(averageBandwidth)
432 return averageBandwidth
435 private initializePlayer () {
436 this.buildQualities()
439 this.player.posterImage.hide()
441 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
445 const oldPlay = this.player.play.bind(this.player);
446 (this.player as any).play = () => {
447 this.player.addClass('vjs-has-big-play-button-clicked')
448 this.player.play = oldPlay
450 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
454 private runAutoQualityScheduler () {
455 this.autoQualityInterval = setInterval(() => {
457 // Not initialized or in HTTP fallback
458 if (this.torrent === undefined || this.torrent === null) return
459 if (this.autoResolution === false) return
460 if (this.isAutoResolutionObservation === true) return
462 const file = this.getAppropriateFile()
463 let changeResolution = false
464 let changeResolutionDelay = 0
467 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
468 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
469 changeResolution = true
470 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
471 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
472 changeResolution = true
473 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
476 if (changeResolution === true) {
477 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
479 // Wait some seconds in observation of our new resolution
480 this.isAutoResolutionObservation = true
482 this.qualityObservationTimer = setTimeout(() => {
483 this.isAutoResolutionObservation = false
484 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
486 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
489 private isPlayerWaiting () {
490 return this.player?.hasClass('vjs-waiting')
493 private runTorrentInfoScheduler () {
494 this.torrentInfoInterval = setInterval(() => {
495 // Not initialized yet
496 if (this.torrent === undefined) return
499 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
501 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
502 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
504 return this.player.trigger('p2pInfo', {
505 source: 'webtorrent',
513 downloadSpeed: this.torrent.downloadSpeed,
514 numPeers: this.torrent.numPeers,
515 uploadSpeed: this.torrent.uploadSpeed,
516 downloaded: this.torrent.downloaded,
517 uploaded: this.torrent.uploaded
519 bandwidthEstimate: this.webtorrent.downloadSpeed
520 } as PlayerNetworkInfo)
521 }, this.CONSTANTS.INFO_SCHEDULER)
524 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
525 const paused = this.player.paused()
527 this.disableAutoResolution()
529 this.flushVideoFile(this.currentVideoFile, true)
532 // Enable error display now this is our last fallback
533 this.player.one('error', () => this.enableErrorDisplay())
535 const httpUrl = this.currentVideoFile.fileUrl
536 this.player.src = this.savePlayerSrcFunction
537 this.player.src(httpUrl)
539 this.selectAppropriateResolution(true)
541 // We changed the source, so reinit captions
542 this.player.trigger('sourcechange')
544 return this.tryToPlay(err => {
545 if (err && done) return done(err)
547 if (options.seek) this.seek(options.seek)
548 if (options.forcePlay === false && paused === true) this.player.pause()
550 if (done) return done()
554 private handleError (err: Error | string) {
555 return this.player.trigger('customError', { err })
558 private enableErrorDisplay () {
559 this.player.addClass('vjs-error-display-enabled')
562 private disableErrorDisplay () {
563 this.player.removeClass('vjs-error-display-enabled')
566 private pickAverageVideoFile () {
567 if (this.videoFiles.length === 1) return this.videoFiles[0]
569 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
570 return files[Math.floor(files.length / 2)]
573 private stopTorrent (torrent: WebTorrent.Torrent) {
575 // Pause does not remove actual peers (in particular the webseed peer)
576 torrent.removePeer(torrent['ws'])
579 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
580 this.destroyingFakeRenderer = false
582 const fakeVideoElem = document.createElement('video')
583 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
584 this.fakeRenderer = renderer
586 // The renderer returns an error when we destroy it, so skip them
587 if (this.destroyingFakeRenderer === false && err) {
588 console.error('Cannot render new torrent in fake video element.', err)
591 // Load the future file at the correct time (in delay MS - 2 seconds)
592 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
596 private destroyFakeRenderer () {
597 if (this.fakeRenderer) {
598 this.destroyingFakeRenderer = true
600 if (this.fakeRenderer.destroy) {
602 this.fakeRenderer.destroy()
604 console.log('Cannot destroy correctly fake renderer.', err)
607 this.fakeRenderer = undefined
611 private buildQualities () {
612 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
613 id: file.resolution.id,
614 label: this.buildQualityLabel(file),
615 height: file.resolution.id,
617 selectCallback: () => this.changeQuality(file.resolution.id)
622 label: this.player.localize('Auto'),
624 selectCallback: () => this.changeQuality(-1)
627 this.player.peertubeResolutions().add(resolutions)
630 private buildQualityLabel (file: VideoFile) {
631 let label = file.resolution.label
633 if (file.fps && file.fps >= 50) {
640 private selectAppropriateResolution (byEngine: boolean) {
641 const resolution = this.autoResolution
643 : this.getCurrentResolutionId()
645 const autoResolutionChosen = this.autoResolution
646 ? this.getCurrentResolutionId()
649 this.player.peertubeResolutions().select({ id: resolution, autoResolutionChosenId: autoResolutionChosen, byEngine })
653 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
654 export { WebTorrentPlugin }