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