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