]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-videojs-plugin.ts
Improve player progress bar
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-videojs-plugin.ts
CommitLineData
aa8b6df4
C
1// Big thanks to: https://github.com/kmoskwiak/videojs-resolution-switcher
2
63c4db6d 3import * as videojs from 'video.js'
aa8b6df4 4import * as WebTorrent from 'webtorrent'
09700934 5import { VideoConstant, VideoResolution } from '../../../../shared/models/videos'
b6827820 6import { VideoFile } from '../../../../shared/models/videos/video.model'
aa8b6df4 7import { renderVideo } from './video-renderer'
be6a4802 8
339632b4
C
9declare module 'video.js' {
10 interface Player {
11 peertube (): PeerTubePlugin
12 }
13}
14
a22bfc3e 15interface VideoJSComponentInterface {
339632b4 16 _player: videojs.Player
a22bfc3e 17
339632b4 18 new (player: videojs.Player, options?: any)
a22bfc3e
C
19
20 registerComponent (name: string, obj: any)
21}
22
a22bfc3e
C
23type PeertubePluginOptions = {
24 videoFiles: VideoFile[]
25 playerElement: HTMLVideoElement
8cac1b64 26 videoViewUrl: string
3bcfff7f 27 videoDuration: number
a22bfc3e
C
28}
29
be6a4802
C
30// https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
31// Don't import all Angular stuff, just copy the code with shame
32const dictionaryBytes: Array<{max: number, type: string}> = [
33 { max: 1024, type: 'B' },
34 { max: 1048576, type: 'KB' },
35 { max: 1073741824, type: 'MB' },
36 { max: 1.0995116e12, type: 'GB' }
37]
38function bytes (value) {
39 const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
40 const calc = Math.floor(value / (format.max / 1024)).toString()
41
42 return [ calc, format.type ]
43}
aa8b6df4
C
44
45// videojs typings don't have some method we need
46const videojsUntyped = videojs as any
d402fb5b
C
47const webtorrent = new WebTorrent({
48 tracker: {
49 rtcConfig: {
50 iceServers: [
51 {
52 urls: 'stun:stun.stunprotocol.org'
53 },
54 {
55 urls: 'stun:stun.framasoft.org'
d402fb5b
C
56 }
57 ]
58 }
59 },
60 dht: false
61})
aa8b6df4 62
a22bfc3e
C
63const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
64class ResolutionMenuItem extends MenuItem {
65
339632b4 66 constructor (player: videojs.Player, options) {
aa8b6df4 67 options.selectable = true
a22bfc3e 68 super(player, options)
aa8b6df4 69
09700934
C
70 const currentResolutionId = this.player_.peertube().getCurrentResolutionId()
71 this.selected(this.options_.id === currentResolutionId)
a22bfc3e 72 }
aa8b6df4 73
a22bfc3e 74 handleClick (event) {
531ab5b6
C
75 super.handleClick(event)
76
a22bfc3e 77 this.player_.peertube().updateResolution(this.options_.id)
aa8b6df4 78 }
a22bfc3e 79}
aa8b6df4
C
80MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
81
a22bfc3e
C
82const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
83class ResolutionMenuButton extends MenuButton {
84 label: HTMLElement
85
339632b4 86 constructor (player: videojs.Player, options) {
aa8b6df4 87 options.label = 'Quality'
a22bfc3e
C
88 super(player, options)
89
90 this.label = document.createElement('span')
aa8b6df4 91
aa8b6df4
C
92 this.el().setAttribute('aria-label', 'Quality')
93 this.controlText('Quality')
94
95 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
96 this.el().appendChild(this.label)
97
a22bfc3e
C
98 player.peertube().on('videoFileUpdate', () => this.update())
99 }
aa8b6df4 100
a22bfc3e 101 createItems () {
aa8b6df4 102 const menuItems = []
a22bfc3e 103 for (const videoFile of this.player_.peertube().videoFiles) {
aa8b6df4
C
104 menuItems.push(new ResolutionMenuItem(
105 this.player_,
106 {
09700934
C
107 id: videoFile.resolution.id,
108 label: videoFile.resolution.label,
aa8b6df4 109 src: videoFile.magnetUri,
09700934 110 selected: videoFile.resolution.id === this.currentSelectionId
aa8b6df4
C
111 })
112 )
113 }
114
115 return menuItems
a22bfc3e
C
116 }
117
118 update () {
119 if (!this.label) return
aa8b6df4 120
a22bfc3e 121 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
be6a4802 122 this.hide()
a22bfc3e
C
123 return super.update()
124 }
125
126 buildCSSClass () {
127 return super.buildCSSClass() + ' vjs-resolution-button'
128 }
a22bfc3e 129}
aa8b6df4
C
130MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
131
a22bfc3e 132const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
3ec8dc09 133class PeerTubeLinkButton extends Button {
aa8b6df4 134
a22bfc3e 135 createEl () {
aa8b6df4
C
136 const link = document.createElement('a')
137 link.href = window.location.href.replace('embed', 'watch')
138 link.innerHTML = 'PeerTube'
139 link.title = 'Go to the video page'
140 link.className = 'vjs-peertube-link'
141 link.target = '_blank'
142
143 return link
a22bfc3e 144 }
aa8b6df4 145
a22bfc3e 146 handleClick () {
be6a4802 147 this.player_.pause()
aa8b6df4 148 }
a22bfc3e 149}
3ec8dc09 150Button.registerComponent('PeerTubeLinkButton', PeerTubeLinkButton)
be6a4802 151
a22bfc3e
C
152class WebTorrentButton extends Button {
153 createEl () {
be6a4802 154 const div = document.createElement('div')
bf5685f0
C
155 const subDivWebtorrent = document.createElement('div')
156 div.appendChild(subDivWebtorrent)
be6a4802
C
157
158 const downloadIcon = document.createElement('span')
159 downloadIcon.classList.add('icon', 'icon-download')
bf5685f0 160 subDivWebtorrent.appendChild(downloadIcon)
be6a4802
C
161
162 const downloadSpeedText = document.createElement('span')
163 downloadSpeedText.classList.add('download-speed-text')
164 const downloadSpeedNumber = document.createElement('span')
165 downloadSpeedNumber.classList.add('download-speed-number')
166 const downloadSpeedUnit = document.createElement('span')
167 downloadSpeedText.appendChild(downloadSpeedNumber)
168 downloadSpeedText.appendChild(downloadSpeedUnit)
bf5685f0 169 subDivWebtorrent.appendChild(downloadSpeedText)
be6a4802
C
170
171 const uploadIcon = document.createElement('span')
172 uploadIcon.classList.add('icon', 'icon-upload')
bf5685f0 173 subDivWebtorrent.appendChild(uploadIcon)
be6a4802
C
174
175 const uploadSpeedText = document.createElement('span')
176 uploadSpeedText.classList.add('upload-speed-text')
177 const uploadSpeedNumber = document.createElement('span')
178 uploadSpeedNumber.classList.add('upload-speed-number')
179 const uploadSpeedUnit = document.createElement('span')
180 uploadSpeedText.appendChild(uploadSpeedNumber)
181 uploadSpeedText.appendChild(uploadSpeedUnit)
bf5685f0 182 subDivWebtorrent.appendChild(uploadSpeedText)
be6a4802
C
183
184 const peersText = document.createElement('span')
be6a4802
C
185 peersText.classList.add('peers-text')
186 const peersNumber = document.createElement('span')
187 peersNumber.classList.add('peers-number')
bf5685f0
C
188 subDivWebtorrent.appendChild(peersNumber)
189 subDivWebtorrent.appendChild(peersText)
be6a4802 190
bf5685f0 191 div.className = 'vjs-peertube'
be6a4802 192 // Hide the stats before we get the info
bf5685f0
C
193 subDivWebtorrent.className = 'vjs-peertube-hidden'
194
195 const subDivHttp = document.createElement('div')
196 subDivHttp.className = 'vjs-peertube-hidden'
197 const subDivHttpText = document.createElement('span')
198 subDivHttpText.classList.add('peers-number')
199 subDivHttpText.textContent = 'HTTP'
200 const subDivFallbackText = document.createElement('span')
201 subDivFallbackText.classList.add('peers-text')
202 subDivFallbackText.textContent = ' fallback'
203
204 subDivHttp.appendChild(subDivHttpText)
205 subDivHttp.appendChild(subDivFallbackText)
206 div.appendChild(subDivHttp)
be6a4802 207
a22bfc3e 208 this.player_.peertube().on('torrentInfo', (event, data) => {
bf5685f0
C
209 // We are in HTTP fallback
210 if (!data) {
211 subDivHttp.className = 'vjs-peertube-displayed'
212 subDivWebtorrent.className = 'vjs-peertube-hidden'
213
214 return
215 }
216
be6a4802
C
217 const downloadSpeed = bytes(data.downloadSpeed)
218 const uploadSpeed = bytes(data.uploadSpeed)
219 const numPeers = data.numPeers
220
bf5685f0
C
221 downloadSpeedNumber.textContent = downloadSpeed[ 0 ]
222 downloadSpeedUnit.textContent = ' ' + downloadSpeed[ 1 ]
be6a4802 223
bf5685f0
C
224 uploadSpeedNumber.textContent = uploadSpeed[ 0 ]
225 uploadSpeedUnit.textContent = ' ' + uploadSpeed[ 1 ]
be6a4802
C
226
227 peersNumber.textContent = numPeers
bf5685f0 228 peersText.textContent = ' peers'
be6a4802 229
bf5685f0
C
230 subDivHttp.className = 'vjs-peertube-hidden'
231 subDivWebtorrent.className = 'vjs-peertube-displayed'
be6a4802
C
232 })
233
234 return div
235 }
aa8b6df4 236}
a22bfc3e
C
237Button.registerComponent('WebTorrentButton', WebTorrentButton)
238
239const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
240class PeerTubePlugin extends Plugin {
241 private player: any
242 private currentVideoFile: VideoFile
243 private playerElement: HTMLVideoElement
244 private videoFiles: VideoFile[]
245 private torrent: WebTorrent.Torrent
481d3596 246 private autoplay = false
8cac1b64 247 private videoViewUrl: string
3bcfff7f 248 private videoDuration: number
8cac1b64 249 private videoViewInterval
3bcfff7f 250 private torrentInfoInterval
bf5685f0 251 private savePlayerSrcFunction: Function
a22bfc3e 252
339632b4 253 constructor (player: videojs.Player, options: PeertubePluginOptions) {
a22bfc3e
C
254 super(player, options)
255
481d3596
C
256 // Fix canplay event on google chrome by disabling default videojs autoplay
257 this.autoplay = this.player.options_.autoplay
258 this.player.options_.autoplay = false
259
a22bfc3e 260 this.videoFiles = options.videoFiles
8cac1b64 261 this.videoViewUrl = options.videoViewUrl
3bcfff7f 262 this.videoDuration = options.videoDuration
a22bfc3e 263
bf5685f0 264 this.savePlayerSrcFunction = this.player.src
a22bfc3e
C
265 // Hack to "simulate" src link in video.js >= 6
266 // Without this, we can't play the video after pausing it
267 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
bf5685f0 268 this.player.src = () => true
a22bfc3e
C
269
270 this.playerElement = options.playerElement
271
272 this.player.ready(() => {
0dcf9a14 273 this.initializePlayer()
a22bfc3e 274 this.runTorrentInfoScheduler()
3bcfff7f 275 this.runViewAdd()
a22bfc3e
C
276 })
277 }
278
279 dispose () {
3bcfff7f
C
280 clearInterval(this.videoViewInterval)
281 clearInterval(this.torrentInfoInterval)
282
a22bfc3e
C
283 // Don't need to destroy renderer, video player will be destroyed
284 this.flushVideoFile(this.currentVideoFile, false)
aa8b6df4
C
285 }
286
09700934
C
287 getCurrentResolutionId () {
288 return this.currentVideoFile ? this.currentVideoFile.resolution.id : -1
aa8b6df4
C
289 }
290
a22bfc3e 291 getCurrentResolutionLabel () {
09700934 292 return this.currentVideoFile ? this.currentVideoFile.resolution.label : ''
aa8b6df4
C
293 }
294
a22bfc3e 295 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
aa8b6df4
C
296 if (done === undefined) {
297 done = () => { /* empty */ }
298 }
299
300 // Pick the first one
301 if (videoFile === undefined) {
a22bfc3e 302 videoFile = this.videoFiles[0]
aa8b6df4
C
303 }
304
305 // Don't add the same video file once again
a22bfc3e 306 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
aa8b6df4
C
307 return
308 }
309
bf5685f0
C
310 // Do not display error to user because we will have multiple fallbacks
311 this.disableErrorDisplay()
1198a08c 312
bf5685f0 313 this.player.src = () => true
1198a08c 314 this.player.playbackRate(1)
bf5685f0 315
a22bfc3e
C
316 const previousVideoFile = this.currentVideoFile
317 this.currentVideoFile = videoFile
aa8b6df4 318
a216c623
C
319 this.addTorrent(this.currentVideoFile.magnetUri, previousVideoFile, done)
320
321 this.trigger('videoFileUpdate')
322 }
323
324 addTorrent (magnetOrTorrentUrl: string, previousVideoFile: VideoFile, done: Function) {
325 console.log('Adding ' + magnetOrTorrentUrl + '.')
326
327 this.torrent = webtorrent.add(magnetOrTorrentUrl, torrent => {
328 console.log('Added ' + magnetOrTorrentUrl + '.')
aa8b6df4
C
329
330 this.flushVideoFile(previousVideoFile)
331
332 const options = { autoplay: true, controls: true }
a22bfc3e 333 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
0dcf9a14
C
334 this.renderer = renderer
335
bf5685f0 336 if (err) return this.fallbackToHttp()
aa8b6df4 337
3bcfff7f
C
338 if (!this.player.paused()) {
339 const playPromise = this.player.play()
340 if (playPromise !== undefined) return playPromise.then(done)
341
342 return done()
343 }
344
345 return done()
aa8b6df4
C
346 })
347 })
348
a22bfc3e 349 this.torrent.on('error', err => this.handleError(err))
a216c623 350
a22bfc3e 351 this.torrent.on('warning', (err: any) => {
a96aed15 352 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
531ab5b6 353 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
a216c623 354
7dbdc3ba
C
355 // Users don't care about issues with WebRTC, but developers do so log it in the console
356 if (err.message.indexOf('Ice connection failed') !== -1) {
357 console.error(err)
358 return
359 }
a96aed15 360
a216c623
C
361 // Magnet hash is not up to date with the torrent file, add directly the torrent file
362 if (err.message.indexOf('incorrect info hash') !== -1) {
363 console.error('Incorrect info hash detected, falling back to torrent file.')
364 return this.addTorrent(this.torrent['xs'], previousVideoFile, done)
365 }
366
a22bfc3e 367 return this.handleError(err)
a96aed15 368 })
aa8b6df4
C
369 }
370
09700934 371 updateResolution (resolutionId: number) {
aa8b6df4 372 // Remember player state
a22bfc3e
C
373 const currentTime = this.player.currentTime()
374 const isPaused = this.player.paused()
aa8b6df4 375
531ab5b6
C
376 // Remove poster to have black background
377 this.playerElement.poster = ''
378
aa8b6df4 379 // Hide bigPlayButton
8fa5653a 380 if (!isPaused) {
a22bfc3e 381 this.player.bigPlayButton.hide()
aa8b6df4
C
382 }
383
09700934 384 const newVideoFile = this.videoFiles.find(f => f.resolution.id === resolutionId)
a22bfc3e
C
385 this.updateVideoFile(newVideoFile, () => {
386 this.player.currentTime(currentTime)
387 this.player.handleTechSeeked_()
aa8b6df4
C
388 })
389 }
390
a22bfc3e 391 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
aa8b6df4 392 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
bf5685f0
C
393 if (destroyRenderer === true && this.renderer && this.renderer.destroy) this.renderer.destroy()
394
aa8b6df4 395 webtorrent.remove(videoFile.magnetUri)
a22bfc3e 396 console.log('Removed ' + videoFile.magnetUri)
aa8b6df4
C
397 }
398 }
399
3bcfff7f 400 setVideoFiles (files: VideoFile[], videoViewUrl: string, videoDuration: number) {
8cac1b64 401 this.videoViewUrl = videoViewUrl
3bcfff7f 402 this.videoDuration = videoDuration
a22bfc3e 403 this.videoFiles = files
ed9f9f5f 404
8cac1b64 405 // Re run view add for the new video
3bcfff7f 406 this.runViewAdd()
a22bfc3e 407 this.updateVideoFile(undefined, () => this.player.play())
ed9f9f5f
C
408 }
409
0dcf9a14 410 private initializePlayer () {
e993ecb3
C
411 this.initSmoothProgressBar()
412
481d3596
C
413 if (this.autoplay === true) {
414 this.updateVideoFile(undefined, () => this.player.play())
aa8b6df4 415 } else {
a22bfc3e 416 this.player.one('play', () => {
481d3596
C
417 this.player.pause()
418 this.updateVideoFile(undefined, () => this.player.play())
4dd551a0 419 })
aa8b6df4 420 }
a22bfc3e 421 }
aa8b6df4 422
a22bfc3e 423 private runTorrentInfoScheduler () {
3bcfff7f 424 this.torrentInfoInterval = setInterval(() => {
bf5685f0
C
425 // Not initialized yet
426 if (this.torrent === undefined) return
427
428 // Http fallback
429 if (this.torrent === null) return this.trigger('torrentInfo', false)
430
431 return this.trigger('torrentInfo', {
432 downloadSpeed: this.torrent.downloadSpeed,
433 numPeers: this.torrent.numPeers,
434 uploadSpeed: this.torrent.uploadSpeed
435 })
aa8b6df4 436 }, 1000)
a22bfc3e 437 }
aa8b6df4 438
8cac1b64
C
439 private runViewAdd () {
440 this.clearVideoViewInterval()
441
442 // After 30 seconds (or 3/4 of the video), add a view to the video
443 let minSecondsToView = 30
444
3bcfff7f 445 if (this.videoDuration < minSecondsToView) minSecondsToView = (this.videoDuration * 3) / 4
8cac1b64
C
446
447 let secondsViewed = 0
448 this.videoViewInterval = setInterval(() => {
449 if (this.player && !this.player.paused()) {
450 secondsViewed += 1
451
452 if (secondsViewed > minSecondsToView) {
453 this.clearVideoViewInterval()
454
455 this.addViewToVideo().catch(err => console.error(err))
456 }
457 }
458 }, 1000)
459 }
460
461 private clearVideoViewInterval () {
462 if (this.videoViewInterval !== undefined) {
463 clearInterval(this.videoViewInterval)
464 this.videoViewInterval = undefined
465 }
466 }
467
468 private addViewToVideo () {
469 return fetch(this.videoViewUrl, { method: 'POST' })
470 }
471
bf5685f0
C
472 private fallbackToHttp () {
473 this.flushVideoFile(this.currentVideoFile, true)
474 this.torrent = null
475
476 // Enable error display now this is our last fallback
477 this.player.one('error', () => this.enableErrorDisplay())
478
479 const httpUrl = this.currentVideoFile.fileUrl
480 this.player.src = this.savePlayerSrcFunction
481 this.player.src(httpUrl)
482 this.player.play()
483 }
484
a22bfc3e
C
485 private handleError (err: Error | string) {
486 return this.player.trigger('customError', { err })
aa8b6df4 487 }
bf5685f0
C
488
489 private enableErrorDisplay () {
490 this.player.addClass('vjs-error-display-enabled')
491 }
492
493 private disableErrorDisplay () {
494 this.player.removeClass('vjs-error-display-enabled')
495 }
e993ecb3
C
496
497 // Thanks: https://github.com/videojs/video.js/issues/4460#issuecomment-312861657
498 private initSmoothProgressBar () {
499 const SeekBar = videojsUntyped.getComponent('SeekBar')
500 SeekBar.prototype.getPercent = function getPercent () {
501 // Allows for smooth scrubbing, when player can't keep up.
502 // const time = (this.player_.scrubbing()) ?
503 // this.player_.getCache().currentTime :
504 // this.player_.currentTime()
505 const time = this.player_.currentTime()
506 const percent = time / this.player_.duration()
507 return percent >= 1 ? 1 : percent
508 }
509 SeekBar.prototype.handleMouseMove = function handleMouseMove (event) {
510 let newTime = this.calculateDistance(event) * this.player_.duration()
511 if (newTime === this.player_.duration()) {
512 newTime = newTime - 0.1
513 }
514 this.player_.currentTime(newTime)
515 this.update()
516 }
517 }
aa8b6df4 518}
a22bfc3e 519videojsUntyped.registerPlugin('peertube', PeerTubePlugin)