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