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