1 import videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { isIOS } from '@root-helpers/web-browser'
4 import { timeToInt } from '@shared/core-utils'
5 import { VideoFile } from '@shared/models'
6 import { getAverageBandwidthInStore, getStoredMute, getStoredVolume, saveAverageBandwidth } from '../../peertube-player-local-storage'
7 import { PeerTubeResolution, PlayerNetworkInfo, WebtorrentPluginOptions } from '../../types'
8 import { getRtcConfig, videoFileMaxByResolution, videoFileMinByResolution } from '../common'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
10 import { renderVideo } from './video-renderer'
12 const CacheChunkStore = require('cache-chunk-store')
20 const Plugin = videojs.getPlugin('plugin')
22 class WebTorrentPlugin extends Plugin {
23 readonly videoFiles: VideoFile[]
25 private readonly playerElement: HTMLVideoElement
27 private readonly autoplay: boolean = false
28 private readonly startTime: number = 0
29 private readonly savePlayerSrcFunction: videojs.Player['src']
30 private readonly videoDuration: number
31 private readonly CONSTANTS = {
32 INFO_SCHEDULER: 1000, // Don't change this
33 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
34 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
35 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
36 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
37 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
40 private readonly webtorrent = new WebTorrent({
42 rtcConfig: getRtcConfig()
47 private currentVideoFile: VideoFile
48 private torrent: WebTorrent.Torrent
51 private fakeRenderer: any
52 private destroyingFakeRenderer = false
54 private autoResolution = true
55 private autoResolutionPossible = true
56 private isAutoResolutionObservation = false
57 private playerRefusedP2P = false
59 private torrentInfoInterval: any
60 private autoQualityInterval: any
61 private addTorrentDelay: any
62 private qualityObservationTimer: any
63 private runAutoQualitySchedulerTimer: any
65 private downloadSpeeds: number[] = []
67 constructor (player: videojs.Player, options?: WebtorrentPluginOptions) {
70 this.startTime = timeToInt(options.startTime)
72 // Custom autoplay handled by webtorrent because we lazy play the video
73 this.autoplay = options.autoplay
75 this.playerRefusedP2P = options.playerRefusedP2P
77 this.videoFiles = options.videoFiles
78 this.videoDuration = options.videoDuration
80 this.savePlayerSrcFunction = this.player.src
81 this.playerElement = options.playerElement
83 this.player.ready(() => {
84 const playerOptions = this.player.options_
86 const volume = getStoredVolume()
87 if (volume !== undefined) this.player.volume(volume)
89 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
90 if (muted !== undefined) this.player.muted(muted)
92 this.player.duration(options.videoDuration)
94 this.initializePlayer()
95 this.runTorrentInfoScheduler()
97 this.player.one('play', () => {
98 // Don't run immediately scheduler, wait some seconds the TCP connections are made
99 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
105 clearTimeout(this.addTorrentDelay)
106 clearTimeout(this.qualityObservationTimer)
107 clearTimeout(this.runAutoQualitySchedulerTimer)
109 clearInterval(this.torrentInfoInterval)
110 clearInterval(this.autoQualityInterval)
112 // Don't need to destroy renderer, video player will be destroyed
113 this.flushVideoFile(this.currentVideoFile, false)
115 this.destroyFakeRenderer()
118 getCurrentResolutionId () {
119 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
123 videoFile?: VideoFile,
129 done: () => void = () => { /* empty */ }
131 // Automatically choose the adapted video file
133 const savedAverageBandwidth = getAverageBandwidthInStore()
134 videoFile = savedAverageBandwidth
135 ? this.getAppropriateFile(savedAverageBandwidth)
136 : this.pickAverageVideoFile()
140 throw Error(`Can't update video file since videoFile is undefined.`)
143 // Don't add the same video file once again
144 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
148 // Do not display error to user because we will have multiple fallback
149 this.player.peertube().hideFatalError();
151 // Hack to "simulate" src link in video.js >= 6
152 // Without this, we can't play the video after pausing it
153 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
154 (this.player as any).src = () => true
155 const oldPlaybackRate = this.player.playbackRate()
157 const previousVideoFile = this.currentVideoFile
158 this.currentVideoFile = videoFile
160 // Don't try on iOS that does not support MediaSource
161 // Or don't use P2P if webtorrent is disabled
162 if (isIOS() || this.playerRefusedP2P) {
163 return this.fallbackToHttp(options, () => {
164 this.player.playbackRate(oldPlaybackRate)
169 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
170 this.player.playbackRate(oldPlaybackRate)
174 this.selectAppropriateResolution(true)
177 updateEngineResolution (resolutionId: number, delay = 0) {
178 // Remember player state
179 const currentTime = this.player.currentTime()
180 const isPaused = this.player.paused()
182 // Hide bigPlayButton
184 this.player.bigPlayButton.hide()
187 // Audio-only (resolutionId === 0) gets special treatment
188 if (resolutionId === 0) {
189 // Audio-only: show poster, do not auto-hide controls
190 this.player.addClass('vjs-playing-audio-only-content')
191 this.player.posterImage.show()
193 // Hide poster to have black background
194 this.player.removeClass('vjs-playing-audio-only-content')
195 this.player.posterImage.hide()
198 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
202 seek: currentTime + (delay / 1000)
205 this.updateVideoFile(newVideoFile, options)
208 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
209 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
210 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
212 this.webtorrent.remove(videoFile.magnetUri)
213 console.log('Removed ' + videoFile.magnetUri)
217 disableAutoResolution () {
218 this.autoResolution = false
219 this.autoResolutionPossible = false
220 this.player.peertubeResolutions().disableAutoResolution()
223 isAutoResolutionPossible () {
224 return this.autoResolutionPossible
231 getCurrentVideoFile () {
232 return this.currentVideoFile
235 changeQuality (id: number) {
237 if (this.autoResolutionPossible === true) {
238 this.autoResolution = true
240 this.selectAppropriateResolution(false)
246 this.autoResolution = false
247 this.updateEngineResolution(id)
248 this.selectAppropriateResolution(false)
252 magnetOrTorrentUrl: string,
253 previousVideoFile: VideoFile,
254 options: PlayOptions,
255 done: (err?: Error) => void
257 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
259 console.log('Adding ' + magnetOrTorrentUrl + '.')
261 const oldTorrent = this.torrent
262 const torrentOptions = {
263 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
264 store: function (chunkLength: number, storeOpts: any) {
265 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
271 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
272 console.log('Added ' + magnetOrTorrentUrl + '.')
275 // Pause the old torrent
276 this.stopTorrent(oldTorrent)
278 // We use a fake renderer so we download correct pieces of the next file
279 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
282 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
283 this.addTorrentDelay = setTimeout(() => {
284 // We don't need the fake renderer anymore
285 this.destroyFakeRenderer()
287 const paused = this.player.paused()
289 this.flushVideoFile(previousVideoFile)
291 // Update progress bar (just for the UI), do not wait rendering
292 if (options.seek) this.player.currentTime(options.seek)
294 const renderVideoOptions = { autoplay: false, controls: true }
295 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
296 this.renderer = renderer
298 if (err) return this.fallbackToHttp(options, done)
300 return this.tryToPlay(err => {
301 if (err) return done(err)
303 if (options.seek) this.seek(options.seek)
304 if (options.forcePlay === false && paused === true) this.player.pause()
309 }, options.delay || 0)
312 this.torrent.on('error', (err: any) => console.error(err))
314 this.torrent.on('warning', (err: any) => {
315 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
316 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
318 // Users don't care about issues with WebRTC, but developers do so log it in the console
319 if (err.message.indexOf('Ice connection failed') !== -1) {
324 // Magnet hash is not up to date with the torrent file, add directly the torrent file
325 if (err.message.indexOf('incorrect info hash') !== -1) {
326 console.error('Incorrect info hash detected, falling back to torrent file.')
327 const newOptions = { forcePlay: true, seek: options.seek }
328 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
331 // Remote instance is down
332 if (err.message.indexOf('from xs param') !== -1) {
333 this.handleError(err)
340 private tryToPlay (done?: (err?: Error) => void) {
341 if (!done) done = function () { /* empty */ }
343 const playPromise = this.player.play()
344 if (playPromise !== undefined) {
345 return playPromise.then(() => done())
346 .catch((err: Error) => {
347 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
353 this.player.posterImage.show()
354 this.player.removeClass('vjs-has-autoplay')
355 this.player.removeClass('vjs-has-big-play-button-clicked')
356 this.player.removeClass('vjs-playing-audio-only-content')
365 private seek (time: number) {
366 this.player.currentTime(time)
367 this.player.handleTechSeeked_()
370 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
371 if (this.videoFiles === undefined) return undefined
372 if (this.videoFiles.length === 1) return this.videoFiles[0]
374 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
375 if (files.length === 0) return undefined
377 // Don't change the torrent if the player ended
378 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
380 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
382 // Limit resolution according to player height
383 const playerHeight = this.playerElement.offsetHeight
385 // We take the first resolution just above the player height
386 // Example: player height is 530px, we want the 720p file instead of 480p
387 let maxResolution = files[0].resolution.id
388 for (let i = files.length - 1; i >= 0; i--) {
389 const resolutionId = files[i].resolution.id
390 if (resolutionId !== 0 && resolutionId >= playerHeight) {
391 maxResolution = resolutionId
396 // Filter videos we can play according to our screen resolution and bandwidth
397 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
399 const fileBitrate = (f.size / this.videoDuration)
400 let threshold = fileBitrate
402 // If this is for a higher resolution or an initial load: add a margin
403 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
404 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
407 return averageDownloadSpeed > threshold
410 // If the download speed is too bad, return the lowest resolution we have
411 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
413 return videoFileMaxByResolution(filteredFiles)
416 private getAndSaveActualDownloadSpeed () {
417 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
418 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
419 if (lastDownloadSpeeds.length === 0) return -1
421 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
422 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
424 // Save the average bandwidth for future use
425 saveAverageBandwidth(averageBandwidth)
427 return averageBandwidth
430 private initializePlayer () {
431 this.buildQualities()
433 if (this.videoFiles.length === 0) {
434 this.player.addClass('disabled')
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.player.peertube().displayFatalError())
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 pickAverageVideoFile () {
559 if (this.videoFiles.length === 1) return this.videoFiles[0]
561 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
562 return files[Math.floor(files.length / 2)]
565 private stopTorrent (torrent: WebTorrent.Torrent) {
567 // Pause does not remove actual peers (in particular the webseed peer)
568 torrent.removePeer(torrent['ws'])
571 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
572 this.destroyingFakeRenderer = false
574 const fakeVideoElem = document.createElement('video')
575 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
576 this.fakeRenderer = renderer
578 // The renderer returns an error when we destroy it, so skip them
579 if (this.destroyingFakeRenderer === false && err) {
580 console.error('Cannot render new torrent in fake video element.', err)
583 // Load the future file at the correct time (in delay MS - 2 seconds)
584 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
588 private destroyFakeRenderer () {
589 if (this.fakeRenderer) {
590 this.destroyingFakeRenderer = true
592 if (this.fakeRenderer.destroy) {
594 this.fakeRenderer.destroy()
596 console.log('Cannot destroy correctly fake renderer.', err)
599 this.fakeRenderer = undefined
603 private buildQualities () {
604 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
605 id: file.resolution.id,
606 label: this.buildQualityLabel(file),
607 height: file.resolution.id,
609 selectCallback: () => this.changeQuality(file.resolution.id)
614 label: this.player.localize('Auto'),
616 selectCallback: () => this.changeQuality(-1)
619 this.player.peertubeResolutions().add(resolutions)
622 private buildQualityLabel (file: VideoFile) {
623 let label = file.resolution.label
625 if (file.fps && file.fps >= 50) {
632 private selectAppropriateResolution (byEngine: boolean) {
633 const resolution = this.autoResolution
635 : this.getCurrentResolutionId()
637 const autoResolutionChosen = this.autoResolution
638 ? this.getCurrentResolutionId()
641 this.player.peertubeResolutions().select({ id: resolution, autoResolutionChosenId: autoResolutionChosen, byEngine })
645 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
646 export { WebTorrentPlugin }