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