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