1 import videojs, { VideoJsPlayer } from 'video.js'
3 import * as WebTorrent from 'webtorrent'
4 import { renderVideo } from './video-renderer'
5 import { LoadedQualityData, PlayerNetworkInfo, WebtorrentPluginOptions } from '../peertube-videojs-typings'
6 import { getRtcConfig, timeToInt, videoFileMaxByResolution, videoFileMinByResolution } from '../utils'
7 import { PeertubeChunkStore } from './peertube-chunk-store'
9 getAverageBandwidthInStore,
14 } from '../peertube-player-local-storage'
15 import { VideoFile } from '@shared/models'
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: VideoJsPlayer['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: VideoJsPlayer, options?: WebtorrentPluginOptions) {
75 this.startTime = timeToInt(options.startTime)
77 // Disable auto play on iOS
78 this.autoplay = options.autoplay && this.isIOS() === false
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
136 if (videoFile === undefined) {
137 const savedAverageBandwidth = getAverageBandwidthInStore()
138 videoFile = savedAverageBandwidth
139 ? this.getAppropriateFile(savedAverageBandwidth)
140 : this.pickAverageVideoFile()
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.disableErrorDisplay();
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 (this.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)
175 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.currentVideoFile.resolution.id })
178 updateResolution (resolutionId: number, delay = 0) {
179 // Remember player state
180 const currentTime = this.player.currentTime()
181 const isPaused = this.player.paused()
183 // Hide bigPlayButton
185 this.player.bigPlayButton.hide()
188 // Audio-only (resolutionId === 0) gets special treatment
189 if (resolutionId === 0) {
190 // Audio-only: show poster, do not auto-hide controls
191 this.player.addClass('vjs-playing-audio-only-content')
192 this.player.posterImage.show()
194 // Hide poster to have black background
195 this.player.removeClass('vjs-playing-audio-only-content')
196 this.player.posterImage.hide()
199 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
203 seek: currentTime + (delay / 1000)
206 this.updateVideoFile(newVideoFile, options)
209 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
210 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
211 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
213 this.webtorrent.remove(videoFile.magnetUri)
214 console.log('Removed ' + videoFile.magnetUri)
218 enableAutoResolution () {
219 this.autoResolution = true
220 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
223 disableAutoResolution (forbid = false) {
224 if (forbid === true) this.autoResolutionPossible = false
226 this.autoResolution = false
227 this.trigger('autoResolutionChange', { possible: this.autoResolutionPossible })
228 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
231 isAutoResolutionPossible () {
232 return this.autoResolutionPossible
239 getCurrentVideoFile () {
240 return this.currentVideoFile
244 magnetOrTorrentUrl: string,
245 previousVideoFile: VideoFile,
246 options: PlayOptions,
249 console.log('Adding ' + magnetOrTorrentUrl + '.')
251 const oldTorrent = this.torrent
252 const torrentOptions = {
253 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
254 store: function (chunkLength: number, storeOpts: any) {
255 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
261 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
262 console.log('Added ' + magnetOrTorrentUrl + '.')
265 // Pause the old torrent
266 this.stopTorrent(oldTorrent)
268 // We use a fake renderer so we download correct pieces of the next file
269 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
272 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
273 this.addTorrentDelay = setTimeout(() => {
274 // We don't need the fake renderer anymore
275 this.destroyFakeRenderer()
277 const paused = this.player.paused()
279 this.flushVideoFile(previousVideoFile)
281 // Update progress bar (just for the UI), do not wait rendering
282 if (options.seek) this.player.currentTime(options.seek)
284 const renderVideoOptions = { autoplay: false, controls: true }
285 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
286 this.renderer = renderer
288 if (err) return this.fallbackToHttp(options, done)
290 return this.tryToPlay(err => {
291 if (err) return done(err)
293 if (options.seek) this.seek(options.seek)
294 if (options.forcePlay === false && paused === true) this.player.pause()
299 }, options.delay || 0)
302 this.torrent.on('error', (err: any) => console.error(err))
304 this.torrent.on('warning', (err: any) => {
305 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
306 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
308 // Users don't care about issues with WebRTC, but developers do so log it in the console
309 if (err.message.indexOf('Ice connection failed') !== -1) {
314 // Magnet hash is not up to date with the torrent file, add directly the torrent file
315 if (err.message.indexOf('incorrect info hash') !== -1) {
316 console.error('Incorrect info hash detected, falling back to torrent file.')
317 const newOptions = { forcePlay: true, seek: options.seek }
318 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
321 // Remote instance is down
322 if (err.message.indexOf('from xs param') !== -1) {
323 this.handleError(err)
330 private tryToPlay (done?: (err?: Error) => void) {
331 if (!done) done = function () { /* empty */ }
333 const playPromise = this.player.play()
334 if (playPromise !== undefined) {
335 return playPromise.then(() => done())
336 .catch((err: Error) => {
337 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
343 this.player.posterImage.show()
344 this.player.removeClass('vjs-has-autoplay')
345 this.player.removeClass('vjs-has-big-play-button-clicked')
346 this.player.removeClass('vjs-playing-audio-only-content')
355 private seek (time: number) {
356 this.player.currentTime(time)
357 this.player.handleTechSeeked_()
360 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
361 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
362 if (this.videoFiles.length === 1) return this.videoFiles[0]
364 // Don't change the torrent is the play was ended
365 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
367 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
369 // Limit resolution according to player height
370 const playerHeight = this.playerElement.offsetHeight
372 // We take the first resolution just above the player height
373 // Example: player height is 530px, we want the 720p file instead of 480p
374 let maxResolution = this.videoFiles[0].resolution.id
375 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
376 const resolutionId = this.videoFiles[i].resolution.id
377 if (resolutionId >= playerHeight) {
378 maxResolution = resolutionId
383 // Filter videos we can play according to our screen resolution and bandwidth
384 const filteredFiles = this.videoFiles
385 .filter(f => f.resolution.id <= maxResolution)
387 const fileBitrate = (f.size / this.videoDuration)
388 let threshold = fileBitrate
390 // If this is for a higher resolution or an initial load: add a margin
391 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
392 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
395 return averageDownloadSpeed > threshold
398 // If the download speed is too bad, return the lowest resolution we have
399 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
401 return videoFileMaxByResolution(filteredFiles)
404 private getAndSaveActualDownloadSpeed () {
405 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
406 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
407 if (lastDownloadSpeeds.length === 0) return -1
409 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
410 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
412 // Save the average bandwidth for future use
413 saveAverageBandwidth(averageBandwidth)
415 return averageBandwidth
418 private initializePlayer () {
419 this.buildQualities()
421 if (this.autoplay === true) {
422 this.player.posterImage.hide()
424 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
428 const oldPlay = this.player.play.bind(this.player);
429 (this.player as any).play = () => {
430 this.player.addClass('vjs-has-big-play-button-clicked')
431 this.player.play = oldPlay
433 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
437 private runAutoQualityScheduler () {
438 this.autoQualityInterval = setInterval(() => {
440 // Not initialized or in HTTP fallback
441 if (this.torrent === undefined || this.torrent === null) return
442 if (this.autoResolution === false) return
443 if (this.isAutoResolutionObservation === true) return
445 const file = this.getAppropriateFile()
446 let changeResolution = false
447 let changeResolutionDelay = 0
450 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
451 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
452 changeResolution = true
453 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
454 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
455 changeResolution = true
456 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
459 if (changeResolution === true) {
460 this.updateResolution(file.resolution.id, changeResolutionDelay)
462 // Wait some seconds in observation of our new resolution
463 this.isAutoResolutionObservation = true
465 this.qualityObservationTimer = setTimeout(() => {
466 this.isAutoResolutionObservation = false
467 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
469 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
472 private isPlayerWaiting () {
473 return this.player && this.player.hasClass('vjs-waiting')
476 private runTorrentInfoScheduler () {
477 this.torrentInfoInterval = setInterval(() => {
478 // Not initialized yet
479 if (this.torrent === undefined) return
482 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
484 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
485 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
487 return this.player.trigger('p2pInfo', {
495 downloadSpeed: this.torrent.downloadSpeed,
496 numPeers: this.torrent.numPeers,
497 uploadSpeed: this.torrent.uploadSpeed,
498 downloaded: this.torrent.downloaded,
499 uploaded: this.torrent.uploaded
501 } as PlayerNetworkInfo)
502 }, this.CONSTANTS.INFO_SCHEDULER)
505 private fallbackToHttp (options: PlayOptions, done?: Function) {
506 const paused = this.player.paused()
508 this.disableAutoResolution(true)
510 this.flushVideoFile(this.currentVideoFile, true)
513 // Enable error display now this is our last fallback
514 this.player.one('error', () => this.enableErrorDisplay())
516 const httpUrl = this.currentVideoFile.fileUrl
517 this.player.src = this.savePlayerSrcFunction
518 this.player.src(httpUrl)
522 // We changed the source, so reinit captions
523 this.player.trigger('sourcechange')
525 return this.tryToPlay(err => {
526 if (err && done) return done(err)
528 if (options.seek) this.seek(options.seek)
529 if (options.forcePlay === false && paused === true) this.player.pause()
531 if (done) return done()
535 private handleError (err: Error | string) {
536 return this.player.trigger('customError', { err })
539 private enableErrorDisplay () {
540 this.player.addClass('vjs-error-display-enabled')
543 private disableErrorDisplay () {
544 this.player.removeClass('vjs-error-display-enabled')
548 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
551 private pickAverageVideoFile () {
552 if (this.videoFiles.length === 1) return this.videoFiles[0]
554 return this.videoFiles[Math.floor(this.videoFiles.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 qualityLevelsPayload = []
598 for (const file of this.videoFiles) {
599 const representation = {
600 id: file.resolution.id,
601 label: this.buildQualityLabel(file),
602 height: file.resolution.id,
606 this.player.qualityLevels().addQualityLevel(representation)
608 qualityLevelsPayload.push({
609 id: representation.id,
610 label: representation.label,
615 const payload: LoadedQualityData = {
616 qualitySwitchCallback: (d: any) => this.qualitySwitchCallback(d),
618 video: qualityLevelsPayload
621 this.player.tech(true).trigger('loadedqualitydata', payload)
624 private buildQualityLabel (file: VideoFile) {
625 let label = file.resolution.label
627 if (file.fps && file.fps >= 50) {
634 private qualitySwitchCallback (id: number) {
636 if (this.autoResolutionPossible === true) this.enableAutoResolution()
640 this.disableAutoResolution()
641 this.updateResolution(id)
644 private changeQuality () {
645 const resolutionId = this.currentVideoFile.resolution.id
646 const qualityLevels = this.player.qualityLevels()
648 if (resolutionId === -1) {
649 qualityLevels.selectedIndex = -1
653 for (let i = 0; i < qualityLevels.length; i++) {
654 const q = qualityLevels[i]
655 if (q.height === resolutionId) qualityLevels.selectedIndex_ = i
660 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
661 export { WebTorrentPlugin }