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