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