]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/webtorrent/webtorrent-plugin.ts
Merge branch 'release/3.4.0' into develop
[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 updateEngineResolution (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 changeQuality (id: number) {
240 if (id === -1) {
241 if (this.autoResolutionPossible === true) {
242 this.autoResolution = true
243
244 this.selectAppropriateResolution(false)
245 }
246
247 return
248 }
249
250 this.autoResolution = false
251 this.updateEngineResolution(id)
252 this.selectAppropriateResolution(false)
253 }
254
255 private addTorrent (
256 magnetOrTorrentUrl: string,
257 previousVideoFile: VideoFile,
258 options: PlayOptions,
259 done: (err?: Error) => void
260 ) {
261 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
262
263 console.log('Adding ' + magnetOrTorrentUrl + '.')
264
265 const oldTorrent = this.torrent
266 const torrentOptions = {
267 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
268 store: function (chunkLength: number, storeOpts: any) {
269 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
270 max: 100
271 })
272 }
273 }
274
275 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
276 console.log('Added ' + magnetOrTorrentUrl + '.')
277
278 if (oldTorrent) {
279 // Pause the old torrent
280 this.stopTorrent(oldTorrent)
281
282 // We use a fake renderer so we download correct pieces of the next file
283 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
284 }
285
286 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
287 this.addTorrentDelay = setTimeout(() => {
288 // We don't need the fake renderer anymore
289 this.destroyFakeRenderer()
290
291 const paused = this.player.paused()
292
293 this.flushVideoFile(previousVideoFile)
294
295 // Update progress bar (just for the UI), do not wait rendering
296 if (options.seek) this.player.currentTime(options.seek)
297
298 const renderVideoOptions = { autoplay: false, controls: true }
299 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
300 this.renderer = renderer
301
302 if (err) return this.fallbackToHttp(options, done)
303
304 return this.tryToPlay(err => {
305 if (err) return done(err)
306
307 if (options.seek) this.seek(options.seek)
308 if (options.forcePlay === false && paused === true) this.player.pause()
309
310 return done()
311 })
312 })
313 }, options.delay || 0)
314 })
315
316 this.torrent.on('error', (err: any) => console.error(err))
317
318 this.torrent.on('warning', (err: any) => {
319 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
320 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
321
322 // Users don't care about issues with WebRTC, but developers do so log it in the console
323 if (err.message.indexOf('Ice connection failed') !== -1) {
324 console.log(err)
325 return
326 }
327
328 // Magnet hash is not up to date with the torrent file, add directly the torrent file
329 if (err.message.indexOf('incorrect info hash') !== -1) {
330 console.error('Incorrect info hash detected, falling back to torrent file.')
331 const newOptions = { forcePlay: true, seek: options.seek }
332 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
333 }
334
335 // Remote instance is down
336 if (err.message.indexOf('from xs param') !== -1) {
337 this.handleError(err)
338 }
339
340 console.warn(err)
341 })
342 }
343
344 private tryToPlay (done?: (err?: Error) => void) {
345 if (!done) done = function () { /* empty */ }
346
347 const playPromise = this.player.play()
348 if (playPromise !== undefined) {
349 return playPromise.then(() => done())
350 .catch((err: Error) => {
351 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
352 return
353 }
354
355 console.error(err)
356 this.player.pause()
357 this.player.posterImage.show()
358 this.player.removeClass('vjs-has-autoplay')
359 this.player.removeClass('vjs-has-big-play-button-clicked')
360 this.player.removeClass('vjs-playing-audio-only-content')
361
362 return done()
363 })
364 }
365
366 return done()
367 }
368
369 private seek (time: number) {
370 this.player.currentTime(time)
371 this.player.handleTechSeeked_()
372 }
373
374 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
375 if (this.videoFiles === undefined) return undefined
376
377 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
378
379 if (files.length === 0) return undefined
380 if (files.length === 1) return files[0]
381
382 // Don't change the torrent if the player ended
383 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
384
385 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
386
387 // Limit resolution according to player height
388 const playerHeight = this.playerElement.offsetHeight
389
390 // We take the first resolution just above the player height
391 // Example: player height is 530px, we want the 720p file instead of 480p
392 let maxResolution = files[0].resolution.id
393 for (let i = files.length - 1; i >= 0; i--) {
394 const resolutionId = files[i].resolution.id
395 if (resolutionId !== 0 && resolutionId >= playerHeight) {
396 maxResolution = resolutionId
397 break
398 }
399 }
400
401 // Filter videos we can play according to our screen resolution and bandwidth
402 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
403 .filter(f => {
404 const fileBitrate = (f.size / this.videoDuration)
405 let threshold = fileBitrate
406
407 // If this is for a higher resolution or an initial load: add a margin
408 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
409 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
410 }
411
412 return averageDownloadSpeed > threshold
413 })
414
415 // If the download speed is too bad, return the lowest resolution we have
416 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
417
418 return videoFileMaxByResolution(filteredFiles)
419 }
420
421 private getAndSaveActualDownloadSpeed () {
422 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
423 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
424 if (lastDownloadSpeeds.length === 0) return -1
425
426 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
427 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
428
429 // Save the average bandwidth for future use
430 saveAverageBandwidth(averageBandwidth)
431
432 return averageBandwidth
433 }
434
435 private initializePlayer () {
436 this.buildQualities()
437
438 if (this.autoplay) {
439 this.player.posterImage.hide()
440
441 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
442 }
443
444 // Proxy first play
445 const oldPlay = this.player.play.bind(this.player);
446 (this.player as any).play = () => {
447 this.player.addClass('vjs-has-big-play-button-clicked')
448 this.player.play = oldPlay
449
450 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
451 }
452 }
453
454 private runAutoQualityScheduler () {
455 this.autoQualityInterval = setInterval(() => {
456
457 // Not initialized or in HTTP fallback
458 if (this.torrent === undefined || this.torrent === null) return
459 if (this.autoResolution === false) return
460 if (this.isAutoResolutionObservation === true) return
461
462 const file = this.getAppropriateFile()
463 let changeResolution = false
464 let changeResolutionDelay = 0
465
466 // Lower resolution
467 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
468 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
469 changeResolution = true
470 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
471 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
472 changeResolution = true
473 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
474 }
475
476 if (changeResolution === true) {
477 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
478
479 // Wait some seconds in observation of our new resolution
480 this.isAutoResolutionObservation = true
481
482 this.qualityObservationTimer = setTimeout(() => {
483 this.isAutoResolutionObservation = false
484 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
485 }
486 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
487 }
488
489 private isPlayerWaiting () {
490 return this.player?.hasClass('vjs-waiting')
491 }
492
493 private runTorrentInfoScheduler () {
494 this.torrentInfoInterval = setInterval(() => {
495 // Not initialized yet
496 if (this.torrent === undefined) return
497
498 // Http fallback
499 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
500
501 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
502 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
503
504 return this.player.trigger('p2pInfo', {
505 source: 'webtorrent',
506 http: {
507 downloadSpeed: 0,
508 uploadSpeed: 0,
509 downloaded: 0,
510 uploaded: 0
511 },
512 p2p: {
513 downloadSpeed: this.torrent.downloadSpeed,
514 numPeers: this.torrent.numPeers,
515 uploadSpeed: this.torrent.uploadSpeed,
516 downloaded: this.torrent.downloaded,
517 uploaded: this.torrent.uploaded
518 },
519 bandwidthEstimate: this.webtorrent.downloadSpeed
520 } as PlayerNetworkInfo)
521 }, this.CONSTANTS.INFO_SCHEDULER)
522 }
523
524 private fallbackToHttp (options: PlayOptions, done?: (err?: Error) => void) {
525 const paused = this.player.paused()
526
527 this.disableAutoResolution()
528
529 this.flushVideoFile(this.currentVideoFile, true)
530 this.torrent = null
531
532 // Enable error display now this is our last fallback
533 this.player.one('error', () => this.enableErrorDisplay())
534
535 const httpUrl = this.currentVideoFile.fileUrl
536 this.player.src = this.savePlayerSrcFunction
537 this.player.src(httpUrl)
538
539 this.selectAppropriateResolution(true)
540
541 // We changed the source, so reinit captions
542 this.player.trigger('sourcechange')
543
544 return this.tryToPlay(err => {
545 if (err && done) return done(err)
546
547 if (options.seek) this.seek(options.seek)
548 if (options.forcePlay === false && paused === true) this.player.pause()
549
550 if (done) return done()
551 })
552 }
553
554 private handleError (err: Error | string) {
555 return this.player.trigger('customError', { err })
556 }
557
558 private enableErrorDisplay () {
559 this.player.addClass('vjs-error-display-enabled')
560 }
561
562 private disableErrorDisplay () {
563 this.player.removeClass('vjs-error-display-enabled')
564 }
565
566 private pickAverageVideoFile () {
567 if (this.videoFiles.length === 1) return this.videoFiles[0]
568
569 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
570 return files[Math.floor(files.length / 2)]
571 }
572
573 private stopTorrent (torrent: WebTorrent.Torrent) {
574 torrent.pause()
575 // Pause does not remove actual peers (in particular the webseed peer)
576 torrent.removePeer(torrent['ws'])
577 }
578
579 private renderFileInFakeElement (file: WebTorrent.TorrentFile, delay: number) {
580 this.destroyingFakeRenderer = false
581
582 const fakeVideoElem = document.createElement('video')
583 renderVideo(file, fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
584 this.fakeRenderer = renderer
585
586 // The renderer returns an error when we destroy it, so skip them
587 if (this.destroyingFakeRenderer === false && err) {
588 console.error('Cannot render new torrent in fake video element.', err)
589 }
590
591 // Load the future file at the correct time (in delay MS - 2 seconds)
592 fakeVideoElem.currentTime = this.player.currentTime() + (delay - 2000)
593 })
594 }
595
596 private destroyFakeRenderer () {
597 if (this.fakeRenderer) {
598 this.destroyingFakeRenderer = true
599
600 if (this.fakeRenderer.destroy) {
601 try {
602 this.fakeRenderer.destroy()
603 } catch (err) {
604 console.log('Cannot destroy correctly fake renderer.', err)
605 }
606 }
607 this.fakeRenderer = undefined
608 }
609 }
610
611 private buildQualities () {
612 const resolutions: PeerTubeResolution[] = this.videoFiles.map(file => ({
613 id: file.resolution.id,
614 label: this.buildQualityLabel(file),
615 height: file.resolution.id,
616 selected: false,
617 selectCallback: () => this.changeQuality(file.resolution.id)
618 }))
619
620 resolutions.push({
621 id: -1,
622 label: this.player.localize('Auto'),
623 selected: true,
624 selectCallback: () => this.changeQuality(-1)
625 })
626
627 this.player.peertubeResolutions().add(resolutions)
628 }
629
630 private buildQualityLabel (file: VideoFile) {
631 let label = file.resolution.label
632
633 if (file.fps && file.fps >= 50) {
634 label += file.fps
635 }
636
637 return label
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 }