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 updateResolution (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
240 magnetOrTorrentUrl: string,
241 previousVideoFile: VideoFile,
242 options: PlayOptions,
243 done: (err?: Error) => void
245 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
247 console.log('Adding ' + magnetOrTorrentUrl + '.')
249 const oldTorrent = this.torrent
250 const torrentOptions = {
251 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
252 store: function (chunkLength: number, storeOpts: any) {
253 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
259 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
260 console.log('Added ' + magnetOrTorrentUrl + '.')
263 // Pause the old torrent
264 this.stopTorrent(oldTorrent)
266 // We use a fake renderer so we download correct pieces of the next file
267 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
270 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
271 this.addTorrentDelay = setTimeout(() => {
272 // We don't need the fake renderer anymore
273 this.destroyFakeRenderer()
275 const paused = this.player.paused()
277 this.flushVideoFile(previousVideoFile)
279 // Update progress bar (just for the UI), do not wait rendering
280 if (options.seek) this.player.currentTime(options.seek)
282 const renderVideoOptions = { autoplay: false, controls: true }
283 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
284 this.renderer = renderer
286 if (err) return this.fallbackToHttp(options, done)
288 return this.tryToPlay(err => {
289 if (err) return done(err)
291 if (options.seek) this.seek(options.seek)
292 if (options.forcePlay === false && paused === true) this.player.pause()
297 }, options.delay || 0)
300 this.torrent.on('error', (err: any) => console.error(err))
302 this.torrent.on('warning', (err: any) => {
303 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
304 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
306 // Users don't care about issues with WebRTC, but developers do so log it in the console
307 if (err.message.indexOf('Ice connection failed') !== -1) {
312 // Magnet hash is not up to date with the torrent file, add directly the torrent file
313 if (err.message.indexOf('incorrect info hash') !== -1) {
314 console.error('Incorrect info hash detected, falling back to torrent file.')
315 const newOptions = { forcePlay: true, seek: options.seek }
316 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
319 // Remote instance is down
320 if (err.message.indexOf('from xs param') !== -1) {
321 this.handleError(err)
328 private tryToPlay (done?: (err?: Error) => void) {
329 if (!done) done = function () { /* empty */ }
331 const playPromise = this.player.play()
332 if (playPromise !== undefined) {
333 return playPromise.then(() => done())
334 .catch((err: Error) => {
335 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
341 this.player.posterImage.show()
342 this.player.removeClass('vjs-has-autoplay')
343 this.player.removeClass('vjs-has-big-play-button-clicked')
344 this.player.removeClass('vjs-playing-audio-only-content')
353 private seek (time: number) {
354 this.player.currentTime(time)
355 this.player.handleTechSeeked_()
358 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
359 if (this.videoFiles === undefined) return undefined
361 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
363 if (files.length === 0) return undefined
364 if (files.length === 1) return files[0]
366 // Don't change the torrent if the player ended
367 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
369 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
371 // Limit resolution according to player height
372 const playerHeight = this.playerElement.offsetHeight
374 // We take the first resolution just above the player height
375 // Example: player height is 530px, we want the 720p file instead of 480p
376 let maxResolution = files[0].resolution.id
377 for (let i = files.length - 1; i >= 0; i--) {
378 const resolutionId = files[i].resolution.id
379 if (resolutionId !== 0 && resolutionId >= playerHeight) {
380 maxResolution = resolutionId
385 // Filter videos we can play according to our screen resolution and bandwidth
386 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
388 const fileBitrate = (f.size / this.videoDuration)
389 let threshold = fileBitrate
391 // If this is for a higher resolution or an initial load: add a margin
392 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
393 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
396 return averageDownloadSpeed > threshold
399 // If the download speed is too bad, return the lowest resolution we have
400 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
402 return videoFileMaxByResolution(filteredFiles)
405 private getAndSaveActualDownloadSpeed () {
406 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
407 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
408 if (lastDownloadSpeeds.length === 0) return -1
410 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
411 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
413 // Save the average bandwidth for future use
414 saveAverageBandwidth(averageBandwidth)
416 return averageBandwidth
419 private initializePlayer () {
420 this.buildQualities()
423 this.player.posterImage.hide()
425 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
429 const oldPlay = this.player.play.bind(this.player);
430 (this.player as any).play = () => {
431 this.player.addClass('vjs-has-big-play-button-clicked')
432 this.player.play = oldPlay
434 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
438 private runAutoQualityScheduler () {
439 this.autoQualityInterval = setInterval(() => {
441 // Not initialized or in HTTP fallback
442 if (this.torrent === undefined || this.torrent === null) return
443 if (this.autoResolution === false) return
444 if (this.isAutoResolutionObservation === true) return
446 const file = this.getAppropriateFile()
447 let changeResolution = false
448 let changeResolutionDelay = 0
451 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
452 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
453 changeResolution = true
454 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
455 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
456 changeResolution = true
457 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
460 if (changeResolution === true) {
461 this.updateResolution(file.resolution.id, changeResolutionDelay)
463 // Wait some seconds in observation of our new resolution
464 this.isAutoResolutionObservation = true
466 this.qualityObservationTimer = setTimeout(() => {
467 this.isAutoResolutionObservation = false
468 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
470 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
473 private isPlayerWaiting () {
474 return this.player?.hasClass('vjs-waiting')
477 private runTorrentInfoScheduler () {
478 this.torrentInfoInterval = setInterval(() => {
479 // Not initialized yet
480 if (this.torrent === undefined) return
483 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
485 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
486 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
488 return this.player.trigger('p2pInfo', {
489 source: 'webtorrent',
497 downloadSpeed: this.torrent.downloadSpeed,
498 numPeers: this.torrent.numPeers,
499 uploadSpeed: this.torrent.uploadSpeed,
500 downloaded: this.torrent.downloaded,
501 uploaded: this.torrent.uploaded
503 bandwidthEstimate: this.webtorrent.downloadSpeed
504 } as PlayerNetworkInfo)
505 }, this.CONSTANTS.INFO_SCHEDULER)
508 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
509 const paused = this.player.paused()
511 this.disableAutoResolution()
513 this.flushVideoFile(this.currentVideoFile, true)
516 // Enable error display now this is our last fallback
517 this.player.one('error', () => this.enableErrorDisplay())
519 const httpUrl = this.currentVideoFile.fileUrl
520 this.player.src = this.savePlayerSrcFunction
521 this.player.src(httpUrl)
523 this.selectAppropriateResolution(true)
525 // We changed the source, so reinit captions
526 this.player.trigger('sourcechange')
528 return this.tryToPlay(err => {
529 if (err && done) return done(err)
531 if (options.seek) this.seek(options.seek)
532 if (options.forcePlay === false && paused === true) this.player.pause()
534 if (done) return done()
538 private handleError (err: Error | string) {
539 return this.player.trigger('customError', { err })
542 private enableErrorDisplay () {
543 this.player.addClass('vjs-error-display-enabled')
546 private disableErrorDisplay () {
547 this.player.removeClass('vjs-error-display-enabled')
550 private pickAverageVideoFile () {
551 if (this.videoFiles.length === 1) return this.videoFiles[0]
553 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
554 return files[Math.floor(files.length / 2)]
557 private stopTorrent (torrent: WebTorrent.Torrent) {
559 // Pause does not remove actual peers (in particular the webseed peer)
560 torrent.removePeer(torrent['ws'])
563 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
564 this.destroyingFakeRenderer = false
566 const fakeVideoElem = document.createElement('video')
567 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
568 this.fakeRenderer = renderer
570 // The renderer returns an error when we destroy it, so skip them
571 if (this.destroyingFakeRenderer === false && err) {
572 console.error('Cannot render new torrent in fake video element.', err)
575 // Load the future file at the correct time (in delay MS - 2 seconds)
576 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
580 private destroyFakeRenderer () {
581 if (this.fakeRenderer) {
582 this.destroyingFakeRenderer = true
584 if (this.fakeRenderer.destroy) {
586 this.fakeRenderer.destroy()
588 console.log('Cannot destroy correctly fake renderer.', err)
591 this.fakeRenderer = undefined
595 private buildQualities () {
596 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
597 id: file.resolution.id,
598 label: this.buildQualityLabel(file),
599 height: file.resolution.id,
601 selectCallback: () => this.qualitySwitchCallback(file.resolution.id)
606 label: this.player.localize('Auto'),
608 selectCallback: () => this.qualitySwitchCallback(-1)
611 this.player.peertubeResolutions().add(resolutions)
614 private buildQualityLabel (file: VideoFile) {
615 let label = file.resolution.label
617 if (file.fps && file.fps >= 50) {
624 private qualitySwitchCallback (id: number) {
626 if (this.autoResolutionPossible === true) {
627 this.autoResolution = true
629 this.selectAppropriateResolution(false)
635 this.autoResolution = false
636 this.updateResolution(id)
637 this.selectAppropriateResolution(false)
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 }