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