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 { addQueryParams, 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 buildWebSeedUrls: (file: VideoFile) => string[]
43 private readonly webtorrent = new WebTorrent({
45 rtcConfig: getRtcConfig()
50 private currentVideoFile: VideoFile
51 private torrent: WebTorrent.Torrent
54 private fakeRenderer: any
55 private destroyingFakeRenderer = false
57 private autoResolution = true
58 private autoResolutionPossible = true
59 private isAutoResolutionObservation = false
60 private playerRefusedP2P = false
62 private requiresAuth: boolean
63 private videoFileToken: () => string
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) {
76 this.startTime = timeToInt(options.startTime)
78 // Custom autoplay handled by webtorrent because we lazy play the video
79 this.autoplay = options.autoplay
81 this.playerRefusedP2P = options.playerRefusedP2P
83 this.videoFiles = options.videoFiles
84 this.videoDuration = options.videoDuration
86 this.savePlayerSrcFunction = this.player.src
87 this.playerElement = options.playerElement
89 this.requiresAuth = options.requiresAuth
90 this.videoFileToken = options.videoFileToken
92 this.buildWebSeedUrls = options.buildWebSeedUrls
94 this.player.ready(() => {
95 const playerOptions = this.player.options_
97 const volume = getStoredVolume()
98 if (volume !== undefined) this.player.volume(volume)
100 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
101 if (muted !== undefined) this.player.muted(muted)
103 this.player.duration(options.videoDuration)
105 this.initializePlayer()
106 this.runTorrentInfoScheduler()
108 this.player.one('play', () => {
109 // Don't run immediately scheduler, wait some seconds the TCP connections are made
110 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
116 clearTimeout(this.addTorrentDelay)
117 clearTimeout(this.qualityObservationTimer)
118 clearTimeout(this.runAutoQualitySchedulerTimer)
120 clearInterval(this.torrentInfoInterval)
121 clearInterval(this.autoQualityInterval)
123 // Don't need to destroy renderer, video player will be destroyed
124 this.flushVideoFile(this.currentVideoFile, false)
126 this.destroyFakeRenderer()
129 getCurrentResolutionId () {
130 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
134 videoFile?: VideoFile,
140 done: () => void = () => { /* empty */ }
142 // Automatically choose the adapted video file
144 const savedAverageBandwidth = getAverageBandwidthInStore()
145 videoFile = savedAverageBandwidth
146 ? this.getAppropriateFile(savedAverageBandwidth)
147 : this.pickAverageVideoFile()
151 throw Error(`Can't update video file since videoFile is undefined.`)
154 // Don't add the same video file once again
155 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
159 // Do not display error to user because we will have multiple fallback
160 this.player.peertube().hideFatalError();
162 // Hack to "simulate" src link in video.js >= 6
163 // Without this, we can't play the video after pausing it
164 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
165 (this.player as any).src = () => true
166 const oldPlaybackRate = this.player.playbackRate()
168 const previousVideoFile = this.currentVideoFile
169 this.currentVideoFile = videoFile
171 // Don't try on iOS that does not support MediaSource
172 // Or don't use P2P if webtorrent is disabled
173 if (isIOS() || this.playerRefusedP2P) {
174 return this.fallbackToHttp(options, () => {
175 this.player.playbackRate(oldPlaybackRate)
180 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
181 this.player.playbackRate(oldPlaybackRate)
185 this.selectAppropriateResolution(true)
188 updateEngineResolution (resolutionId: number, delay = 0) {
189 // Remember player state
190 const currentTime = this.player.currentTime()
191 const isPaused = this.player.paused()
193 // Hide bigPlayButton
195 this.player.bigPlayButton.hide()
198 // Audio-only (resolutionId === 0) gets special treatment
199 if (resolutionId === 0) {
200 // Audio-only: show poster, do not auto-hide controls
201 this.player.addClass('vjs-playing-audio-only-content')
202 this.player.posterImage.show()
204 // Hide poster to have black background
205 this.player.removeClass('vjs-playing-audio-only-content')
206 this.player.posterImage.hide()
209 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
213 seek: currentTime + (delay / 1000)
216 this.updateVideoFile(newVideoFile, options)
218 this.player.trigger('engineResolutionChange')
221 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
222 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
223 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
225 this.webtorrent.remove(videoFile.magnetUri)
226 logger.info(`Removed ${videoFile.magnetUri}`)
230 disableAutoResolution () {
231 this.autoResolution = false
232 this.autoResolutionPossible = false
233 this.player.peertubeResolutions().disableAutoResolution()
236 isAutoResolutionPossible () {
237 return this.autoResolutionPossible
244 getCurrentVideoFile () {
245 return this.currentVideoFile
248 changeQuality (id: number) {
250 if (this.autoResolutionPossible === true) {
251 this.autoResolution = true
253 this.selectAppropriateResolution(false)
259 this.autoResolution = false
260 this.updateEngineResolution(id)
261 this.selectAppropriateResolution(false)
265 magnetOrTorrentUrl: string,
266 previousVideoFile: VideoFile,
267 options: PlayOptions,
268 done: (err?: Error) => void
270 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
272 logger.info(`Adding ${magnetOrTorrentUrl}.`)
274 const oldTorrent = this.torrent
275 const torrentOptions = {
276 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
277 store: function (chunkLength: number, storeOpts: any) {
278 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
282 urlList: this.buildWebSeedUrls(this.currentVideoFile)
285 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
286 logger.info(`Added ${magnetOrTorrentUrl}.`)
289 // Pause the old torrent
290 this.stopTorrent(oldTorrent)
292 // We use a fake renderer so we download correct pieces of the next file
293 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
296 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
297 this.addTorrentDelay = setTimeout(() => {
298 // We don't need the fake renderer anymore
299 this.destroyFakeRenderer()
301 const paused = this.player.paused()
303 this.flushVideoFile(previousVideoFile)
305 // Update progress bar (just for the UI), do not wait rendering
306 if (options.seek) this.player.currentTime(options.seek)
308 const renderVideoOptions = { autoplay: false, controls: true }
309 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
310 this.renderer = renderer
312 if (err) return this.fallbackToHttp(options, done)
314 return this.tryToPlay(err => {
315 if (err) return done(err)
317 if (options.seek) this.seek(options.seek)
318 if (options.forcePlay === false && paused === true) this.player.pause()
323 }, options.delay || 0)
326 this.torrent.on('error', (err: any) => logger.error(err))
328 this.torrent.on('warning', (err: any) => {
329 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
330 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
332 // Users don't care about issues with WebRTC, but developers do so log it in the console
333 if (err.message.indexOf('Ice connection failed') !== -1) {
338 // Magnet hash is not up to date with the torrent file, add directly the torrent file
339 if (err.message.indexOf('incorrect info hash') !== -1) {
340 logger.error('Incorrect info hash detected, falling back to torrent file.')
341 const newOptions = { forcePlay: true, seek: options.seek }
342 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
345 // Remote instance is down
346 if (err.message.indexOf('from xs param') !== -1) {
347 this.handleError(err)
354 private tryToPlay (done?: (err?: Error) => void) {
355 if (!done) done = function () { /* empty */ }
357 const playPromise = this.player.play()
358 if (playPromise !== undefined) {
359 return playPromise.then(() => done())
360 .catch((err: Error) => {
361 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
367 this.player.posterImage.show()
368 this.player.removeClass('vjs-has-autoplay')
369 this.player.removeClass('vjs-has-big-play-button-clicked')
370 this.player.removeClass('vjs-playing-audio-only-content')
379 private seek (time: number) {
380 this.player.currentTime(time)
381 this.player.handleTechSeeked_()
384 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
385 if (this.videoFiles === undefined) return undefined
386 if (this.videoFiles.length === 1) return this.videoFiles[0]
388 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
389 if (files.length === 0) return undefined
391 // Don't change the torrent if the player ended
392 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
394 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
396 // Limit resolution according to player height
397 const playerHeight = this.playerElement.offsetHeight
399 // We take the first resolution just above the player height
400 // Example: player height is 530px, we want the 720p file instead of 480p
401 let maxResolution = files[0].resolution.id
402 for (let i = files.length - 1; i >= 0; i--) {
403 const resolutionId = files[i].resolution.id
404 if (resolutionId !== 0 && resolutionId >= playerHeight) {
405 maxResolution = resolutionId
410 // Filter videos we can play according to our screen resolution and bandwidth
411 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
413 const fileBitrate = (f.size / this.videoDuration)
414 let threshold = fileBitrate
416 // If this is for a higher resolution or an initial load: add a margin
417 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
418 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
421 return averageDownloadSpeed > threshold
424 // If the download speed is too bad, return the lowest resolution we have
425 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
427 return videoFileMaxByResolution(filteredFiles)
430 private getAndSaveActualDownloadSpeed () {
431 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
432 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
433 if (lastDownloadSpeeds.length === 0) return -1
435 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
436 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
438 // Save the average bandwidth for future use
439 saveAverageBandwidth(averageBandwidth)
441 return averageBandwidth
444 private initializePlayer () {
445 this.buildQualities()
447 if (this.videoFiles.length === 0) {
448 this.player.addClass('disabled')
453 this.player.posterImage.hide()
455 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
459 const oldPlay = this.player.play.bind(this.player);
460 (this.player as any).play = () => {
461 this.player.addClass('vjs-has-big-play-button-clicked')
462 this.player.play = oldPlay
464 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
468 private runAutoQualityScheduler () {
469 this.autoQualityInterval = setInterval(() => {
471 // Not initialized or in HTTP fallback
472 if (this.torrent === undefined || this.torrent === null) return
473 if (this.autoResolution === false) return
474 if (this.isAutoResolutionObservation === true) return
476 const file = this.getAppropriateFile()
477 let changeResolution = false
478 let changeResolutionDelay = 0
481 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
482 logger.info(`Downgrading automatically the resolution to: ${file.resolution.label}`)
483 changeResolution = true
484 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
485 logger.info(`Upgrading automatically the resolution to: ${file.resolution.label}`)
486 changeResolution = true
487 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
490 if (changeResolution === true) {
491 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
493 // Wait some seconds in observation of our new resolution
494 this.isAutoResolutionObservation = true
496 this.qualityObservationTimer = setTimeout(() => {
497 this.isAutoResolutionObservation = false
498 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
500 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
503 private isPlayerWaiting () {
504 return this.player?.hasClass('vjs-waiting')
507 private runTorrentInfoScheduler () {
508 this.torrentInfoInterval = setInterval(() => {
509 // Not initialized yet
510 if (this.torrent === undefined) return
513 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
515 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
516 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
518 return this.player.trigger('p2pInfo', {
519 source: 'webtorrent',
525 downloadSpeed: this.torrent.downloadSpeed,
526 numPeers: this.torrent.numPeers,
527 uploadSpeed: this.torrent.uploadSpeed,
528 downloaded: this.torrent.downloaded,
529 uploaded: this.torrent.uploaded
531 bandwidthEstimate: this.webtorrent.downloadSpeed
532 } as PlayerNetworkInfo)
533 }, this.CONSTANTS.INFO_SCHEDULER)
536 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
537 const paused = this.player.paused()
539 this.disableAutoResolution()
541 this.flushVideoFile(this.currentVideoFile, true)
544 // Enable error display now this is our last fallback
545 this.player.one('error', () => this.player.peertube().displayFatalError())
547 let httpUrl = this.currentVideoFile.fileUrl
549 if (this.requiresAuth && this.videoFileToken) {
550 httpUrl = addQueryParams(httpUrl, { videoFileToken: this.videoFileToken() })
553 this.player.src = this.savePlayerSrcFunction
554 this.player.src(httpUrl)
556 this.selectAppropriateResolution(true)
558 // We changed the source, so reinit captions
559 this.player.trigger('sourcechange')
561 return this.tryToPlay(err => {
562 if (err && done) return done(err)
564 if (options.seek) this.seek(options.seek)
565 if (options.forcePlay === false && paused === true) this.player.pause()
567 if (done) return done()
571 private handleError (err: Error | string) {
572 return this.player.trigger('customError', { err })
575 private pickAverageVideoFile () {
576 if (this.videoFiles.length === 1) return this.videoFiles[0]
578 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
579 return files[Math.floor(files.length / 2)]
582 private stopTorrent (torrent: WebTorrent.Torrent) {
584 // Pause does not remove actual peers (in particular the webseed peer)
585 torrent.removePeer(torrent['ws'])
588 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
589 this.destroyingFakeRenderer = false
591 const fakeVideoElem = document.createElement('video')
592 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
593 this.fakeRenderer = renderer
595 // The renderer returns an error when we destroy it, so skip them
596 if (this.destroyingFakeRenderer === false && err) {
597 logger.error('Cannot render new torrent in fake video element.', err)
600 // Load the future file at the correct time (in delay MS - 2 seconds)
601 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
605 private destroyFakeRenderer () {
606 if (this.fakeRenderer) {
607 this.destroyingFakeRenderer = true
609 if (this.fakeRenderer.destroy) {
611 this.fakeRenderer.destroy()
613 logger.info('Cannot destroy correctly fake renderer.', err)
616 this.fakeRenderer = undefined
620 private buildQualities () {
621 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
622 id: file.resolution.id,
623 label: this.buildQualityLabel(file),
624 height: file.resolution.id,
626 selectCallback: () => this.changeQuality(file.resolution.id)
631 label: this.player.localize('Auto'),
633 selectCallback: () => this.changeQuality(-1)
636 this.player.peertubeResolutions().add(resolutions)
639 private buildQualityLabel (file: VideoFile) {
640 let label = file.resolution.label
642 if (file.fps && file.fps >= 50) {
649 private selectAppropriateResolution (byEngine: boolean) {
650 const resolution = this.autoResolution
652 : this.getCurrentResolutionId()
654 const autoResolutionChosen = this.autoResolution
655 ? this.getCurrentResolutionId()
658 this.player.peertubeResolutions().select({ id: resolution, autoResolutionChosenId: autoResolutionChosen, byEngine })
662 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
663 export { WebTorrentPlugin }