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