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