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