]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - 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
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 (
130 videoFile?: VideoFile,
131 options: {
132 forcePlay?: boolean,
133 seek?: number,
134 delay?: number
135 } = {},
136 done: () => void = () => { /* empty */ }
137 ) {
138 // Automatically choose the adapted video file
139 if (videoFile === undefined) {
140 const savedAverageBandwidth = getAverageBandwidth()
141 videoFile = savedAverageBandwidth
142 ? this.getAppropriateFile(savedAverageBandwidth)
143 : this.videoFiles[0]
144 }
145
146 // Don't add the same video file once again
147 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
148 return
149 }
150
151 // Do not display error to user because we will have multiple fallback
152 this.disableErrorDisplay()
153
154 this.player.src = () => true
155 const oldPlaybackRate = this.player.playbackRate()
156
157 const previousVideoFile = this.currentVideoFile
158 this.currentVideoFile = videoFile
159
160 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, options, () => {
161 this.player.playbackRate(oldPlaybackRate)
162 return done()
163 })
164
165 this.trigger('videoFileUpdate')
166 }
167
168 addTorrent (
169 magnetOrTorrentUrl: string,
170 previousVideoFile: VideoFile,
171 options: {
172 forcePlay?: boolean,
173 seek?: number,
174 delay?: number
175 },
176 done: Function
177 ) {
178 console.log('Adding ' + magnetOrTorrentUrl + '.')
179
180 const oldTorrent = this.torrent
181 const torrentOptions = {
182 store: (chunkLength, storeOpts) => new CacheChunkStore(new PeertubeChunkStore(chunkLength, storeOpts), {
183 max: 100
184 })
185 }
186
187 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrentOptions, torrent => {
188 console.log('Added ' + magnetOrTorrentUrl + '.')
189
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 }
196
197 // Render the video in a few seconds? (on resolution change for example, we wait some seconds of the new video resolution)
198 this.addTorrentDelay = setTimeout(() => {
199 const paused = this.player.paused()
200
201 this.flushVideoFile(previousVideoFile)
202
203 const renderVideoOptions = { autoplay: false, controls: true }
204 renderVideo(torrent.files[0], this.playerElement, renderVideoOptions,(err, renderer) => {
205 this.renderer = renderer
206
207 if (err) return this.fallbackToHttp(done)
208
209 return this.tryToPlay(err => {
210 if (err) return done(err)
211
212 if (options.seek) this.seek(options.seek)
213 if (options.forcePlay === false && paused === true) this.player.pause()
214 })
215 })
216 }, options.delay || 0)
217 })
218
219 this.torrent.on('error', err => this.handleError(err))
220
221 this.torrent.on('warning', (err: any) => {
222 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
223 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
224
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 }
230
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.')
234 const options = { forcePlay: true }
235 return this.addTorrent(this.torrent['xs'], previousVideoFile, options, done)
236 }
237
238 return this.handleError(err)
239 })
240 }
241
242 updateResolution (resolutionId: number, delay = 0) {
243 // Remember player state
244 const currentTime = this.player.currentTime()
245 const isPaused = this.player.paused()
246
247 // Remove poster to have black background
248 this.playerElement.poster = ''
249
250 // Hide bigPlayButton
251 if (!isPaused) {
252 this.player.bigPlayButton.hide()
253 }
254
255 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
256 const options = {
257 forcePlay: false,
258 delay,
259 seek: currentTime
260 }
261 this.updateVideoFile(newVideoFile, options)
262 }
263
264 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
265 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
266 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
267
268 webtorrent.remove(videoFile.magnetUri)
269 console.log('Removed ' + videoFile.magnetUri)
270 }
271 }
272
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
287 getCurrentVideoFile () {
288 return this.currentVideoFile
289 }
290
291 getTorrent () {
292 return this.torrent
293 }
294
295 private tryToPlay (done?: Function) {
296 if (!done) done = function () { /* empty */ }
297
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
314 private seek (time: number) {
315 this.player.currentTime(time)
316 this.player.handleTechSeeked_()
317 }
318
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]
322
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()
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
333 // If this is for a higher resolution or an initial load: add a margin
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
347 private getAndSaveActualDownloadSpeed () {
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)
357
358 return averageBandwidth
359 }
360
361 private initializePlayer () {
362 this.initSmoothProgressBar()
363
364 this.alterInactivity()
365
366 if (this.autoplay === true) {
367 this.player.posterImage.hide()
368
369 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
370 } else {
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
377 // Proxy first play
378 const oldPlay = this.player.play.bind(this.player)
379 this.player.play = () => {
380 this.player.addClass('vjs-has-big-play-button-clicked')
381 this.player.play = oldPlay
382
383 this.updateVideoFile(undefined, { forcePlay: true, seek: this.startTime })
384 }
385 }
386 }
387
388 private runAutoQualityScheduler () {
389 this.autoQualityInterval = setInterval(() => {
390
391 // Not initialized or in HTTP fallback
392 if (this.torrent === undefined || this.torrent === null) return
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
404 } else if (file.resolution.id > this.currentVideoFile.resolution.id) { // Higher resolution
405 console.log('Upgrading automatically the resolution to: %s', file.resolution.label)
406 changeResolution = true
407 changeResolutionDelay = this.CONSTANTS.AUTO_QUALITY_HIGHER_RESOLUTION_DELAY
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
415
416 this.qualityObservationTimer = setTimeout(() => {
417 this.isAutoResolutionObservation = false
418 }, this.CONSTANTS.AUTO_QUALITY_OBSERVATION_TIME)
419 }
420 }, this.CONSTANTS.AUTO_QUALITY_SCHEDULER)
421 }
422
423 private isPlayerWaiting () {
424 return this.player && this.player.hasClass('vjs-waiting')
425 }
426
427 private runTorrentInfoScheduler () {
428 this.torrentInfoInterval = setInterval(() => {
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
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
438 return this.trigger('torrentInfo', {
439 downloadSpeed: this.torrent.downloadSpeed,
440 numPeers: this.torrent.numPeers,
441 uploadSpeed: this.torrent.uploadSpeed
442 })
443 }, this.CONSTANTS.INFO_SCHEDULER)
444 }
445
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
452 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
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
479 private fallbackToHttp (done?: Function, play = true) {
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)
489 if (play) this.tryToPlay()
490
491 if (done) return done()
492 }
493
494 private handleError (err: Error | string) {
495 return this.player.trigger('customError', { err })
496 }
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 }
505
506 private isIOS () {
507 return !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)
508 }
509
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 = () => {
518 this.player.options_.inactivityTimeout = saveInactivityTimeout
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
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 }
550 }
551
552 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)
553 export { PeerTubePlugin }