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