]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-videojs-plugin.ts
5fad139b90438cf9aa0efb300c45d65b3f97e79b
[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, VideoJSComponentInterface, videojsUntyped } from './peertube-videojs-typings'
7 import { isMobile, videoFileMaxByResolution, videoFileMinByResolution } 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 renderer
58 private fakeRenderer
59 private autoResolution = true
60 private forbidAutoResolution = false
61 private isAutoResolutionObservation = false
62
63 private videoViewInterval
64 private torrentInfoInterval
65 private autoQualityInterval
66 private addTorrentDelay
67 private qualityObservationTimer
68 private runAutoQualitySchedulerTimer
69
70 private downloadSpeeds: number[] = []
71
72 constructor (player: videojs.Player, options: PeertubePluginOptions) {
73 super(player, options)
74
75 // Disable auto play on iOS
76 this.autoplay = options.autoplay && this.isIOS() === false
77
78 this.startTime = options.startTime
79 this.videoFiles = options.videoFiles
80 this.videoViewUrl = options.videoViewUrl
81 this.videoDuration = options.videoDuration
82
83 this.savePlayerSrcFunction = this.player.src
84 // Hack to "simulate" src link in video.js >= 6
85 // Without this, we can't play the video after pausing it
86 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
87 this.player.src = () => true
88
89 this.playerElement = options.playerElement
90
91 if (this.autoplay === true) this.player.addClass('vjs-has-autoplay')
92
93 this.player.ready(() => {
94 const volume = getStoredVolume()
95 if (volume !== undefined) this.player.volume(volume)
96 const muted = getStoredMute()
97 if (muted !== undefined) this.player.muted(muted)
98
99 this.initializePlayer()
100 this.runTorrentInfoScheduler()
101 this.runViewAdd()
102
103 this.player.one('play', () => {
104 // Don't run immediately scheduler, wait some seconds the TCP connections are made
105 this.runAutoQualitySchedulerTimer = setTimeout(() => {
106 this.runAutoQualityScheduler()
107 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
108 })
109 })
110
111 this.player.on('volumechange', () => {
112 saveVolumeInStore(this.player.volume())
113 saveMuteInStore(this.player.muted())
114 })
115 }
116
117 dispose () {
118 clearTimeout(this.addTorrentDelay)
119 clearTimeout(this.qualityObservationTimer)
120 clearTimeout(this.runAutoQualitySchedulerTimer)
121
122 clearInterval(this.videoViewInterval)
123 clearInterval(this.torrentInfoInterval)
124 clearInterval(this.autoQualityInterval)
125
126 // Don't need to destroy renderer, video player will be destroyed
127 this.flushVideoFile(this.currentVideoFile, false)
128
129 this.destroyFakeRenderer()
130 }
131
132 getCurrentResolutionId () {
133 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
134 }
135
136 getCurrentResolutionLabel () {
137 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
138 }
139
140 updateVideoFile (
141 videoFile?: VideoFile,
142 options: {
143 forcePlay?: boolean,
144 seek?: number,
145 delay?: number
146 } = {},
147 done: () => void = () => { /* empty */ }
148 ) {
149 // Automatically choose the adapted video file
150 if (videoFile === undefined) {
151 const savedAverageBandwidth = getAverageBandwidthInStore()
152 videoFile = savedAverageBandwidth
153 ? this.getAppropriateFile(savedAverageBandwidth)
154 : this.pickAverageVideoFile()
155 }
156
157 // Don't add the same video file once again
158 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
159 return
160 }
161
162 // Do not display error to user because we will have multiple fallback
163 this.disableErrorDisplay()
164
165 this.player.src = () => true
166 const oldPlaybackRate = this.player.playbackRate()
167
168 const previousVideoFile = this.currentVideoFile
169 this.currentVideoFile = videoFile
170
171 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
172 this.player.playbackRate(oldPlaybackRate)
173 return done()
174 })
175
176 this.trigger('videoFileUpdate')
177 }
178
179 addTorrent (
180 magnetOrTorrentUrl: string,
181 previousVideoFile: VideoFile,
182 options: {
183 forcePlay?: boolean,
184 seek?: number,
185 delay?: number
186 },
187 done: Function
188 ) {
189 console.log('Adding ' + magnetOrTorrentUrl + '.')
190
191 const oldTorrent = this.torrent
192 const torrentOptions = {
193 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
194 max: 100
195 })
196 }
197
198 this.torrent = this.webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
199 console.log('Added ' + magnetOrTorrentUrl + '.')
200
201 if (oldTorrent) {
202 // Pause the old torrent
203 oldTorrent.pause()
204 // Pause does not remove actual peers (in particular the webseed peer)
205 oldTorrent.removePeer(oldTorrent['ws'])
206
207 // We use a fake renderer so we download correct pieces of the next file
208 if (options.delay) {
209 const fakeVideoElem = document.createElement('video')
210 renderVideo(torrent.files[0], fakeVideoElem, { autoplay: false, controls: false }, (err, renderer) => {
211 this.fakeRenderer = renderer
212
213 if (err) console.error('Cannot render new torrent in fake video element.', err)
214
215 // Load the future file at the correct time
216 fakeVideoElem.currentTime = this.player.currentTime() + (options.delay / 2000)
217 })
218 }
219 }
220
221 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
222 this.addTorrentDelay = setTimeout(() => {
223 this.destroyFakeRenderer()
224
225 const paused = this.player.paused()
226
227 this.flushVideoFile(previousVideoFile)
228
229 const renderVideoOptions = { autoplay: false, controls: true }
230 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
231 this.renderer = renderer
232
233 if (err) return this.fallbackToHttp(done)
234
235 return this.tryToPlay(err => {
236 if (err) return done(err)
237
238 if (options.seek) this.seek(options.seek)
239 if (options.forcePlay === false && paused === true) this.player.pause()
240 })
241 })
242 }, options.delay || 0)
243 })
244
245 this.torrent.on('error', err => console.error(err))
246
247 this.torrent.on('warning', (err: any) => {
248 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
249 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
250
251 // Users don't care about issues with WebRTC, but developers do so log it in the console
252 if (err.message.indexOf('Ice connection failed') !== -1) {
253 console.log(err)
254 return
255 }
256
257 // Magnet hash is not up to date with the torrent file, add directly the torrent file
258 if (err.message.indexOf('incorrect info hash') !== -1) {
259 console.error('Incorrect info hash detected, falling back to torrent file.')
260 const options = { forcePlay: true }
261 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
262 }
263
264 return console.warn(err)
265 })
266 }
267
268 updateResolution (resolutionId: number, delay = 0) {
269 // Remember player state
270 const currentTime = this.player.currentTime()
271 const isPaused = this.player.paused()
272
273 // Remove poster to have black background
274 this.playerElement.poster = ''
275
276 // Hide bigPlayButton
277 if (!isPaused) {
278 this.player.bigPlayButton.hide()
279 }
280
281 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
282 const options = {
283 forcePlay: false,
284 delay,
285 seek: currentTime + (delay / 1000)
286 }
287 this.updateVideoFile(newVideoFile, options)
288 }
289
290 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
291 if (videoFile !== undefined && this.webtorrent.get(videoFile.magnetUri)) {
292 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
293
294 this.webtorrent.remove(videoFile.magnetUri)
295 console.log('Removed ' + videoFile.magnetUri)
296 }
297 }
298
299 isAutoResolutionOn () {
300 return this.autoResolution
301 }
302
303 enableAutoResolution () {
304 this.autoResolution = true
305 this.trigger('autoResolutionUpdate')
306 }
307
308 disableAutoResolution (forbid = false) {
309 if (forbid === true) this.forbidAutoResolution = true
310
311 this.autoResolution = false
312 this.trigger('autoResolutionUpdate')
313 }
314
315 isAutoResolutionForbidden () {
316 return this.forbidAutoResolution === true
317 }
318
319 getCurrentVideoFile () {
320 return this.currentVideoFile
321 }
322
323 getTorrent () {
324 return this.torrent
325 }
326
327 private tryToPlay (done?: Function) {
328 if (!done) done = function () { /* empty */ }
329
330 const playPromise = this.player.play()
331 if (playPromise !== undefined) {
332 return playPromise.then(done)
333 .catch(err => {
334 if (err.message.indexOf('The play() request was interrupted by a call to pause()') !== -1) {
335 return
336 }
337
338 console.error(err)
339 this.player.pause()
340 this.player.posterImage.show()
341 this.player.removeClass('vjs-has-autoplay')
342 this.player.removeClass('vjs-has-big-play-button-clicked')
343
344 return done()
345 })
346 }
347
348 return done()
349 }
350
351 private seek (time: number) {
352 this.player.currentTime(time)
353 this.player.handleTechSeeked_()
354 }
355
356 private getAppropriateFile (averageDownloadSpeed?: number): VideoFile {
357 if (this.videoFiles === undefined || this.videoFiles.length === 0) return undefined
358 if (this.videoFiles.length === 1) return this.videoFiles[0]
359
360 // Don't change the torrent is the play was ended
361 if (this.torrent && this.torrent.progress === 1 && this.player.ended()) return this.currentVideoFile
362
363 if (!averageDownloadSpeed) averageDownloadSpeed = this.getAndSaveActualDownloadSpeed()
364
365 // Filter videos we can play according to our bandwidth
366 const filteredFiles = this.videoFiles.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 if (isMobile()) this.player.addClass('vjs-is-mobile')
400
401 this.initSmoothProgressBar()
402
403 this.alterInactivity()
404
405 if (this.autoplay === true) {
406 this.player.posterImage.hide()
407
408 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
409 } else {
410 // Don't try on iOS that does not support MediaSource
411 if (this.isIOS()) {
412 this.currentVideoFile = this.pickAverageVideoFile()
413 return this.fallbackToHttp(undefined, false)
414 }
415
416 // Proxy first play
417 const oldPlay = this.player.play.bind(this.player)
418 this.player.play = () => {
419 this.player.addClass('vjs-has-big-play-button-clicked')
420 this.player.play = oldPlay
421
422 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
423 }
424 }
425 }
426
427 private runAutoQualityScheduler () {
428 this.autoQualityInterval = setInterval(() => {
429
430 // Not initialized or in HTTP fallback
431 if (this.torrent === undefined || this.torrent === null) return
432 if (this.isAutoResolutionOn() === false) return
433 if (this.isAutoResolutionObservation === true) return
434
435 const file = this.getAppropriateFile()
436 let changeResolution = false
437 let changeResolutionDelay = 0
438
439 // Lower resolution
440 if (this.isPlayerWaiting() && file.resolution.id < this.currentVideoFile.resolution.id) {
441 console.log('Downgrading automatically the resolution to: %s', file.resolution.label)
442 changeResolution = true
443 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
444 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
445 changeResolution = true
446 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
447 }
448
449 if (changeResolution === true) {
450 this.updateResolution(file.resolution.id, changeResolutionDelay)
451
452 // Wait some seconds in observation of our new resolution
453 this.isAutoResolutionObservation = true
454
455 this.qualityObservationTimer = setTimeout(() => {
456 this.isAutoResolutionObservation = false
457 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
458 }
459 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
460 }
461
462 private isPlayerWaiting () {
463 return this.player && this.player.hasClass('vjs-waiting')
464 }
465
466 private runTorrentInfoScheduler () {
467 this.torrentInfoInterval = setInterval(() => {
468 // Not initialized yet
469 if (this.torrent === undefined) return
470
471 // Http fallback
472 if (this.torrent === null) return this.trigger('torrentInfo', false)
473
474 // this.webtorrent.downloadSpeed because we need to take into account the potential old torrent too
475 if (this.webtorrent.downloadSpeed !== 0) this.downloadSpeeds.push(this.webtorrent.downloadSpeed)
476
477 return this.trigger('torrentInfo', {
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 }, this.CONSTANTS.INFO_SCHEDULER)
485 }
486
487 private runViewAdd () {
488 this.clearVideoViewInterval()
489
490 // After 30 seconds (or 3/4 of the video), add a view to the video
491 let minSecondsToView = 30
492
493 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
494
495 let secondsViewed = 0
496 this.videoViewInterval = setInterval(() => {
497 if (this.player && !this.player.paused()) {
498 secondsViewed += 1
499
500 if (secondsViewed > minSecondsToView) {
501 this.clearVideoViewInterval()
502
503 this.addViewToVideo().catch(err => console.error(err))
504 }
505 }
506 }, 1000)
507 }
508
509 private clearVideoViewInterval () {
510 if (this.videoViewInterval !== undefined) {
511 clearInterval(this.videoViewInterval)
512 this.videoViewInterval = undefined
513 }
514 }
515
516 private addViewToVideo () {
517 if (!this.videoViewUrl) return Promise.resolve(undefined)
518
519 return fetch(this.videoViewUrl, { method: 'POST' })
520 }
521
522 private fallbackToHttp (done?: Function, play = true) {
523 this.disableAutoResolution(true)
524
525 this.flushVideoFile(this.currentVideoFile, true)
526 this.torrent = null
527
528 // Enable error display now this is our last fallback
529 this.player.one('error', () => this.enableErrorDisplay())
530
531 const httpUrl = this.currentVideoFile.fileUrl
532 this.player.src = this.savePlayerSrcFunction
533 this.player.src(httpUrl)
534 if (play) this.tryToPlay()
535
536 if (done) return done()
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 isIOS () {
552 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
553 }
554
555 private alterInactivity () {
556 let saveInactivityTimeout: number
557
558 const disableInactivity = () => {
559 saveInactivityTimeout = this.player.options_.inactivityTimeout
560 this.player.options_.inactivityTimeout = 0
561 }
562 const enableInactivity = () => {
563 this.player.options_.inactivityTimeout = saveInactivityTimeout
564 }
565
566 const settingsDialog = this.player.children_.find(c => c.name_ === 'SettingsDialog')
567
568 this.player.controlBar.on('mouseenter', () => disableInactivity())
569 settingsDialog.on('mouseenter', () => disableInactivity())
570 this.player.controlBar.on('mouseleave', () => enableInactivity())
571 settingsDialog.on('mouseleave', () => enableInactivity())
572 }
573
574 private pickAverageVideoFile () {
575 if (this.videoFiles.length === 1) return this.videoFiles[0]
576
577 return this.videoFiles[Math.floor(this.videoFiles.length / 2)]
578 }
579
580 private destroyFakeRenderer () {
581 if (this.fakeRenderer) {
582 if (this.fakeRenderer.destroy) {
583 try {
584 this.fakeRenderer.destroy()
585 } catch (err) {
586 console.log('Cannot destroy correctly fake renderer.', err)
587 }
588 }
589 this.fakeRenderer = undefined
590 }
591 }
592
593 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
594 private initSmoothProgressBar () {
595 const SeekBar = videojsUntyped.getComponent('SeekBar')
596 SeekBar.prototype.getPercent = function getPercent () {
597 // Allows for smooth scrubbing, when player can't keep up.
598 // const time = (this.player_.scrubbing()) ?
599 // this.player_.getCache().currentTime :
600 // this.player_.currentTime()
601 const time = this.player_.currentTime()
602 const percent = time / this.player_.duration()
603 return percent >= 1 ? 1 : percent
604 }
605 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
606 let newTime = this.calculateDistance(event) * this.player_.duration()
607 if (newTime === this.player_.duration()) {
608 newTime = newTime - 0.1
609 }
610 this.player_.currentTime(newTime)
611 this.update()
612 }
613 }
614 }
615
616 videojs.registerPlugin('peertube', PeerTubePlugin)
617 export { PeerTubePlugin }