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