]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/shared/webtorrent/webtorrent-plugin.ts
Add ability to list comments on local videos
[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
C
206 this.updateVideoFile(newVideoFile, options)
207 }
208
209 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
210 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
211 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
212
213 this.webtorrent.remove(videoFile.magnetUri)
42b40636 214 logger.info(`Removed ${videoFile.magnetUri}`)
b335ccec
C
215 }
216 }
217
e367da94 218 disableAutoResolution () {
b335ccec 219 this.autoResolution = false
e367da94
C
220 this.autoResolutionPossible = false
221 this.player.peertubeResolutions().disableAutoResolution()
b335ccec
C
222 }
223
6377a9f2
C
224 isAutoResolutionPossible () {
225 return this.autoResolutionPossible
226 }
227
b335ccec
C
228 getTorrent () {
229 return this.torrent
230 }
231
aedf50d1
C
232 getCurrentVideoFile () {
233 return this.currentVideoFile
234 }
235
89ac282e
C
236 changeQuality (id: number) {
237 if (id === -1) {
238 if (this.autoResolutionPossible === true) {
239 this.autoResolution = true
240
241 this.selectAppropriateResolution(false)
242 }
243
244 return
245 }
246
247 this.autoResolution = false
248 this.updateEngineResolution(id)
249 this.selectAppropriateResolution(false)
250 }
251
b335ccec 252 private addTorrent (
3baf9be2
C
253 magnetOrTorrentUrl: string,
254 previousVideoFile: VideoFile,
a73115f3 255 options: PlayOptions,
9df52d66 256 done: (err?: Error) => void
3baf9be2 257 ) {
d61893f7
C
258 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
259
42b40636 260 logger.info(`Adding ${magnetOrTorrentUrl}.`)
a216c623 261
a8462c8e 262 const oldTorrent = this.torrent
3baf9be2 263 const torrentOptions = {
85394ba2
C
264 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
265 store: function (chunkLength: number, storeOpts: any) {
266 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
267 max: 100
268 })
269 }
efda99c3
C
270 }
271
b7f1747d 272 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
42b40636 273 logger.info(`Added ${magnetOrTorrentUrl}.`)
aa8b6df4 274
a8462c8e 275 if (oldTorrent) {
4a7591e1 276 // Pause the old torrent
b335ccec 277 this.stopTorrent(oldTorrent)
6d272f39
C
278
279 // We use a fake renderer so we download correct pieces of the next file
9df52d66 280 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
a8462c8e 281 }
aa8b6df4 282
e7eb5b39 283 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
7ee4a4af 284 this.addTorrentDelay = setTimeout(() => {
b335ccec 285 // We don't need the fake renderer anymore
054a103b 286 this.destroyFakeRenderer()
6d272f39 287
3baf9be2
C
288 const paused = this.player.paused()
289
a8462c8e 290 this.flushVideoFile(previousVideoFile)
0dcf9a14 291
fe05c3ac
C
292 // Update progress bar (just for the UI), do not wait rendering
293 if (options.seek) this.player.currentTime(options.seek)
294
3baf9be2 295 const renderVideoOptions = { autoplay: false, controls: true }
9df52d66 296 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
a8462c8e 297 this.renderer = renderer
aa8b6df4 298
a73115f3 299 if (err) return this.fallbackToHttp(options, done)
3bcfff7f 300
c199c427 301 return this.tryToPlay(err => {
3baf9be2 302 if (err) return done(err)
a8462c8e 303
3baf9be2
C
304 if (options.seek) this.seek(options.seek)
305 if (options.forcePlay === false && paused === true) this.player.pause()
8244e187 306
a73115f3 307 return done()
3baf9be2 308 })
a8462c8e 309 })
3baf9be2 310 }, options.delay || 0)
aa8b6df4
C
311 })
312
42b40636 313 this.torrent.on('error', (err: any) => logger.error(err))
a216c623 314
a22bfc3e 315 this.torrent.on('warning', (err: any) => {
a96aed15 316 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
531ab5b6 317 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
a216c623 318
7dbdc3ba
C
319 // Users don't care about issues with WebRTC, but developers do so log it in the console
320 if (err.message.indexOf('Ice connection failed') !== -1) {
42b40636 321 logger.info(err)
7dbdc3ba
C
322 return
323 }
a96aed15 324
a216c623
C
325 // Magnet hash is not up to date with the torrent file, add directly the torrent file
326 if (err.message.indexOf('incorrect info hash') !== -1) {
42b40636 327 logger.error('Incorrect info hash detected, falling back to torrent file.')
1f6824c9 328 const newOptions = { forcePlay: true, seek: options.seek }
9df52d66 329 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
a216c623
C
330 }
331
6d88de72 332 // Remote instance is down
0f7fedc3 333 if (err.message.indexOf('from xs param') !== -1) {
6d88de72
C
334 this.handleError(err)
335 }
336
42b40636 337 logger.warn(err)
a96aed15 338 })
aa8b6df4
C
339 }
340
c199c427 341 private tryToPlay (done?: (err?: Error) => void) {
80109b2d 342 if (!done) done = function () { /* empty */ }
1fad099d 343
80109b2d
C
344 const playPromise = this.player.play()
345 if (playPromise !== undefined) {
f5fcd9f7 346 return playPromise.then(() => done())
244b4ae3 347 .catch((err: Error) => {
9df52d66 348 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
70b40c2e
C
349 return
350 }
351
3a818abd 352 logger.warn(err)
80109b2d
C
353 this.player.pause()
354 this.player.posterImage.show()
355 this.player.removeClass('vjs-has-autoplay')
91d95589 356 this.player.removeClass('vjs-has-big-play-button-clicked')
5c7d6508 357 this.player.removeClass('vjs-playing-audio-only-content')
80109b2d
C
358
359 return done()
360 })
361 }
362
363 return done()
364 }
365
f37bad63
C
366 private seek (time: number) {
367 this.player.currentTime(time)
368 this.player.handleTechSeeked_()
369 }
370
a8462c8e 371 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
3cd56a29 372 if (this.videoFiles === undefined) return undefined
2b6af10e 373 if (this.videoFiles.length === 1) return this.videoFiles[0]
3cd56a29
C
374
375 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
3cd56a29 376 if (files.length === 0) return undefined
a8462c8e 377
aea53cc6 378 // Don't change the torrent if the player ended
3c40590d
C
379 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
380
381 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
a8462c8e 382
0b755f3b 383 // Limit resolution according to player height
c4710631 384 const playerHeight = this.playerElement.offsetHeight
0b755f3b
C
385
386 // We take the first resolution just above the player height
387 // Example: player height is 530px, we want the 720p file instead of 480p
3cd56a29
C
388 let maxResolution = files[0].resolution.id
389 for (let i = files.length - 1; i >= 0; i--) {
390 const resolutionId = files[i].resolution.id
391 if (resolutionId !== 0 && resolutionId >= playerHeight) {
0b755f3b
C
392 maxResolution = resolutionId
393 break
a8462c8e 394 }
0b755f3b 395 }
a8462c8e 396
0b755f3b 397 // Filter videos we can play according to our screen resolution and bandwidth
3cd56a29
C
398 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
399 .filter(f => {
400 const fileBitrate = (f.size / this.videoDuration)
401 let threshold = fileBitrate
0b755f3b 402
3cd56a29
C
403 // If this is for a higher resolution or an initial load: add a margin
404 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
405 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
406 }
0b755f3b 407
3cd56a29
C
408 return averageDownloadSpeed > threshold
409 })
a8462c8e
C
410
411 // If the download speed is too bad, return the lowest resolution we have
3cd56a29 412 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
a8462c8e 413
6cca7360 414 return videoFileMaxByResolution(filteredFiles)
a8462c8e
C
415 }
416
3c40590d 417 private getAndSaveActualDownloadSpeed () {
a8462c8e
C
418 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
419 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
420 if (lastDownloadSpeeds.length === 0) return -1
421
422 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
423 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
424
425 // Save the average bandwidth for future use
426 saveAverageBandwidth(averageBandwidth)
ed9f9f5f 427
a8462c8e 428 return averageBandwidth
ed9f9f5f
C
429 }
430
0dcf9a14 431 private initializePlayer () {
2adfc7ea 432 this.buildQualities()
c6352f2c 433
d3f4689b
C
434 if (this.videoFiles.length === 0) {
435 this.player.addClass('disabled')
436 return
437 }
438
72efdda5 439 if (this.autoplay) {
33d78552 440 this.player.posterImage.hide()
e6f62797 441
a325db17 442 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
b335ccec 443 }
e7eb5b39 444
b335ccec 445 // Proxy first play
f5fcd9f7
C
446 const oldPlay = this.player.play.bind(this.player);
447 (this.player as any).play = () => {
b335ccec
C
448 this.player.addClass('vjs-has-big-play-button-clicked')
449 this.player.play = oldPlay
450
a325db17 451 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
aa8b6df4 452 }
a22bfc3e 453 }
aa8b6df4 454
a8462c8e
C
455 private runAutoQualityScheduler () {
456 this.autoQualityInterval = setInterval(() => {
7ee4a4af 457
877b0528
C
458 // Not initialized or in HTTP fallback
459 if (this.torrent === undefined || this.torrent === null) return
2adfc7ea 460 if (this.autoResolution === false) return
a8462c8e
C
461 if (this.isAutoResolutionObservation === true) return
462
463 const file = this.getAppropriateFile()
464 let changeResolution = false
465 let changeResolutionDelay = 0
466
467 // Lower resolution
468 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
42b40636 469 logger.info(`Downgrading automatically the resolution to: ${file.resolution.label}`)
a8462c8e 470 changeResolution = true
7ee4a4af 471 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
42b40636 472 logger.info(`Upgrading automatically the resolution to: ${file.resolution.label}`)
a8462c8e 473 changeResolution = true
7ee4a4af 474 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
a8462c8e
C
475 }
476
477 if (changeResolution === true) {
89ac282e 478 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
a8462c8e
C
479
480 // Wait some seconds in observation of our new resolution
481 this.isAutoResolutionObservation = true
7ee4a4af
C
482
483 this.qualityObservationTimer = setTimeout(() => {
484 this.isAutoResolutionObservation = false
485 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
a8462c8e
C
486 }
487 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
488 }
489
490 private isPlayerWaiting () {
9df52d66 491 return this.player?.hasClass('vjs-waiting')
a8462c8e
C
492 }
493
a22bfc3e 494 private runTorrentInfoScheduler () {
3bcfff7f 495 this.torrentInfoInterval = setInterval(() => {
bf5685f0
C
496 // Not initialized yet
497 if (this.torrent === undefined) return
498
499 // Http fallback
2adfc7ea 500 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
bf5685f0 501
b7f1747d
C
502 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
503 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
a8462c8e 504
2adfc7ea 505 return this.player.trigger('p2pInfo', {
17152837 506 source: 'webtorrent',
09209296
C
507 http: {
508 downloadSpeed: 0,
509 uploadSpeed: 0,
510 downloaded: 0,
511 uploaded: 0
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 }