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