]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-videojs-plugin.ts
Cache player translations
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-videojs-plugin.ts
1 import * as videojs from 'video.js'
2 import * as WebTorrent from 'webtorrent'
3 import { VideoFile } from '../../../../shared/models/videos/video.model'
4 import { renderVideo } from './video-renderer'
5 import './settings-menu-button'
6 import { PeertubePluginOptions, VideoJSCaption, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { isMobile, videoFileMaxByResolution, videoFileMinByResolution, timeToInt } from './utils'
8 import * as CacheChunkStore from 'cache-chunk-store'
9 import { PeertubeChunkStore } from './peertube-chunk-store'
10 import {
11 getAverageBandwidthInStore,
12 getStoredMute,
13 getStoredVolume,
14 saveAverageBandwidth,
15 saveMuteInStore,
16 saveVolumeInStore
17 } from './peertube-player-local-storage'
18
19 const Plugin: VideoJSComponentInterface = videojs.getPlugin('plugin')
20 class PeerTubePlugin extends Plugin {
21 private readonly playerElement: HTMLVideoElement
22
23 private readonly autoplay: boolean = false
24 private readonly startTime: number = 0
25 private readonly savePlayerSrcFunction: Function
26 private readonly videoFiles: VideoFile[]
27 private readonly videoViewUrl: string
28 private readonly videoDuration: number
29 private readonly CONSTANTS = {
30 INFO_SCHEDULER: 1000, // Don't change this
31 AUTO_QUALITY_SCHEDULER: 3000, // Check quality every 3 seconds
32 AUTO_QUALITY_THRESHOLD_PERCENT: 30, // Bandwidth should be 30% more important than a resolution bitrate to change to it
33 AUTO_QUALITY_OBSERVATION_TIME: 10000, // Wait 10 seconds after having change the resolution before another check
34 AUTO_QUALITY_HIGHER_RESOLUTION_DELAY: 5000, // Buffering higher resolution during 5 seconds
35 BANDWIDTH_AVERAGE_NUMBER_OF_VALUES: 5 // Last 5 seconds to build average bandwidth
36 }
37
38 private readonly webtorrent = new WebTorrent({
39 tracker: {
40 rtcConfig: {
41 iceServers: [
42 {
43 urls: 'stun:stun.stunprotocol.org'
44 },
45 {
46 urls: 'stun:stun.framasoft.org'
47 }
48 ]
49 }
50 },
51 dht: false
52 })
53
54 private player: any
55 private currentVideoFile: VideoFile
56 private torrent: WebTorrent.Torrent
57 private videoCaptions: VideoJSCaption[]
58 private renderer
59 private fakeRenderer
60 private autoResolution = true
61 private forbidAutoResolution = false
62 private isAutoResolutionObservation = false
63
64 private videoViewInterval
65 private torrentInfoInterval
66 private autoQualityInterval
67 private addTorrentDelay
68 private qualityObservationTimer
69 private runAutoQualitySchedulerTimer
70
71 private downloadSpeeds: number[] = []
72
73 constructor (player: videojs.Player, options: PeertubePluginOptions) {
74 super(player, options)
75
76 // Disable auto play on iOS
77 this.autoplay = options.autoplay && this.isIOS() === false
78
79 this.startTime = timeToInt(options.startTime)
80 this.videoFiles = options.videoFiles
81 this.videoViewUrl = options.videoViewUrl
82 this.videoDuration = options.videoDuration
83 this.videoCaptions = options.videoCaptions
84
85 this.savePlayerSrcFunction = this.player.src
86 // Hack to "simulate" src link in video.js >= 6
87 // Without this, we can't play the video after pausing it
88 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
89 this.player.src = () => true
90
91 this.playerElement = options.playerElement
92
93 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
94
95 this.player.ready(() => {
96 const volume = getStoredVolume()
97 if (volume !== undefined) this.player.volume(volume)
98 const muted = getStoredMute()
99 if (muted !== undefined) this.player.muted(muted)
100
101 this.initializePlayer()
102 this.runTorrentInfoScheduler()
103 this.runViewAdd()
104
105 this.player.one('play', () => {
106 // Don't run immediately scheduler, wait some seconds the TCP connections are made
107 this.runAutoQualitySchedulerTimer = setTimeout(() => {
108 this.runAutoQualityScheduler()
109 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
110 })
111 })
112
113 this.player.on('volumechange', () => {
114 saveVolumeInStore(this.player.volume())
115 saveMuteInStore(this.player.muted())
116 })
117 }
118
119 dispose () {
120 clearTimeout(this.addTorrentDelay)
121 clearTimeout(this.qualityObservationTimer)
122 clearTimeout(this.runAutoQualitySchedulerTimer)
123
124 clearInterval(this.videoViewInterval)
125 clearInterval(this.torrentInfoInterval)
126 clearInterval(this.autoQualityInterval)
127
128 // Don't need to destroy renderer, video player will be destroyed
129 this.flushVideoFile(this.currentVideoFile, false)
130
131 this.destroyFakeRenderer()
132 }
133
134 getCurrentResolutionId () {
135 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
136 }
137
138 getCurrentResolutionLabel () {
139 if (!this.currentVideoFile) return ''
140
141 const fps = this.currentVideoFile.fps >= 50 ? this.currentVideoFile.fps : ''
142 return this.currentVideoFile.resolution.label + fps
143 }
144
145 updateVideoFile (
146 videoFile?: VideoFile,
147 options: {
148 forcePlay?: boolean,
149 seek?: number,
150 delay?: number
151 } = {},
152 done: () => void = () => { /* empty */ }
153 ) {
154 // Automatically choose the adapted video file
155 if (videoFile === undefined) {
156 const savedAverageBandwidth = getAverageBandwidthInStore()
157 videoFile = savedAverageBandwidth
158 ? this.getAppropriateFile(savedAverageBandwidth)
159 : this.pickAverageVideoFile()
160 }
161
162 // Don't add the same video file once again
163 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
164 return
165 }
166
167 // Do not display error to user because we will have multiple fallback
168 this.disableErrorDisplay()
169
170 this.player.src = () => true
171 const oldPlaybackRate = this.player.playbackRate()
172
173 const previousVideoFile = this.currentVideoFile
174 this.currentVideoFile = videoFile
175
176 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
177 this.player.playbackRate(oldPlaybackRate)
178 return done()
179 })
180
181 this.trigger('videoFileUpdate')
182 }
183
184 addTorrent (
185 magnetOrTorrentUrl: string,
186 previousVideoFile: VideoFile,
187 options: {
188 forcePlay?: boolean,
189 seek?: number,
190 delay?: number
191 },
192 done: Function
193 ) {
194 console.log('Adding ' + magnetOrTorrentUrl + '.')
195
196 const oldTorrent = this.torrent
197 const torrentOptions = {
198 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
199 max: 100
200 })
201 }
202
203 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
204 console.log('Added ' + magnetOrTorrentUrl + '.')
205
206 if (oldTorrent) {
207 // Pause the old torrent
208 oldTorrent.pause()
209 // Pause does not remove actual peers (in particular the webseed peer)
210 oldTorrent.removePeer(oldTorrent['ws'])
211
212 // We use a fake renderer so we download correct pieces of the next file
213 if (options.delay) {
214 const fakeVideoElem = document.createElement('video')
215 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
216 this.fakeRenderer = renderer
217
218 if (err) console.error('Cannot render new torrent in fake video element.', err)
219
220 // Load the future file at the correct time
221 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
222 })
223 }
224 }
225
226 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
227 this.addTorrentDelay = setTimeout(() => {
228 this.destroyFakeRenderer()
229
230 const paused = this.player.paused()
231
232 this.flushVideoFile(previousVideoFile)
233
234 const renderVideoOptions = { autoplay: false, controls: true }
235 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
236 this.renderer = renderer
237
238 if (err) return this.fallbackToHttp(done)
239
240 return this.tryToPlay(err => {
241 if (err) return done(err)
242
243 if (options.seek) this.seek(options.seek)
244 if (options.forcePlay === false && paused === true) this.player.pause()
245
246 return done(err)
247 })
248 })
249 }, options.delay || 0)
250 })
251
252 this.torrent.on('error', err => console.error(err))
253
254 this.torrent.on('warning', (err: any) => {
255 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
256 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
257
258 // Users don't care about issues with WebRTC, but developers do so log it in the console
259 if (err.message.indexOf('Ice connection failed') !== -1) {
260 console.log(err)
261 return
262 }
263
264 // Magnet hash is not up to date with the torrent file, add directly the torrent file
265 if (err.message.indexOf('incorrect info hash') !== -1) {
266 console.error('Incorrect info hash detected, falling back to torrent file.')
267 const newOptions = { forcePlay: true, seek: options.seek }
268 return this.addTorrent(this.torrent['xs'], previousVideoFile, newOptions, done)
269 }
270
271 // Remote instance is down
272 if (err.message.indexOf('from xs param') !== -1) {
273 this.handleError(err)
274 }
275
276 console.warn(err)
277 })
278 }
279
280 updateResolution (resolutionId: number, delay = 0) {
281 // Remember player state
282 const currentTime = this.player.currentTime()
283 const isPaused = this.player.paused()
284
285 // Remove poster to have black background
286 this.playerElement.poster = ''
287
288 // Hide bigPlayButton
289 if (!isPaused) {
290 this.player.bigPlayButton.hide()
291 }
292
293 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
294 const options = {
295 forcePlay: false,
296 delay,
297 seek: currentTime + (delay / 1000)
298 }
299 this.updateVideoFile(newVideoFile, options)
300 }
301
302 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
303 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
304 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
305
306 this.webtorrent.remove(videoFile.magnetUri)
307 console.log('Removed ' + videoFile.magnetUri)
308 }
309 }
310
311 isAutoResolutionOn () {
312 return this.autoResolution
313 }
314
315 enableAutoResolution () {
316 this.autoResolution = true
317 this.trigger('autoResolutionUpdate')
318 }
319
320 disableAutoResolution (forbid = false) {
321 if (forbid === true) this.forbidAutoResolution = true
322
323 this.autoResolution = false
324 this.trigger('autoResolutionUpdate')
325 }
326
327 isAutoResolutionForbidden () {
328 return this.forbidAutoResolution === true
329 }
330
331 getCurrentVideoFile () {
332 return this.currentVideoFile
333 }
334
335 getTorrent () {
336 return this.torrent
337 }
338
339 private tryToPlay (done?: Function) {
340 if (!done) done = function () { /* empty */ }
341
342 const playPromise = this.player.play()
343 if (playPromise !== undefined) {
344 return playPromise.then(done)
345 .catch(err => {
346 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
347 return
348 }
349
350 console.error(err)
351 this.player.pause()
352 this.player.posterImage.show()
353 this.player.removeClass('vjs-has-autoplay')
354 this.player.removeClass('vjs-has-big-play-button-clicked')
355
356 return done()
357 })
358 }
359
360 return done()
361 }
362
363 private seek (time: number) {
364 this.player.currentTime(time)
365 this.player.handleTechSeeked_()
366 }
367
368 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
369 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
370 if (this.videoFiles.length === 1) return this.videoFiles[0]
371
372 // Don't change the torrent is the play was ended
373 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
374
375 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
376
377 // Limit resolution according to player height
378 const playerHeight = this.playerElement.offsetHeight as number
379
380 // We take the first resolution just above the player height
381 // Example: player height is 530px, we want the 720p file instead of 480p
382 let maxResolution = this.videoFiles[0].resolution.id
383 for (let i = this.videoFiles.length - 1; i >= 0; i--) {
384 const resolutionId = this.videoFiles[i].resolution.id
385 if (resolutionId >= playerHeight) {
386 maxResolution = resolutionId
387 break
388 }
389 }
390
391 // Filter videos we can play according to our screen resolution and bandwidth
392 const filteredFiles = this.videoFiles
393 .filter(f => f.resolution.id <= maxResolution)
394 .filter(f => {
395 const fileBitrate = (f.size / this.videoDuration)
396 let threshold = fileBitrate
397
398 // If this is for a higher resolution or an initial load: add a margin
399 if (!this.currentVideoFile || f.resolution.id > this.currentVideoFile.resolution.id) {
400 threshold += ((fileBitrate * this.CONSTANTS.AUTO_QUALITY_THRESHOLD_PERCENT) / 100)
401 }
402
403 return averageDownloadSpeed > threshold
404 })
405
406 // If the download speed is too bad, return the lowest resolution we have
407 if (filteredFiles.length === 0) return videoFileMinByResolution(this.videoFiles)
408
409 return videoFileMaxByResolution(filteredFiles)
410 }
411
412 private getAndSaveActualDownloadSpeed () {
413 const start = Math.max(this.downloadSpeeds.length - this.CONSTANTS.BANDWIDTH_AVERAGE_NUMBER_OF_VALUES, 0)
414 const lastDownloadSpeeds = this.downloadSpeeds.slice(start, this.downloadSpeeds.length)
415 if (lastDownloadSpeeds.length === 0) return -1
416
417 const sum = lastDownloadSpeeds.reduce((a, b) => a + b)
418 const averageBandwidth = Math.round(sum / lastDownloadSpeeds.length)
419
420 // Save the average bandwidth for future use
421 saveAverageBandwidth(averageBandwidth)
422
423 return averageBandwidth
424 }
425
426 private initializePlayer () {
427 if (isMobile()) this.player.addClass('vjs-is-mobile')
428
429 this.initSmoothProgressBar()
430
431 this.initCaptions()
432
433 this.alterInactivity()
434
435 if (this.autoplay === true) {
436 this.player.posterImage.hide()
437
438 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
439 } else {
440 // Don't try on iOS that does not support MediaSource
441 if (this.isIOS()) {
442 this.currentVideoFile = this.pickAverageVideoFile()
443 return this.fallbackToHttp(undefined, false)
444 }
445
446 // Proxy first play
447 const oldPlay = this.player.play.bind(this.player)
448 this.player.play = () => {
449 this.player.addClass('vjs-has-big-play-button-clicked')
450 this.player.play = oldPlay
451
452 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
453 }
454 }
455 }
456
457 private runAutoQualityScheduler () {
458 this.autoQualityInterval = setInterval(() => {
459
460 // Not initialized or in HTTP fallback
461 if (this.torrent === undefined || this.torrent === null) return
462 if (this.isAutoResolutionOn() === false) return
463 if (this.isAutoResolutionObservation === true) return
464
465 const file = this.getAppropriateFile()
466 let changeResolution = false
467 let changeResolutionDelay = 0
468
469 // Lower resolution
470 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
471 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
472 changeResolution = true
473 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
474 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
475 changeResolution = true
476 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
477 }
478
479 if (changeResolution === true) {
480 this.updateResolution(file.resolution.id, changeResolutionDelay)
481
482 // Wait some seconds in observation of our new resolution
483 this.isAutoResolutionObservation = true
484
485 this.qualityObservationTimer = setTimeout(() => {
486 this.isAutoResolutionObservation = false
487 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
488 }
489 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
490 }
491
492 private isPlayerWaiting () {
493 return this.player && this.player.hasClass('vjs-waiting')
494 }
495
496 private runTorrentInfoScheduler () {
497 this.torrentInfoInterval = setInterval(() => {
498 // Not initialized yet
499 if (this.torrent === undefined) return
500
501 // Http fallback
502 if (this.torrent === null) return this.trigger('torrentInfo', false)
503
504 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
505 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
506
507 return this.trigger('torrentInfo', {
508 downloadSpeed: this.torrent.downloadSpeed,
509 numPeers: this.torrent.numPeers,
510 uploadSpeed: this.torrent.uploadSpeed,
511 downloaded: this.torrent.downloaded,
512 uploaded: this.torrent.uploaded
513 })
514 }, this.CONSTANTS.INFO_SCHEDULER)
515 }
516
517 private runViewAdd () {
518 this.clearVideoViewInterval()
519
520 // After 30 seconds (or 3/4 of the video), add a view to the video
521 let minSecondsToView = 30
522
523 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
524
525 let secondsViewed = 0
526 this.videoViewInterval = setInterval(() => {
527 if (this.player && !this.player.paused()) {
528 secondsViewed += 1
529
530 if (secondsViewed > minSecondsToView) {
531 this.clearVideoViewInterval()
532
533 this.addViewToVideo().catch(err => console.error(err))
534 }
535 }
536 }, 1000)
537 }
538
539 private clearVideoViewInterval () {
540 if (this.videoViewInterval !== undefined) {
541 clearInterval(this.videoViewInterval)
542 this.videoViewInterval = undefined
543 }
544 }
545
546 private addViewToVideo () {
547 if (!this.videoViewUrl) return Promise.resolve(undefined)
548
549 return fetch(this.videoViewUrl, { method: 'POST' })
550 }
551
552 private fallbackToHttp (done?: Function, play = true) {
553 this.disableAutoResolution(true)
554
555 this.flushVideoFile(this.currentVideoFile, true)
556 this.torrent = null
557
558 // Enable error display now this is our last fallback
559 this.player.one('error', () => this.enableErrorDisplay())
560
561 const httpUrl = this.currentVideoFile.fileUrl
562 this.player.src = this.savePlayerSrcFunction
563 this.player.src(httpUrl)
564 if (play) this.tryToPlay()
565
566 if (done) return done()
567 }
568
569 private handleError (err: Error | string) {
570 return this.player.trigger('customError', { err })
571 }
572
573 private enableErrorDisplay () {
574 this.player.addClass('vjs-error-display-enabled')
575 }
576
577 private disableErrorDisplay () {
578 this.player.removeClass('vjs-error-display-enabled')
579 }
580
581 private isIOS () {
582 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
583 }
584
585 private alterInactivity () {
586 let saveInactivityTimeout: number
587
588 const disableInactivity = () => {
589 saveInactivityTimeout = this.player.options_.inactivityTimeout
590 this.player.options_.inactivityTimeout = 0
591 }
592 const enableInactivity = () => {
593 this.player.options_.inactivityTimeout = saveInactivityTimeout
594 }
595
596 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
597
598 this.player.controlBar.on('mouseenter', () => disableInactivity())
599 settingsDialog.on('mouseenter', () => disableInactivity())
600 this.player.controlBar.on('mouseleave', () => enableInactivity())
601 settingsDialog.on('mouseleave', () => enableInactivity())
602 }
603
604 private pickAverageVideoFile () {
605 if (this.videoFiles.length === 1) return this.videoFiles[0]
606
607 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
608 }
609
610 private destroyFakeRenderer () {
611 if (this.fakeRenderer) {
612 if (this.fakeRenderer.destroy) {
613 try {
614 this.fakeRenderer.destroy()
615 } catch (err) {
616 console.log('Cannot destroy correctly fake renderer.', err)
617 }
618 }
619 this.fakeRenderer = undefined
620 }
621 }
622
623 private initCaptions () {
624 for (const caption of this.videoCaptions) {
625 this.player.addRemoteTextTrack({
626 kind: 'captions',
627 label: caption.label,
628 language: caption.language,
629 id: caption.language,
630 src: caption.src
631 }, false)
632 }
633 }
634
635 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
636 private initSmoothProgressBar () {
637 const SeekBar = videojsUntyped.getComponent('SeekBar')
638 SeekBar.prototype.getPercent = function getPercent () {
639 // Allows for smooth scrubbing, when player can't keep up.
640 // const time = (this.player_.scrubbing()) ?
641 // this.player_.getCache().currentTime :
642 // this.player_.currentTime()
643 const time = this.player_.currentTime()
644 const percent = time / this.player_.duration()
645 return percent >= 1 ? 1 : percent
646 }
647 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
648 let newTime = this.calculateDistance(event) * this.player_.duration()
649 if (newTime === this.player_.duration()) {
650 newTime = newTime - 0.1
651 }
652 this.player_.currentTime(newTime)
653 this.update()
654 }
655 }
656 }
657
658 videojs.registerPlugin('peertube', PeerTubePlugin)
659 export { PeerTubePlugin }