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