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