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