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