1 import videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { renderVideo } from './video-renderer'
4 import { LoadedQualityData, PlayerNetworkInfo, WebtorrentPluginOptions } from '../peertube-videojs-typings'
5 import { getRtcConfig, timeToInt, videoFileMaxByResolution, videoFileMinByResolution, isIOS, isSafari } from '../utils'
6 import { PeertubeChunkStore } from './peertube-chunk-store'
8 getAverageBandwidthInStore,
13 } from '../peertube-player-local-storage'
14 import { VideoFile } from '@shared/models'
16 const CacheChunkStore = require('cache-chunk-store')
24 const Plugin = videojs.getPlugin('plugin')
26 class WebTorrentPlugin extends Plugin {
27 readonly videoFiles: VideoFile[]
29 private readonly playerElement: HTMLVideoElement
31 private readonly autoplay: boolean = false
32 private readonly startTime: number = 0
33 private readonly savePlayerSrcFunction: videojs.Player['src']
34 private readonly videoDuration: number
35 private readonly CONSTANTS = {
36 INFO_SCHEDULER: 1000, // Don't change this
37 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
38 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
39 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
40 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
41 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
44 private readonly webtorrent = new WebTorrent({
46 rtcConfig: getRtcConfig()
51 private currentVideoFile: VideoFile
52 private torrent: WebTorrent.Torrent
55 private fakeRenderer: any
56 private destroyingFakeRenderer = false
58 private autoResolution = true
59 private autoResolutionPossible = true
60 private isAutoResolutionObservation = false
61 private playerRefusedP2P = false
63 private torrentInfoInterval: any
64 private autoQualityInterval: any
65 private addTorrentDelay: any
66 private qualityObservationTimer: any
67 private runAutoQualitySchedulerTimer: any
69 private downloadSpeeds: number[] = []
71 constructor (player: videojs.Player, options?: WebtorrentPluginOptions) {
74 this.startTime = timeToInt(options.startTime)
76 // Disable auto play on iOS
77 this.autoplay = options.autoplay
78 this.playerRefusedP2P = !getStoredP2PEnabled()
80 this.videoFiles = options.videoFiles
81 this.videoDuration = options.videoDuration
83 this.savePlayerSrcFunction = this.player.src
84 this.playerElement = options.playerElement
86 this.player.ready(() => {
87 const playerOptions = this.player.options_
89 const volume = getStoredVolume()
90 if (volume !== undefined) this.player.volume(volume)
92 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
93 if (muted !== undefined) this.player.muted(muted)
95 this.player.duration(options.videoDuration)
97 this.initializePlayer()
98 this.runTorrentInfoScheduler()
100 this.player.one('play', () => {
101 // Don't run immediately scheduler, wait some seconds the TCP connections are made
102 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
108 clearTimeout(this.addTorrentDelay)
109 clearTimeout(this.qualityObservationTimer)
110 clearTimeout(this.runAutoQualitySchedulerTimer)
112 clearInterval(this.torrentInfoInterval)
113 clearInterval(this.autoQualityInterval)
115 // Don't need to destroy renderer, video player will be destroyed
116 this.flushVideoFile(this.currentVideoFile, false)
118 this.destroyFakeRenderer()
121 getCurrentResolutionId () {
122 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
126 videoFile?: VideoFile,
132 done: () => void = () => { /* empty */ }
134 // Automatically choose the adapted video file
136 const savedAverageBandwidth = getAverageBandwidthInStore()
137 videoFile = savedAverageBandwidth
138 ? this.getAppropriateFile(savedAverageBandwidth)
139 : this.pickAverageVideoFile()
143 throw Error(`Can't update video file since videoFile is undefined.`)
146 // Don't add the same video file once again
147 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
151 // Do not display error to user because we will have multiple fallback
152 this.disableErrorDisplay();
154 // Hack to "simulate" src link in video.js >= 6
155 // Without this, we can't play the video after pausing it
156 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
157 (this.player as any).src = () => true
158 const oldPlaybackRate = this.player.playbackRate()
160 const previousVideoFile = this.currentVideoFile
161 this.currentVideoFile = videoFile
163 // Don't try on iOS that does not support MediaSource
164 // Or don't use P2P if webtorrent is disabled
165 if (isIOS() || this.playerRefusedP2P) {
166 return this.fallbackToHttp(options, () => {
167 this.player.playbackRate(oldPlaybackRate)
172 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
173 this.player.playbackRate(oldPlaybackRate)
178 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.currentVideoFile.resolution.id })
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 enableAutoResolution () {
222 this.autoResolution = true
223 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
226 disableAutoResolution (forbid = false) {
227 if (forbid === true) this.autoResolutionPossible = false
229 this.autoResolution = false
230 this.trigger('autoResolutionChange', { possible: this.autoResolutionPossible })
231 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
234 isAutoResolutionPossible () {
235 return this.autoResolutionPossible
242 getCurrentVideoFile () {
243 return this.currentVideoFile
247 magnetOrTorrentUrl: string,
248 previousVideoFile: VideoFile,
249 options: PlayOptions,
252 console.log('Adding ' + magnetOrTorrentUrl + '.')
254 const oldTorrent = this.torrent
255 const torrentOptions = {
256 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
257 store: function (chunkLength: number, storeOpts: any) {
258 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
264 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
265 console.log('Added ' + magnetOrTorrentUrl + '.')
268 // Pause the old torrent
269 this.stopTorrent(oldTorrent)
271 // We use a fake renderer so we download correct pieces of the next file
272 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
275 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
276 this.addTorrentDelay = setTimeout(() => {
277 // We don't need the fake renderer anymore
278 this.destroyFakeRenderer()
280 const paused = this.player.paused()
282 this.flushVideoFile(previousVideoFile)
284 // Update progress bar (just for the UI), do not wait rendering
285 if (options.seek) this.player.currentTime(options.seek)
287 const renderVideoOptions = { autoplay: false, controls: true }
288 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
289 this.renderer = renderer
291 if (err) return this.fallbackToHttp(options, done)
293 return this.tryToPlay(err => {
294 if (err) return done(err)
296 if (options.seek) this.seek(options.seek)
297 if (options.forcePlay === false && paused === true) this.player.pause()
302 }, options.delay || 0)
305 this.torrent.on('error', (err: any) => console.error(err))
307 this.torrent.on('warning', (err: any) => {
308 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
309 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
311 // Users don't care about issues with WebRTC, but developers do so log it in the console
312 if (err.message.indexOf('Ice connection failed') !== -1) {
317 // Magnet hash is not up to date with the torrent file, add directly the torrent file
318 if (err.message.indexOf('incorrect info hash') !== -1) {
319 console.error('Incorrect info hash detected, falling back to torrent file.')
320 const newOptions = { forcePlay: true, seek: options.seek }
321 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
324 // Remote instance is down
325 if (err.message.indexOf('from xs param') !== -1) {
326 this.handleError(err)
333 private tryToPlay (done?: (err?: Error) => void) {
334 if (!done) done = function () { /* empty */ }
336 const playPromise = this.player.play()
337 if (playPromise !== undefined) {
338 return playPromise.then(() => done())
339 .catch((err: Error) => {
340 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
346 this.player.posterImage.show()
347 this.player.removeClass('vjs-has-autoplay')
348 this.player.removeClass('vjs-has-big-play-button-clicked')
349 this.player.removeClass('vjs-playing-audio-only-content')
358 private seek (time: number) {
359 this.player.currentTime(time)
360 this.player.handleTechSeeked_()
363 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
364 if (this.videoFiles === undefined) return undefined
366 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
368 if (files.length === 0) return undefined
369 if (files.length === 1) return files[0]
371 // Don't change the torrent if the player ended
372 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
374 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
376 // Limit resolution according to player height
377 const playerHeight = this.playerElement.offsetHeight
379 // We take the first resolution just above the player height
380 // Example: player height is 530px, we want the 720p file instead of 480p
381 let maxResolution = files[0].resolution.id
382 for (let i = files.length - 1; i >= 0; i--) {
383 const resolutionId = files[i].resolution.id
384 if (resolutionId !== 0 && resolutionId >= playerHeight) {
385 maxResolution = resolutionId
390 // Filter videos we can play according to our screen resolution and bandwidth
391 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
393 const fileBitrate = (f.size / this.videoDuration)
394 let threshold = fileBitrate
396 // If this is for a higher resolution or an initial load: add a margin
397 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
398 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
401 return averageDownloadSpeed > threshold
404 // If the download speed is too bad, return the lowest resolution we have
405 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
407 return videoFileMaxByResolution(filteredFiles)
410 private getAndSaveActualDownloadSpeed () {
411 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
412 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
413 if (lastDownloadSpeeds.length === 0) return -1
415 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
416 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
418 // Save the average bandwidth for future use
419 saveAverageBandwidth(averageBandwidth)
421 return averageBandwidth
424 private initializePlayer () {
425 this.buildQualities()
428 this.player.posterImage.hide()
430 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
434 const oldPlay = this.player.play.bind(this.player);
435 (this.player as any).play = () => {
436 this.player.addClass('vjs-has-big-play-button-clicked')
437 this.player.play = oldPlay
439 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
443 private runAutoQualityScheduler () {
444 this.autoQualityInterval = setInterval(() => {
446 // Not initialized or in HTTP fallback
447 if (this.torrent === undefined || this.torrent === null) return
448 if (this.autoResolution === false) return
449 if (this.isAutoResolutionObservation === true) return
451 const file = this.getAppropriateFile()
452 let changeResolution = false
453 let changeResolutionDelay = 0
456 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
457 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
458 changeResolution = true
459 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
460 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
461 changeResolution = true
462 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
465 if (changeResolution === true) {
466 this.updateResolution(file.resolution.id, changeResolutionDelay)
468 // Wait some seconds in observation of our new resolution
469 this.isAutoResolutionObservation = true
471 this.qualityObservationTimer = setTimeout(() => {
472 this.isAutoResolutionObservation = false
473 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
475 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
478 private isPlayerWaiting () {
479 return this.player && this.player.hasClass('vjs-waiting')
482 private runTorrentInfoScheduler () {
483 this.torrentInfoInterval = setInterval(() => {
484 // Not initialized yet
485 if (this.torrent === undefined) return
488 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
490 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
491 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
493 return this.player.trigger('p2pInfo', {
494 source: 'webtorrent',
502 downloadSpeed: this.torrent.downloadSpeed,
503 numPeers: this.torrent.numPeers,
504 uploadSpeed: this.torrent.uploadSpeed,
505 downloaded: this.torrent.downloaded,
506 uploaded: this.torrent.uploaded
508 } as PlayerNetworkInfo)
509 }, this.CONSTANTS.INFO_SCHEDULER)
512 private fallbackToHttp (options: PlayOptions, done?: Function) {
513 const paused = this.player.paused()
515 this.disableAutoResolution(true)
517 this.flushVideoFile(this.currentVideoFile, true)
520 // Enable error display now this is our last fallback
521 this.player.one('error', () => this.enableErrorDisplay())
523 const httpUrl = this.currentVideoFile.fileUrl
524 this.player.src = this.savePlayerSrcFunction
525 this.player.src(httpUrl)
529 // We changed the source, so reinit captions
530 this.player.trigger('sourcechange')
532 return this.tryToPlay(err => {
533 if (err && done) return done(err)
535 if (options.seek) this.seek(options.seek)
536 if (options.forcePlay === false && paused === true) this.player.pause()
538 if (done) return done()
542 private handleError (err: Error | string) {
543 return this.player.trigger('customError', { err })
546 private enableErrorDisplay () {
547 this.player.addClass('vjs-error-display-enabled')
550 private disableErrorDisplay () {
551 this.player.removeClass('vjs-error-display-enabled')
554 private pickAverageVideoFile () {
555 if (this.videoFiles.length === 1) return this.videoFiles[0]
557 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
560 private stopTorrent (torrent: WebTorrent.Torrent) {
562 // Pause does not remove actual peers (in particular the webseed peer)
563 torrent.removePeer(torrent[ 'ws' ])
566 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
567 this.destroyingFakeRenderer = false
569 const fakeVideoElem = document.createElement('video')
570 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
571 this.fakeRenderer = renderer
573 // The renderer returns an error when we destroy it, so skip them
574 if (this.destroyingFakeRenderer === false && err) {
575 console.error('Cannot render new torrent in fake video element.', err)
578 // Load the future file at the correct time (in delay MS - 2 seconds)
579 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
583 private destroyFakeRenderer () {
584 if (this.fakeRenderer) {
585 this.destroyingFakeRenderer = true
587 if (this.fakeRenderer.destroy) {
589 this.fakeRenderer.destroy()
591 console.log('Cannot destroy correctly fake renderer.', err)
594 this.fakeRenderer = undefined
598 private buildQualities () {
599 const qualityLevelsPayload = []
601 for (const file of this.videoFiles) {
602 const representation = {
603 id: file.resolution.id,
604 label: this.buildQualityLabel(file),
605 height: file.resolution.id,
609 this.player.qualityLevels().addQualityLevel(representation)
611 qualityLevelsPayload.push({
612 id: representation.id,
613 label: representation.label,
618 const payload: LoadedQualityData = {
619 qualitySwitchCallback: (d: any) => this.qualitySwitchCallback(d),
621 video: qualityLevelsPayload
624 this.player.tech(true).trigger('loadedqualitydata', payload)
627 private buildQualityLabel (file: VideoFile) {
628 let label = file.resolution.label
630 if (file.fps && file.fps >= 50) {
637 private qualitySwitchCallback (id: number) {
639 if (this.autoResolutionPossible === true) this.enableAutoResolution()
643 this.disableAutoResolution()
644 this.updateResolution(id)
647 private changeQuality () {
648 const resolutionId = this.currentVideoFile.resolution.id
649 const qualityLevels = this.player.qualityLevels()
651 if (resolutionId === -1) {
652 qualityLevels.selectedIndex = -1
656 for (let i = 0; i < qualityLevels.length; i++) {
657 const q = qualityLevels[i]
658 if (q.height === resolutionId) qualityLevels.selectedIndex_ = i
663 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
664 export { WebTorrentPlugin }