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