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