]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/webtorrent/webtorrent-plugin.ts
Fix webtorrent play on Safari
[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 && isIOS() === false
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 === undefined) {
136 const savedAverageBandwidth = getAverageBandwidthInStore()
137 videoFile = savedAverageBandwidth
138 ? this.getAppropriateFile(savedAverageBandwidth)
139 : this.pickAverageVideoFile()
140 }
141
142 // Don't add the same video file once again
143 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
144 return
145 }
146
147 // Do not display error to user because we will have multiple fallback
148 this.disableErrorDisplay();
149
150 // Hack to "simulate" src link in video.js >= 6
151 // Without this, we can't play the video after pausing it
152 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
153 (this.player as any).src = () => true
154 const oldPlaybackRate = this.player.playbackRate()
155
156 const previousVideoFile = this.currentVideoFile
157 this.currentVideoFile = videoFile
158
159 // Don't try on iOS that does not support MediaSource
160 // Or don't use P2P if webtorrent is disabled
161 if (isIOS() || this.playerRefusedP2P) {
162 return this.fallbackToHttp(options, () => {
163 this.player.playbackRate(oldPlaybackRate)
164 return done()
165 })
166 }
167
168 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
169 this.player.playbackRate(oldPlaybackRate)
170 return done()
171 })
172
173 this.changeQuality()
174 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.currentVideoFile.resolution.id })
175 }
176
177 updateResolution (resolutionId: number, delay = 0) {
178 // Remember player state
179 const currentTime = this.player.currentTime()
180 const isPaused = this.player.paused()
181
182 // Hide bigPlayButton
183 if (!isPaused) {
184 this.player.bigPlayButton.hide()
185 }
186
187 // Audio-only (resolutionId === 0) gets special treatment
188 if (resolutionId === 0) {
189 // Audio-only: show poster, do not auto-hide controls
190 this.player.addClass('vjs-playing-audio-only-content')
191 this.player.posterImage.show()
192 } else {
193 // Hide poster to have black background
194 this.player.removeClass('vjs-playing-audio-only-content')
195 this.player.posterImage.hide()
196 }
197
198 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
199 const options = {
200 forcePlay: false,
201 delay,
202 seek: currentTime + (delay / 1000)
203 }
204
205 this.updateVideoFile(newVideoFile, options)
206 }
207
208 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
209 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
210 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
211
212 this.webtorrent.remove(videoFile.magnetUri)
213 console.log('Removed ' + videoFile.magnetUri)
214 }
215 }
216
217 enableAutoResolution () {
218 this.autoResolution = true
219 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
220 }
221
222 disableAutoResolution (forbid = false) {
223 if (forbid === true) this.autoResolutionPossible = false
224
225 this.autoResolution = false
226 this.trigger('autoResolutionChange', { possible: this.autoResolutionPossible })
227 this.trigger('resolutionChange', { auto: this.autoResolution, resolutionId: this.getCurrentResolutionId() })
228 }
229
230 isAutoResolutionPossible () {
231 return this.autoResolutionPossible
232 }
233
234 getTorrent () {
235 return this.torrent
236 }
237
238 getCurrentVideoFile () {
239 return this.currentVideoFile
240 }
241
242 private addTorrent (
243 magnetOrTorrentUrl: string,
244 previousVideoFile: VideoFile,
245 options: PlayOptions,
246 done: Function
247 ) {
248 console.log('Adding ' + magnetOrTorrentUrl + '.')
249
250 const oldTorrent = this.torrent
251 const torrentOptions = {
252 // Don't use arrow function: it breaks webtorrent (that uses `new` keyword)
253 store: function (chunkLength: number, storeOpts: any) {
254 return new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
255 max: 100
256 })
257 }
258 }
259
260 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
261 console.log('Added ' + magnetOrTorrentUrl + '.')
262
263 if (oldTorrent) {
264 // Pause the old torrent
265 this.stopTorrent(oldTorrent)
266
267 // We use a fake renderer so we download correct pieces of the next file
268 if (options.delay) this.renderFileInFakeElement(torrent.files[ 0 ], options.delay)
269 }
270
271 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
272 this.addTorrentDelay = setTimeout(() => {
273 // We don't need the fake renderer anymore
274 this.destroyFakeRenderer()
275
276 const paused = this.player.paused()
277
278 this.flushVideoFile(previousVideoFile)
279
280 // Update progress bar (just for the UI), do not wait rendering
281 if (options.seek) this.player.currentTime(options.seek)
282
283 const renderVideoOptions = { autoplay: false, controls: true }
284 renderVideo(torrent.files[ 0 ], this.playerElement, renderVideoOptions, (err, renderer) => {
285 this.renderer = renderer
286
287 if (err) return this.fallbackToHttp(options, done)
288
289 return this.tryToPlay(err => {
290 if (err) return done(err)
291
292 if (options.seek) this.seek(options.seek)
293 if (options.forcePlay === false && paused === true) this.player.pause()
294
295 return done()
296 })
297 })
298 }, options.delay || 0)
299 })
300
301 this.torrent.on('error', (err: any) => console.error(err))
302
303 this.torrent.on('warning', (err: any) => {
304 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
305 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
306
307 // Users don't care about issues with WebRTC, but developers do so log it in the console
308 if (err.message.indexOf('Ice connection failed') !== -1) {
309 console.log(err)
310 return
311 }
312
313 // Magnet hash is not up to date with the torrent file, add directly the torrent file
314 if (err.message.indexOf('incorrect info hash') !== -1) {
315 console.error('Incorrect info hash detected, falling back to torrent file.')
316 const newOptions = { forcePlay: true, seek: options.seek }
317 return this.addTorrent(this.torrent[ 'xs' ], previousVideoFile, newOptions, done)
318 }
319
320 // Remote instance is down
321 if (err.message.indexOf('from xs param') !== -1) {
322 this.handleError(err)
323 }
324
325 console.warn(err)
326 })
327 }
328
329 private tryToPlay (done?: (err?: Error) => void) {
330 if (!done) done = function () { /* empty */ }
331
332 // Try in mute mode because we have issues with Safari
333 if (isSafari() && this.player.muted() === false) {
334 this.player.muted(true)
335 }
336
337 const playPromise = this.player.play()
338 if (playPromise !== undefined) {
339 return playPromise.then(() => done())
340 .catch((err: Error) => {
341 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
342 return
343 }
344
345 console.error(err)
346 this.player.pause()
347 this.player.posterImage.show()
348 this.player.removeClass('vjs-has-autoplay')
349 this.player.removeClass('vjs-has-big-play-button-clicked')
350 this.player.removeClass('vjs-playing-audio-only-content')
351
352 return done()
353 })
354 }
355
356 return done()
357 }
358
359 private seek (time: number) {
360 this.player.currentTime(time)
361 this.player.handleTechSeeked_()
362 }
363
364 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
365 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
366 if (this.videoFiles.length === 1) return this.videoFiles[0]
367
368 // Don't change the torrent is the play was ended
369 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
370
371 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
372
373 // Limit resolution according to player height
374 const playerHeight = this.playerElement.offsetHeight
375
376 // We take the first resolution just above the player height
377 // Example: player height is 530px, we want the 720p file instead of 480p
378 let maxResolution = this.videoFiles[0].resolution.id
379 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
380 const resolutionId = this.videoFiles[i].resolution.id
381 if (resolutionId >= playerHeight) {
382 maxResolution = resolutionId
383 break
384 }
385 }
386
387 // Filter videos we can play according to our screen resolution and bandwidth
388 const filteredFiles = this.videoFiles
389 .filter(f => f.resolution.id <= maxResolution)
390 .filter(f => {
391 const fileBitrate = (f.size / this.videoDuration)
392 let threshold = fileBitrate
393
394 // If this is for a higher resolution or an initial load: add a margin
395 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
396 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
397 }
398
399 return averageDownloadSpeed > threshold
400 })
401
402 // If the download speed is too bad, return the lowest resolution we have
403 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
404
405 return videoFileMaxByResolution(filteredFiles)
406 }
407
408 private getAndSaveActualDownloadSpeed () {
409 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
410 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
411 if (lastDownloadSpeeds.length === 0) return -1
412
413 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
414 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
415
416 // Save the average bandwidth for future use
417 saveAverageBandwidth(averageBandwidth)
418
419 return averageBandwidth
420 }
421
422 private initializePlayer () {
423 this.buildQualities()
424
425 if (this.autoplay) {
426 this.player.posterImage.hide()
427
428 return this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
429 }
430
431 // Proxy first play
432 const oldPlay = this.player.play.bind(this.player);
433 (this.player as any).play = () => {
434 this.player.addClass('vjs-has-big-play-button-clicked')
435 this.player.play = oldPlay
436
437 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
438 }
439 }
440
441 private runAutoQualityScheduler () {
442 this.autoQualityInterval = setInterval(() => {
443
444 // Not initialized or in HTTP fallback
445 if (this.torrent === undefined || this.torrent === null) return
446 if (this.autoResolution === false) return
447 if (this.isAutoResolutionObservation === true) return
448
449 const file = this.getAppropriateFile()
450 let changeResolution = false
451 let changeResolutionDelay = 0
452
453 // Lower resolution
454 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
455 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
456 changeResolution = true
457 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
458 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
459 changeResolution = true
460 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
461 }
462
463 if (changeResolution === true) {
464 this.updateResolution(file.resolution.id, changeResolutionDelay)
465
466 // Wait some seconds in observation of our new resolution
467 this.isAutoResolutionObservation = true
468
469 this.qualityObservationTimer = setTimeout(() => {
470 this.isAutoResolutionObservation = false
471 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
472 }
473 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
474 }
475
476 private isPlayerWaiting () {
477 return this.player && this.player.hasClass('vjs-waiting')
478 }
479
480 private runTorrentInfoScheduler () {
481 this.torrentInfoInterval = setInterval(() => {
482 // Not initialized yet
483 if (this.torrent === undefined) return
484
485 // Http fallback
486 if (this.torrent === null) return this.player.trigger('p2pInfo', false)
487
488 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
489 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
490
491 return this.player.trigger('p2pInfo', {
492 http: {
493 downloadSpeed: 0,
494 uploadSpeed: 0,
495 downloaded: 0,
496 uploaded: 0
497 },
498 p2p: {
499 downloadSpeed: this.torrent.downloadSpeed,
500 numPeers: this.torrent.numPeers,
501 uploadSpeed: this.torrent.uploadSpeed,
502 downloaded: this.torrent.downloaded,
503 uploaded: this.torrent.uploaded
504 }
505 } as PlayerNetworkInfo)
506 }, this.CONSTANTS.INFO_SCHEDULER)
507 }
508
509 private fallbackToHttp (options: PlayOptions, done?: Function) {
510 const paused = this.player.paused()
511
512 this.disableAutoResolution(true)
513
514 this.flushVideoFile(this.currentVideoFile, true)
515 this.torrent = null
516
517 // Enable error display now this is our last fallback
518 this.player.one('error', () => this.enableErrorDisplay())
519
520 const httpUrl = this.currentVideoFile.fileUrl
521 this.player.src = this.savePlayerSrcFunction
522 this.player.src(httpUrl)
523
524 this.changeQuality()
525
526 // We changed the source, so reinit captions
527 this.player.trigger('sourcechange')
528
529 return this.tryToPlay(err => {
530 if (err && done) return done(err)
531
532 if (options.seek) this.seek(options.seek)
533 if (options.forcePlay === false && paused === true) this.player.pause()
534
535 if (done) return done()
536 })
537 }
538
539 private handleError (err: Error | string) {
540 return this.player.trigger('customError', { err })
541 }
542
543 private enableErrorDisplay () {
544 this.player.addClass('vjs-error-display-enabled')
545 }
546
547 private disableErrorDisplay () {
548 this.player.removeClass('vjs-error-display-enabled')
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
660 videojs.registerPlugin('webtorrent', WebTorrentPlugin)
661 export { WebTorrentPlugin }