]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/shared/webtorrent/webtorrent-plugin.ts
Reduce auto play error log
[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
209 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
210 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
211 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
212
213 this.webtorrent.remove(videoFile.magnetUri)
214 logger.info(`Removed ${videoFile.magnetUri}`)
215 }
216 }
217
218 disableAutoResolution () {
219 this.autoResolution = false
220 this.autoResolutionPossible = false
221 this.player.peertubeResolutions().disableAutoResolution()
222 }
223
224 isAutoResolutionPossible () {
225 return this.autoResolutionPossible
226 }
227
228 getTorrent () {
229 return this.torrent
230 }
231
232 getCurrentVideoFile () {
233 return this.currentVideoFile
234 }
235
236 changeQuality (id: number) {
237 if (id === -1) {
238 if (this.autoResolutionPossible === true) {
239 this.autoResolution = true
240
241 this.selectAppropriateResolution(false)
242 }
243
244 return
245 }
246
247 this.autoResolution = false
248 this.updateEngineResolution(id)
249 this.selectAppropriateResolution(false)
250 }
251
252 private addTorrent (
253 magnetOrTorrentUrl: string,
254 previousVideoFile: VideoFile,
255 options: PlayOptions,
256 done: (err?: Error) => void
257 ) {
258 if (!magnetOrTorrentUrl) return this.fallbackToHttp(options, done)
259
260 logger.info(`Adding ${magnetOrTorrentUrl}.`)
261
262 const oldTorrent = this.torrent
263 const torrentOptions = {
264 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
265 store: function (chunkLength: number, storeOpts: any) {
266 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
267 max: 100
268 })
269 }
270 }
271
272 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
273 logger.info(`Added ${magnetOrTorrentUrl}.`)
274
275 if (oldTorrent) {
276 // Pause the old torrent
277 this.stopTorrent(oldTorrent)
278
279 // We use a fake renderer so we download correct pieces of the next file
280 if (options.delay) this.renderFileInFakeElement(torrent.files[0], options.delay)
281 }
282
283 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
284 this.addTorrentDelay = setTimeout(() => {
285 // We don't need the fake renderer anymore
286 this.destroyFakeRenderer()
287
288 const paused = this.player.paused()
289
290 this.flushVideoFile(previousVideoFile)
291
292 // Update progress bar (just for the UI), do not wait rendering
293 if (options.seek) this.player.currentTime(options.seek)
294
295 const renderVideoOptions = { autoplay: false, controls: true }
296 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions, (err, renderer) => {
297 this.renderer = renderer
298
299 if (err) return this.fallbackToHttp(options, done)
300
301 return this.tryToPlay(err => {
302 if (err) return done(err)
303
304 if (options.seek) this.seek(options.seek)
305 if (options.forcePlay === false && paused === true) this.player.pause()
306
307 return done()
308 })
309 })
310 }, options.delay || 0)
311 })
312
313 this.torrent.on('error', (err: any) => logger.error(err))
314
315 this.torrent.on('warning', (err: any) => {
316 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
317 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
318
319 // Users don't care about issues with WebRTC, but developers do so log it in the console
320 if (err.message.indexOf('Ice connection failed') !== -1) {
321 logger.info(err)
322 return
323 }
324
325 // Magnet hash is not up to date with the torrent file, add directly the torrent file
326 if (err.message.indexOf('incorrect info hash') !== -1) {
327 logger.error('Incorrect info hash detected, falling back to torrent file.')
328 const newOptions = { forcePlay: true, seek: options.seek }
329 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
330 }
331
332 // Remote instance is down
333 if (err.message.indexOf('from xs param') !== -1) {
334 this.handleError(err)
335 }
336
337 logger.warn(err)
338 })
339 }
340
341 private tryToPlay (done?: (err?: Error) => void) {
342 if (!done) done = function () { /* empty */ }
343
344 const playPromise = this.player.play()
345 if (playPromise !== undefined) {
346 return playPromise.then(() => done())
347 .catch((err: Error) => {
348 if (err.message.includes('The play() request was interrupted by a call to pause()')) {
349 return
350 }
351
352 logger.warn(err)
353 this.player.pause()
354 this.player.posterImage.show()
355 this.player.removeClass('vjs-has-autoplay')
356 this.player.removeClass('vjs-has-big-play-button-clicked')
357 this.player.removeClass('vjs-playing-audio-only-content')
358
359 return done()
360 })
361 }
362
363 return done()
364 }
365
366 private seek (time: number) {
367 this.player.currentTime(time)
368 this.player.handleTechSeeked_()
369 }
370
371 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
372 if (this.videoFiles === undefined) return undefined
373 if (this.videoFiles.length === 1) return this.videoFiles[0]
374
375 const files = this.videoFiles.filter(f => f.resolution.id !== 0)
376 if (files.length === 0) return undefined
377
378 // Don't change the torrent if the player ended
379 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
380
381 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
382
383 // Limit resolution according to player height
384 const playerHeight = this.playerElement.offsetHeight
385
386 // We take the first resolution just above the player height
387 // Example: player height is 530px, we want the 720p file instead of 480p
388 let maxResolution = files[0].resolution.id
389 for (let i = files.length - 1; i >= 0; i--) {
390 const resolutionId = files[i].resolution.id
391 if (resolutionId !== 0 && resolutionId >= playerHeight) {
392 maxResolution = resolutionId
393 break
394 }
395 }
396
397 // Filter videos we can play according to our screen resolution and bandwidth
398 const filteredFiles = files.filter(f => f.resolution.id <= maxResolution)
399 .filter(f => {
400 const fileBitrate = (f.size / this.videoDuration)
401 let threshold = fileBitrate
402
403 // If this is for a higher resolution or an initial load: add a margin
404 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
405 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
406 }
407
408 return averageDownloadSpeed > threshold
409 })
410
411 // If the download speed is too bad, return the lowest resolution we have
412 if (filteredFiles.length === 0) return videoFileMinByResolution(files)
413
414 return videoFileMaxByResolution(filteredFiles)
415 }
416
417 private getAndSaveActualDownloadSpeed () {
418 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
419 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
420 if (lastDownloadSpeeds.length === 0) return -1
421
422 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
423 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
424
425 // Save the average bandwidth for future use
426 saveAverageBandwidth(averageBandwidth)
427
428 return averageBandwidth
429 }
430
431 private initializePlayer () {
432 this.buildQualities()
433
434 if (this.videoFiles.length === 0) {
435 this.player.addClass('disabled')
436 return
437 }
438
439 if (this.autoplay) {
440 this.player.posterImage.hide()
441
442 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
443 }
444
445 // Proxy first play
446 const oldPlay = this.player.play.bind(this.player);
447 (this.player as any).play = () => {
448 this.player.addClass('vjs-has-big-play-button-clicked')
449 this.player.play = oldPlay
450
451 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
452 }
453 }
454
455 private runAutoQualityScheduler () {
456 this.autoQualityInterval = setInterval(() => {
457
458 // Not initialized or in HTTP fallback
459 if (this.torrent === undefined || this.torrent === null) return
460 if (this.autoResolution === false) return
461 if (this.isAutoResolutionObservation === true) return
462
463 const file = this.getAppropriateFile()
464 let changeResolution = false
465 let changeResolutionDelay = 0
466
467 // Lower resolution
468 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
469 logger.info(`Downgrading automatically the resolution to: ${file.resolution.label}`)
470 changeResolution = true
471 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
472 logger.info(`Upgrading automatically the resolution to: ${file.resolution.label}`)
473 changeResolution = true
474 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
475 }
476
477 if (changeResolution === true) {
478 this.updateEngineResolution(file.resolution.id, changeResolutionDelay)
479
480 // Wait some seconds in observation of our new resolution
481 this.isAutoResolutionObservation = true
482
483 this.qualityObservationTimer = setTimeout(() => {
484 this.isAutoResolutionObservation = false
485 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
486 }
487 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
488 }
489
490 private isPlayerWaiting () {
491 return this.player?.hasClass('vjs-waiting')
492 }
493
494 private runTorrentInfoScheduler () {
495 this.torrentInfoInterval = setInterval(() => {
496 // Not initialized yet
497 if (this.torrent === undefined) return
498
499 // Http fallback
500 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
501
502 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
503 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
504
505 return this.player.trigger('p2pInfo', {
506 source: 'webtorrent',
507 http: {
508 downloadSpeed: 0,
509 uploadSpeed: 0,
510 downloaded: 0,
511 uploaded: 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 }