]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/webtorrent/webtorrent-plugin.ts
Better display redundancy pies
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / webtorrent / webtorrent-plugin.ts
CommitLineData
512decf3 1import videojs from 'video.js'
aa8b6df4 2import * as WebTorrent from 'webtorrent'
15a7eafb
C
3import { timeToInt } from '@shared/core-utils'
4import { VideoFile } from '@shared/models'
a9bfa85d 5import { getAverageBandwidthInStore, getStoredMute, getStoredVolume, saveAverageBandwidth } from '../peertube-player-local-storage'
e367da94 6import { PeerTubeResolution, PlayerNetworkInfo, WebtorrentPluginOptions } from '../peertube-videojs-typings'
15a7eafb
C
7import { getRtcConfig, isIOS, videoFileMaxByResolution, videoFileMinByResolution } from '../utils'
8import { PeertubeChunkStore } from './peertube-chunk-store'
9import { renderVideo } from './video-renderer'
be6a4802 10
c199c427
C
11const CacheChunkStore = require('cache-chunk-store')
12
a73115f3 13type PlayOptions = {
9df52d66
C
14 forcePlay?: boolean
15 seek?: number
a73115f3
C
16 delay?: number
17}
18
f5fcd9f7
C
19const Plugin = videojs.getPlugin('plugin')
20
2adfc7ea 21class WebTorrentPlugin extends Plugin {
abb3097e
C
22 readonly videoFiles: VideoFile[]
23
c6352f2c 24 private readonly playerElement: HTMLVideoElement
a8462c8e 25
c6352f2c 26 private readonly autoplay: boolean = false
f37bad63 27 private readonly startTime: number = 0
7e37e111 28 private readonly savePlayerSrcFunction: videojs.Player['src']
a8462c8e
C
29 private readonly videoDuration: number
30 private readonly CONSTANTS = {
31 INFO_SCHEDULER: 1000, // Don't change this
32 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
33 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
7ee4a4af
C
34 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
35 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
2adfc7ea 36 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
a8462c8e
C
37 }
38
b7f1747d
C
39 private readonly webtorrent = new WebTorrent({
40 tracker: {
09209296 41 rtcConfig: getRtcConfig()
b7f1747d
C
42 },
43 dht: false
44 })
45
a22bfc3e 46 private currentVideoFile: VideoFile
c199c427 47 private torrent: WebTorrent.Torrent
287918da 48
244b4ae3
B
49 private renderer: any
50 private fakeRenderer: any
3b019808 51 private destroyingFakeRenderer = false
287918da 52
7ee4a4af 53 private autoResolution = true
2adfc7ea 54 private autoResolutionPossible = true
7ee4a4af 55 private isAutoResolutionObservation = false
64cc5e85 56 private playerRefusedP2P = false
7ee4a4af 57
244b4ae3
B
58 private torrentInfoInterval: any
59 private autoQualityInterval: any
244b4ae3
B
60 private addTorrentDelay: any
61 private qualityObservationTimer: any
62 private runAutoQualitySchedulerTimer: any
a8462c8e
C
63
64 private downloadSpeeds: number[] = []
a22bfc3e 65
8426a711 66 constructor (player: videojs.Player, options?: WebtorrentPluginOptions) {
f5fcd9f7 67 super(player)
a22bfc3e 68
f0a39880
C
69 this.startTime = timeToInt(options.startTime)
70
a9bfa85d 71 // Custom autoplay handled by webtorrent because we lazy play the video
9eccae74 72 this.autoplay = options.autoplay
a9bfa85d
C
73
74 this.playerRefusedP2P = options.playerRefusedP2P
481d3596 75
a22bfc3e 76 this.videoFiles = options.videoFiles
3bcfff7f 77 this.videoDuration = options.videoDuration
a22bfc3e 78
bf5685f0 79 this.savePlayerSrcFunction = this.player.src
a22bfc3e
C
80 this.playerElement = options.playerElement
81
82 this.player.ready(() => {
3b019808
C
83 const playerOptions = this.player.options_
84
c6352f2c
C
85 const volume = getStoredVolume()
86 if (volume !== undefined) this.player.volume(volume)
3b019808
C
87
88 const muted = playerOptions.muted !== undefined ? playerOptions.muted : getStoredMute()
c6352f2c
C
89 if (muted !== undefined) this.player.muted(muted)
90
fe05c3ac
C
91 this.player.duration(options.videoDuration)
92
0dcf9a14 93 this.initializePlayer()
a22bfc3e 94 this.runTorrentInfoScheduler()
6e46de09 95
a8462c8e 96 this.player.one('play', () => {
f37bad63 97 // Don't run immediately scheduler, wait some seconds the TCP connections are made
b335ccec 98 this.runAutoQualitySchedulerTimer = setTimeout(() => this.runAutoQualityScheduler(), this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
a8462c8e 99 })
a22bfc3e
C
100 })
101 }
102
103 dispose () {
7ee4a4af
C
104 clearTimeout(this.addTorrentDelay)
105 clearTimeout(this.qualityObservationTimer)
106 clearTimeout(this.runAutoQualitySchedulerTimer)
107
3bcfff7f 108 clearInterval(this.torrentInfoInterval)
a8462c8e 109 clearInterval(this.autoQualityInterval)
3bcfff7f 110
a22bfc3e
C
111 // Don't need to destroy renderer, video player will be destroyed
112 this.flushVideoFile(this.currentVideoFile, false)
054a103b
C
113
114 this.destroyFakeRenderer()
aa8b6df4
C
115 }
116
09700934
C
117 getCurrentResolutionId () {
118 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
aa8b6df4
C
119 }
120
8426a711 121 updateVideoFile (
a325db17 122 videoFile?: VideoFile,
3baf9be2 123 options: {
9df52d66
C
124 forcePlay?: boolean
125 seek?: number
3baf9be2
C
126 delay?: number
127 } = {},
128 done: () => void = () => { /* empty */ }
129 ) {
a325db17 130 // Automatically choose the adapted video file
6a882bc4 131 if (!videoFile) {
a325db17 132 const savedAverageBandwidth = getAverageBandwidthInStore()
133 videoFile = savedAverageBandwidth
134 ? this.getAppropriateFile(savedAverageBandwidth)
135 : this.pickAverageVideoFile()
136 }
137
6a882bc4 138 if (!videoFile) {
a5a69fc7 139 throw Error(`Can't update video file since videoFile is undefined.`)
140 }
141
aa8b6df4 142 // Don't add the same video file once again
a22bfc3e 143 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
aa8b6df4
C
144 return
145 }
146
c6352f2c 147 // Do not display error to user because we will have multiple fallback
c4207f97 148 this.player.peertube().hideFatalError();
1198a08c 149
b335ccec
C
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
f5fcd9f7 153 (this.player as any).src = () => true
c6352f2c 154 const oldPlaybackRate = this.player.playbackRate()
bf5685f0 155
a22bfc3e
C
156 const previousVideoFile = this.currentVideoFile
157 this.currentVideoFile = videoFile
aa8b6df4 158
a73115f3
C
159 // Don't try on iOS that does not support MediaSource
160 // Or don't use P2P if webtorrent is disabled
3e2bc4ea 161 if (isIOS() || this.playerRefusedP2P) {
a73115f3
C
162 return this.fallbackToHttp(options, () => {
163 this.player.playbackRate(oldPlaybackRate)
164 return done()
165 })
166 }
167
3baf9be2 168 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
c6352f2c
C
169 this.player.playbackRate(oldPlaybackRate)
170 return done()
171 })
a216c623 172
e367da94 173 this.selectAppropriateResolution(true)
a216c623
C
174 }
175
89ac282e 176 updateEngineResolution (resolutionId: number, delay = 0) {
b335ccec
C
177 // Remember player state
178 const currentTime = this.player.currentTime()
179 const isPaused = this.player.paused()
180
b335ccec
C
181 // Hide bigPlayButton
182 if (!isPaused) {
183 this.player.bigPlayButton.hide()
184 }
185
3a149e9f
C
186 // Audio-only (resolutionId === 0) gets special treatment
187 if (resolutionId === 0) {
5c7d6508 188 // Audio-only: show poster, do not auto-hide controls
189 this.player.addClass('vjs-playing-audio-only-content')
190 this.player.posterImage.show()
3a149e9f
C
191 } else {
192 // Hide poster to have black background
193 this.player.removeClass('vjs-playing-audio-only-content')
194 this.player.posterImage.hide()
5c7d6508 195 }
196
b335ccec
C
197 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
198 const options = {
199 forcePlay: false,
200 delay,
201 seek: currentTime + (delay / 1000)
202 }
5c7d6508 203
b335ccec
C
204 this.updateVideoFile(newVideoFile, options)
205 }
206
207 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
208 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
209 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
210
211 this.webtorrent.remove(videoFile.magnetUri)
212 console.log('Removed ' + videoFile.magnetUri)
213 }
214 }
215
e367da94 216 disableAutoResolution () {
b335ccec 217 this.autoResolution = false
e367da94
C
218 this.autoResolutionPossible = false
219 this.player.peertubeResolutions().disableAutoResolution()
b335ccec
C
220 }
221
6377a9f2
C
222 isAutoResolutionPossible () {
223 return this.autoResolutionPossible
224 }
225
b335ccec
C
226 getTorrent () {
227 return this.torrent
228 }
229
aedf50d1
C
230 getCurrentVideoFile () {
231 return this.currentVideoFile
232 }
233
89ac282e
C
234 changeQuality (id: number) {
235 if (id === -1) {
236 if (this.autoResolutionPossible === true) {
237 this.autoResolution = true
238
239 this.selectAppropriateResolution(false)
240 }
241
242 return
243 }
244
245 this.autoResolution = false
246 this.updateEngineResolution(id)
247 this.selectAppropriateResolution(false)
248 }
249
b335ccec 250 private addTorrent (
3baf9be2
C
251 magnetOrTorrentUrl: string,
252 previousVideoFile: VideoFile,
a73115f3 253 options: PlayOptions,
9df52d66 254 done: (err?: Error) => void
3baf9be2 255 ) {
d61893f7
C
256 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
257
a216c623
C
258 console.log('Adding ' + magnetOrTorrentUrl + '.')
259
a8462c8e 260 const oldTorrent = this.torrent
3baf9be2 261 const torrentOptions = {
85394ba2
C
262 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
263 store: function (chunkLength: number, storeOpts: any) {
264 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
265 max: 100
266 })
267 }
efda99c3
C
268 }
269
b7f1747d 270 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
a216c623 271 console.log('Added ' + magnetOrTorrentUrl + '.')
aa8b6df4 272
a8462c8e 273 if (oldTorrent) {
4a7591e1 274 // Pause the old torrent
b335ccec 275 this.stopTorrent(oldTorrent)
6d272f39
C
276
277 // We use a fake renderer so we download correct pieces of the next file
9df52d66 278 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
a8462c8e 279 }
aa8b6df4 280
e7eb5b39 281 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
7ee4a4af 282 this.addTorrentDelay = setTimeout(() => {
b335ccec 283 // We don't need the fake renderer anymore
054a103b 284 this.destroyFakeRenderer()
6d272f39 285
3baf9be2
C
286 const paused = this.player.paused()
287
a8462c8e 288 this.flushVideoFile(previousVideoFile)
0dcf9a14 289
fe05c3ac
C
290 // Update progress bar (just for the UI), do not wait rendering
291 if (options.seek) this.player.currentTime(options.seek)
292
3baf9be2 293 const renderVideoOptions = { autoplay: false, controls: true }
9df52d66 294 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
a8462c8e 295 this.renderer = renderer
aa8b6df4 296
a73115f3 297 if (err) return this.fallbackToHttp(options, done)
3bcfff7f 298
c199c427 299 return this.tryToPlay(err => {
3baf9be2 300 if (err) return done(err)
a8462c8e 301
3baf9be2
C
302 if (options.seek) this.seek(options.seek)
303 if (options.forcePlay === false && paused === true) this.player.pause()
8244e187 304
a73115f3 305 return done()
3baf9be2 306 })
a8462c8e 307 })
3baf9be2 308 }, options.delay || 0)
aa8b6df4
C
309 })
310
244b4ae3 311 this.torrent.on('error', (err: any) => console.error(err))
a216c623 312
a22bfc3e 313 this.torrent.on('warning', (err: any) => {
a96aed15 314 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
531ab5b6 315 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
a216c623 316
7dbdc3ba
C
317 // Users don't care about issues with WebRTC, but developers do so log it in the console
318 if (err.message.indexOf('Ice connection failed') !== -1) {
332e7032 319 console.log(err)
7dbdc3ba
C
320 return
321 }
a96aed15 322
a216c623
C
323 // Magnet hash is not up to date with the torrent file, add directly the torrent file
324 if (err.message.indexOf('incorrect info hash') !== -1) {
325 console.error('Incorrect info hash detected, falling back to torrent file.')
1f6824c9 326 const newOptions = { forcePlay: true, seek: options.seek }
9df52d66 327 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
a216c623
C
328 }
329
6d88de72 330 // Remote instance is down
0f7fedc3 331 if (err.message.indexOf('from xs param') !== -1) {
6d88de72
C
332 this.handleError(err)
333 }
334
335 console.warn(err)
a96aed15 336 })
aa8b6df4
C
337 }
338
c199c427 339 private tryToPlay (done?: (err?: Error) => void) {
80109b2d 340 if (!done) done = function () { /* empty */ }
1fad099d 341
80109b2d
C
342 const playPromise = this.player.play()
343 if (playPromise !== undefined) {
f5fcd9f7 344 return playPromise.then(() => done())
244b4ae3 345 .catch((err: Error) => {
9df52d66 346 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
70b40c2e
C
347 return
348 }
349
80109b2d
C
350 console.error(err)
351 this.player.pause()
352 this.player.posterImage.show()
353 this.player.removeClass('vjs-has-autoplay')
91d95589 354 this.player.removeClass('vjs-has-big-play-button-clicked')
5c7d6508 355 this.player.removeClass('vjs-playing-audio-only-content')
80109b2d
C
356
357 return done()
358 })
359 }
360
361 return done()
362 }
363
f37bad63
C
364 private seek (time: number) {
365 this.player.currentTime(time)
366 this.player.handleTechSeeked_()
367 }
368
a8462c8e 369 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
3cd56a29 370 if (this.videoFiles === undefined) return undefined
2b6af10e 371 if (this.videoFiles.length === 1) return this.videoFiles[0]
3cd56a29
C
372
373 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
3cd56a29 374 if (files.length === 0) return undefined
a8462c8e 375
aea53cc6 376 // Don't change the torrent if the player ended
3c40590d
C
377 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
378
379 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
a8462c8e 380
0b755f3b 381 // Limit resolution according to player height
c4710631 382 const playerHeight = this.playerElement.offsetHeight
0b755f3b
C
383
384 // We take the first resolution just above the player height
385 // Example: player height is 530px, we want the 720p file instead of 480p
3cd56a29
C
386 let maxResolution = files[0].resolution.id
387 for (let i = files.length - 1; i >= 0; i--) {
388 const resolutionId = files[i].resolution.id
389 if (resolutionId !== 0 && resolutionId >= playerHeight) {
0b755f3b
C
390 maxResolution = resolutionId
391 break
a8462c8e 392 }
0b755f3b 393 }
a8462c8e 394
0b755f3b 395 // Filter videos we can play according to our screen resolution and bandwidth
3cd56a29
C
396 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
397 .filter(f => {
398 const fileBitrate = (f.size / this.videoDuration)
399 let threshold = fileBitrate
0b755f3b 400
3cd56a29
C
401 // If this is for a higher resolution or an initial load: add a margin
402 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
403 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
404 }
0b755f3b 405
3cd56a29
C
406 return averageDownloadSpeed > threshold
407 })
a8462c8e
C
408
409 // If the download speed is too bad, return the lowest resolution we have
3cd56a29 410 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
a8462c8e 411
6cca7360 412 return videoFileMaxByResolution(filteredFiles)
a8462c8e
C
413 }
414
3c40590d 415 private getAndSaveActualDownloadSpeed () {
a8462c8e
C
416 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
417 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
418 if (lastDownloadSpeeds.length === 0) return -1
419
420 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
421 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
422
423 // Save the average bandwidth for future use
424 saveAverageBandwidth(averageBandwidth)
ed9f9f5f 425
a8462c8e 426 return averageBandwidth
ed9f9f5f
C
427 }
428
0dcf9a14 429 private initializePlayer () {
2adfc7ea 430 this.buildQualities()
c6352f2c 431
72efdda5 432 if (this.autoplay) {
33d78552 433 this.player.posterImage.hide()
e6f62797 434
a325db17 435 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
b335ccec 436 }
e7eb5b39 437
b335ccec 438 // Proxy first play
f5fcd9f7
C
439 const oldPlay = this.player.play.bind(this.player);
440 (this.player as any).play = () => {
b335ccec
C
441 this.player.addClass('vjs-has-big-play-button-clicked')
442 this.player.play = oldPlay
443
a325db17 444 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
aa8b6df4 445 }
a22bfc3e 446 }
aa8b6df4 447
a8462c8e
C
448 private runAutoQualityScheduler () {
449 this.autoQualityInterval = setInterval(() => {
7ee4a4af 450
877b0528
C
451 // Not initialized or in HTTP fallback
452 if (this.torrent === undefined || this.torrent === null) return
2adfc7ea 453 if (this.autoResolution === false) return
a8462c8e
C
454 if (this.isAutoResolutionObservation === true) return
455
456 const file = this.getAppropriateFile()
457 let changeResolution = false
458 let changeResolutionDelay = 0
459
460 // Lower resolution
461 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
462 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
463 changeResolution = true
7ee4a4af 464 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
a8462c8e
C
465 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
466 changeResolution = true
7ee4a4af 467 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
a8462c8e
C
468 }
469
470 if (changeResolution === true) {
89ac282e 471 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
a8462c8e
C
472
473 // Wait some seconds in observation of our new resolution
474 this.isAutoResolutionObservation = true
7ee4a4af
C
475
476 this.qualityObservationTimer = setTimeout(() => {
477 this.isAutoResolutionObservation = false
478 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
a8462c8e
C
479 }
480 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
481 }
482
483 private isPlayerWaiting () {
9df52d66 484 return this.player?.hasClass('vjs-waiting')
a8462c8e
C
485 }
486
a22bfc3e 487 private runTorrentInfoScheduler () {
3bcfff7f 488 this.torrentInfoInterval = setInterval(() => {
bf5685f0
C
489 // Not initialized yet
490 if (this.torrent === undefined) return
491
492 // Http fallback
2adfc7ea 493 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
bf5685f0 494
b7f1747d
C
495 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
496 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
a8462c8e 497
2adfc7ea 498 return this.player.trigger('p2pInfo', {
17152837 499 source: 'webtorrent',
09209296
C
500 http: {
501 downloadSpeed: 0,
502 uploadSpeed: 0,
503 downloaded: 0,
504 uploaded: 0
505 },
3b6f205c
C
506 p2p: {
507 downloadSpeed: this.torrent.downloadSpeed,
508 numPeers: this.torrent.numPeers,
509 uploadSpeed: this.torrent.uploadSpeed,
510 downloaded: this.torrent.downloaded,
511 uploaded: this.torrent.uploaded
4e11d8f3
C
512 },
513 bandwidthEstimate: this.webtorrent.downloadSpeed
3b6f205c 514 } as PlayerNetworkInfo)
a8462c8e 515 }, this.CONSTANTS.INFO_SCHEDULER)
a22bfc3e 516 }
aa8b6df4 517
9df52d66 518 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
a73115f3
C
519 const paused = this.player.paused()
520
e367da94 521 this.disableAutoResolution()
c4082b8b 522
bf5685f0
C
523 this.flushVideoFile(this.currentVideoFile, true)
524 this.torrent = null
525
526 // Enable error display now this is our last fallback
c4207f97 527 this.player.one('error', () => this.player.peertube().displayFatalError())
bf5685f0
C
528
529 const httpUrl = this.currentVideoFile.fileUrl
530 this.player.src = this.savePlayerSrcFunction
531 this.player.src(httpUrl)
c6352f2c 532
e367da94 533 this.selectAppropriateResolution(true)
2adfc7ea 534
c32bf839 535 // We changed the source, so reinit captions
2adfc7ea 536 this.player.trigger('sourcechange')
c32bf839 537
a73115f3
C
538 return this.tryToPlay(err => {
539 if (err && done) return done(err)
540
541 if (options.seek) this.seek(options.seek)
542 if (options.forcePlay === false && paused === true) this.player.pause()
543
544 if (done) return done()
545 })
bf5685f0
C
546 }
547
a22bfc3e
C
548 private handleError (err: Error | string) {
549 return this.player.trigger('customError', { err })
aa8b6df4 550 }
bf5685f0 551
8eb8bc20
C
552 private pickAverageVideoFile () {
553 if (this.videoFiles.length === 1) return this.videoFiles[0]
554
1a5b67b6
C
555 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
556 return files[Math.floor(files.length / 2)]
8eb8bc20
C
557 }
558
c199c427 559 private stopTorrent (torrent: WebTorrent.Torrent) {
b335ccec
C
560 torrent.pause()
561 // Pause does not remove actual peers (in particular the webseed peer)
9df52d66 562 torrent.removePeer(torrent['ws'])
b335ccec
C
563 }
564
565 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
3b019808 566 this.destroyingFakeRenderer = false
287918da 567
b335ccec
C
568 const fakeVideoElem = document.createElement('video')
569 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
570 this.fakeRenderer = renderer
571
287918da 572 // The renderer returns an error when we destroy it, so skip them
3b019808 573 if (this.destroyingFakeRenderer === false && err) {
287918da
C
574 console.error('Cannot render new torrent in fake video element.', err)
575 }
b335ccec
C
576
577 // Load the future file at the correct time (in delay MS - 2 seconds)
578 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
579 })
580 }
581
054a103b
C
582 private destroyFakeRenderer () {
583 if (this.fakeRenderer) {
3b019808 584 this.destroyingFakeRenderer = true
287918da 585
054a103b
C
586 if (this.fakeRenderer.destroy) {
587 try {
588 this.fakeRenderer.destroy()
589 } catch (err) {
590 console.log('Cannot destroy correctly fake renderer.', err)
591 }
592 }
593 this.fakeRenderer = undefined
594 }
595 }
596
2adfc7ea 597 private buildQualities () {
e367da94
C
598 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
599 id: file.resolution.id,
600 label: this.buildQualityLabel(file),
601 height: file.resolution.id,
602 selected: false,
89ac282e 603 selectCallback: () => this.changeQuality(file.resolution.id)
e367da94
C
604 }))
605
606 resolutions.push({
607 id: -1,
608 label: this.player.localize('Auto'),
609 selected: true,
89ac282e 610 selectCallback: () => this.changeQuality(-1)
e367da94 611 })
c32bf839 612
e367da94 613 this.player.peertubeResolutions().add(resolutions)
16f7022b
C
614 }
615
2adfc7ea
C
616 private buildQualityLabel (file: VideoFile) {
617 let label = file.resolution.label
618
619 if (file.fps && file.fps >= 50) {
620 label += file.fps
e993ecb3 621 }
2adfc7ea
C
622
623 return label
624 }
625
e367da94
C
626 private selectAppropriateResolution (byEngine: boolean) {
627 const resolution = this.autoResolution
628 ? -1
629 : this.getCurrentResolutionId()
2adfc7ea 630
e367da94
C
631 const autoResolutionChosen = this.autoResolution
632 ? this.getCurrentResolutionId()
633 : undefined
2adfc7ea 634
e367da94 635 this.player.peertubeResolutions().select({ id: resolution, autoResolutionChosenId: autoResolutionChosen, byEngine })
e993ecb3 636 }
aa8b6df4 637}
c6352f2c 638
2adfc7ea
C
639videojs.registerPlugin('webtorrent', WebTorrentPlugin)
640export { WebTorrentPlugin }