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