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