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 && isIOS() === false
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
135 if (videoFile === undefined) {
136 const savedAverageBandwidth = getAverageBandwidthInStore()
137 videoFile = savedAverageBandwidth
138 ? this.getAppropriateFile(savedAverageBandwidth)
139 : this.pickAverageVideoFile()
142 // Don't add the same video file once again
143 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
147 // Do not display error to user because we will have multiple fallback
148 this.disableErrorDisplay();
150 // Hack to "simulate" src link in video.js >= 6
151 // Without this, we can't play the video after pausing it
152 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
153 (this.player as any).src = () => true
154 const oldPlaybackRate = this.player.playbackRate()
156 const previousVideoFile = this.currentVideoFile
157 this.currentVideoFile = videoFile
159 // Don't try on iOS that does not support MediaSource
160 // Or don't use P2P if webtorrent is disabled
161 if (isIOS() || this.playerRefusedP2P) {
162 return this.fallbackToHttp(options, () => {
163 this.player.playbackRate(oldPlaybackRate)
168 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
169 this.player.playbackRate(oldPlaybackRate)
174 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.currentVideoFile.resolution.id })
177 updateResolution (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 enableAutoResolution () {
218 this.autoResolution = true
219 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
222 disableAutoResolution (forbid = false) {
223 if (forbid === true) this.autoResolutionPossible = false
225 this.autoResolution = false
226 this.trigger('autoResolutionChange', { possible: this.autoResolutionPossible })
227 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
230 isAutoResolutionPossible () {
231 return this.autoResolutionPossible
238 getCurrentVideoFile () {
239 return this.currentVideoFile
243 magnetOrTorrentUrl: string,
244 previousVideoFile: VideoFile,
245 options: PlayOptions,
248 console.log('Adding ' + magnetOrTorrentUrl + '.')
250 const oldTorrent = this.torrent
251 const torrentOptions = {
252 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
253 store: function (chunkLength: number, storeOpts: any) {
254 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
260 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
261 console.log('Added ' + magnetOrTorrentUrl + '.')
264 // Pause the old torrent
265 this.stopTorrent(oldTorrent)
267 // We use a fake renderer so we download correct pieces of the next file
268 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
271 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
272 this.addTorrentDelay = setTimeout(() => {
273 // We don't need the fake renderer anymore
274 this.destroyFakeRenderer()
276 const paused = this.player.paused()
278 this.flushVideoFile(previousVideoFile)
280 // Update progress bar (just for the UI), do not wait rendering
281 if (options.seek) this.player.currentTime(options.seek)
283 const renderVideoOptions = { autoplay: false, controls: true }
284 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
285 this.renderer = renderer
287 if (err) return this.fallbackToHttp(options, done)
289 return this.tryToPlay(err => {
290 if (err) return done(err)
292 if (options.seek) this.seek(options.seek)
293 if (options.forcePlay === false && paused === true) this.player.pause()
298 }, options.delay || 0)
301 this.torrent.on('error', (err: any) => console.error(err))
303 this.torrent.on('warning', (err: any) => {
304 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
305 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
307 // Users don't care about issues with WebRTC, but developers do so log it in the console
308 if (err.message.indexOf('Ice connection failed') !== -1) {
313 // Magnet hash is not up to date with the torrent file, add directly the torrent file
314 if (err.message.indexOf('incorrect info hash') !== -1) {
315 console.error('Incorrect info hash detected, falling back to torrent file.')
316 const newOptions = { forcePlay: true, seek: options.seek }
317 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
320 // Remote instance is down
321 if (err.message.indexOf('from xs param') !== -1) {
322 this.handleError(err)
329 private tryToPlay (done?: (err?: Error) => void) {
330 if (!done) done = function () { /* empty */ }
332 // Try in mute mode because we have issues with Safari
333 if (isSafari() && this.player.muted() === false) {
334 this.player.muted(true)
337 const playPromise = this.player.play()
338 if (playPromise !== undefined) {
339 return playPromise.then(() => done())
340 .catch((err: Error) => {
341 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
347 this.player.posterImage.show()
348 this.player.removeClass('vjs-has-autoplay')
349 this.player.removeClass('vjs-has-big-play-button-clicked')
350 this.player.removeClass('vjs-playing-audio-only-content')
359 private seek (time: number) {
360 this.player.currentTime(time)
361 this.player.handleTechSeeked_()
364 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
365 if (this.videoFiles === undefined) return undefined
367 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
369 if (files.length === 0) return undefined
370 if (files.length === 1) return files[0]
372 // Don't change the torrent is the play was ended
373 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
375 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
376 averageDownloadSpeed = 0
378 // Limit resolution according to player height
379 const playerHeight = this.playerElement.offsetHeight
381 // We take the first resolution just above the player height
382 // Example: player height is 530px, we want the 720p file instead of 480p
383 let maxResolution = files[0].resolution.id
384 for (let i = files.length - 1; i >= 0; i--) {
385 const resolutionId = files[i].resolution.id
386 if (resolutionId !== 0 && resolutionId >= playerHeight) {
387 maxResolution = resolutionId
392 // Filter videos we can play according to our screen resolution and bandwidth
393 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
395 const fileBitrate = (f.size / this.videoDuration)
396 let threshold = fileBitrate
398 // If this is for a higher resolution or an initial load: add a margin
399 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
400 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
403 return averageDownloadSpeed > threshold
406 // If the download speed is too bad, return the lowest resolution we have
407 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
409 return videoFileMaxByResolution(filteredFiles)
412 private getAndSaveActualDownloadSpeed () {
413 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
414 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
415 if (lastDownloadSpeeds.length === 0) return -1
417 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
418 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
420 // Save the average bandwidth for future use
421 saveAverageBandwidth(averageBandwidth)
423 return averageBandwidth
426 private initializePlayer () {
427 this.buildQualities()
430 this.player.posterImage.hide()
432 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
436 const oldPlay = this.player.play.bind(this.player);
437 (this.player as any).play = () => {
438 this.player.addClass('vjs-has-big-play-button-clicked')
439 this.player.play = oldPlay
441 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
445 private runAutoQualityScheduler () {
446 this.autoQualityInterval = setInterval(() => {
448 // Not initialized or in HTTP fallback
449 if (this.torrent === undefined || this.torrent === null) return
450 if (this.autoResolution === false) return
451 if (this.isAutoResolutionObservation === true) return
453 const file = this.getAppropriateFile()
454 let changeResolution = false
455 let changeResolutionDelay = 0
458 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
459 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
460 changeResolution = true
461 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
462 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
463 changeResolution = true
464 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
467 if (changeResolution === true) {
468 this.updateResolution(file.resolution.id, changeResolutionDelay)
470 // Wait some seconds in observation of our new resolution
471 this.isAutoResolutionObservation = true
473 this.qualityObservationTimer = setTimeout(() => {
474 this.isAutoResolutionObservation = false
475 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
477 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
480 private isPlayerWaiting () {
481 return this.player && this.player.hasClass('vjs-waiting')
484 private runTorrentInfoScheduler () {
485 this.torrentInfoInterval = setInterval(() => {
486 // Not initialized yet
487 if (this.torrent === undefined) return
490 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
492 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
493 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
495 return this.player.trigger('p2pInfo', {
503 downloadSpeed: this.torrent.downloadSpeed,
504 numPeers: this.torrent.numPeers,
505 uploadSpeed: this.torrent.uploadSpeed,
506 downloaded: this.torrent.downloaded,
507 uploaded: this.torrent.uploaded
509 } as PlayerNetworkInfo)
510 }, this.CONSTANTS.INFO_SCHEDULER)
513 private fallbackToHttp (options: PlayOptions, done?: Function) {
514 const paused = this.player.paused()
516 this.disableAutoResolution(true)
518 this.flushVideoFile(this.currentVideoFile, true)
521 // Enable error display now this is our last fallback
522 this.player.one('error', () => this.enableErrorDisplay())
524 const httpUrl = this.currentVideoFile.fileUrl
525 this.player.src = this.savePlayerSrcFunction
526 this.player.src(httpUrl)
530 // We changed the source, so reinit captions
531 this.player.trigger('sourcechange')
533 return this.tryToPlay(err => {
534 if (err && done) return done(err)
536 if (options.seek) this.seek(options.seek)
537 if (options.forcePlay === false && paused === true) this.player.pause()
539 if (done) return done()
543 private handleError (err: Error | string) {
544 return this.player.trigger('customError', { err })
547 private enableErrorDisplay () {
548 this.player.addClass('vjs-error-display-enabled')
551 private disableErrorDisplay () {
552 this.player.removeClass('vjs-error-display-enabled')
555 private pickAverageVideoFile () {
556 if (this.videoFiles.length === 1) return this.videoFiles[0]
558 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
561 private stopTorrent (torrent: WebTorrent.Torrent) {
563 // Pause does not remove actual peers (in particular the webseed peer)
564 torrent.removePeer(torrent[ 'ws' ])
567 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
568 this.destroyingFakeRenderer = false
570 const fakeVideoElem = document.createElement('video')
571 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
572 this.fakeRenderer = renderer
574 // The renderer returns an error when we destroy it, so skip them
575 if (this.destroyingFakeRenderer === false && err) {
576 console.error('Cannot render new torrent in fake video element.', err)
579 // Load the future file at the correct time (in delay MS - 2 seconds)
580 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
584 private destroyFakeRenderer () {
585 if (this.fakeRenderer) {
586 this.destroyingFakeRenderer = true
588 if (this.fakeRenderer.destroy) {
590 this.fakeRenderer.destroy()
592 console.log('Cannot destroy correctly fake renderer.', err)
595 this.fakeRenderer = undefined
599 private buildQualities () {
600 const qualityLevelsPayload = []
602 for (const file of this.videoFiles) {
603 const representation = {
604 id: file.resolution.id,
605 label: this.buildQualityLabel(file),
606 height: file.resolution.id,
610 this.player.qualityLevels().addQualityLevel(representation)
612 qualityLevelsPayload.push({
613 id: representation.id,
614 label: representation.label,
619 const payload: LoadedQualityData = {
620 qualitySwitchCallback: (d: any) => this.qualitySwitchCallback(d),
622 video: qualityLevelsPayload
625 this.player.tech(true).trigger('loadedqualitydata', payload)
628 private buildQualityLabel (file: VideoFile) {
629 let label = file.resolution.label
631 if (file.fps && file.fps >= 50) {
638 private qualitySwitchCallback (id: number) {
640 if (this.autoResolutionPossible === true) this.enableAutoResolution()
644 this.disableAutoResolution()
645 this.updateResolution(id)
648 private changeQuality () {
649 const resolutionId = this.currentVideoFile.resolution.id
650 const qualityLevels = this.player.qualityLevels()
652 if (resolutionId === -1) {
653 qualityLevels.selectedIndex = -1
657 for (let i = 0; i < qualityLevels.length; i++) {
658 const q = qualityLevels[i]
659 if (q.height === resolutionId) qualityLevels.selectedIndex_ = i
664 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
665 export { WebTorrentPlugin }