]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-videojs-plugin.ts
5ccfdce36b8ad127dac80119206a6bff6bcee690
[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 { VideoFile } from '../../../../shared/models/videos/video.model'
6 import { renderVideo } from './video-renderer'
7
8 declare module 'video.js' {
9 interface Player {
10 peertube (): PeerTubePlugin
11 }
12 }
13
14 interface VideoJSComponentInterface {
15 _player: videojs.Player
16
17 new (player: videojs.Player, options?: any)
18
19 registerComponent (name: string, obj: any)
20 }
21
22 type PeertubePluginOptions = {
23 videoFiles: VideoFile[]
24 playerElement: HTMLVideoElement
25 peerTubeLink: boolean
26 }
27
28 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
29 // Don't import all Angular stuff, just copy the code with shame
30 const dictionaryBytes: Array<{max: number, type: string}> = [
31 { max: 1024, type: 'B' },
32 { max: 1048576, type: 'KB' },
33 { max: 1073741824, type: 'MB' },
34 { max: 1.0995116e12, type: 'GB' }
35 ]
36 function bytes (value) {
37 const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
38 const calc = Math.floor(value / (format.max / 1024)).toString()
39
40 return [ calc, format.type ]
41 }
42
43 // videojs typings don't have some method we need
44 const videojsUntyped = videojs as any
45 const webtorrent = new WebTorrent({ dht: false })
46
47 const MenuItem: VideoJSComponentInterface = videojsUntyped.getComponent('MenuItem')
48 class ResolutionMenuItem extends MenuItem {
49
50 constructor (player: videojs.Player, options) {
51 options.selectable = true
52 super(player, options)
53
54 const currentResolution = this.player_.peertube().getCurrentResolution()
55 this.selected(this.options_.id === currentResolution)
56 }
57
58 handleClick (event) {
59 super.handleClick(event)
60
61 this.player_.peertube().updateResolution(this.options_.id)
62 }
63 }
64 MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
65
66 const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
67 class ResolutionMenuButton extends MenuButton {
68 label: HTMLElement
69
70 constructor (player: videojs.Player, options) {
71 options.label = 'Quality'
72 super(player, options)
73
74 this.label = document.createElement('span')
75
76 this.el().setAttribute('aria-label', 'Quality')
77 this.controlText('Quality')
78
79 videojsUntyped.dom.addClass(this.label, 'vjs-resolution-button-label')
80 this.el().appendChild(this.label)
81
82 player.peertube().on('videoFileUpdate', () => this.update())
83 }
84
85 createItems () {
86 const menuItems = []
87 for (const videoFile of this.player_.peertube().videoFiles) {
88 menuItems.push(new ResolutionMenuItem(
89 this.player_,
90 {
91 id: videoFile.resolution,
92 label: videoFile.resolutionLabel,
93 src: videoFile.magnetUri,
94 selected: videoFile.resolution === this.currentSelection
95 })
96 )
97 }
98
99 return menuItems
100 }
101
102 update () {
103 if (!this.label) return
104
105 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
106 this.hide()
107 return super.update()
108 }
109
110 buildCSSClass () {
111 return super.buildCSSClass() + ' vjs-resolution-button'
112 }
113
114 dispose () {
115 this.parentNode.removeChild(this)
116 }
117 }
118 MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
119
120 const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
121 class PeertubeLinkButton extends Button {
122
123 createEl () {
124 const link = document.createElement('a')
125 link.href = window.location.href.replace('embed', 'watch')
126 link.innerHTML = 'PeerTube'
127 link.title = 'Go to the video page'
128 link.className = 'vjs-peertube-link'
129 link.target = '_blank'
130
131 return link
132 }
133
134 handleClick () {
135 this.player_.pause()
136 }
137
138 dispose () {
139 this.parentNode.removeChild(this)
140 }
141 }
142 Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
143
144 class WebTorrentButton extends Button {
145 createEl () {
146 const div = document.createElement('div')
147 const subDiv = document.createElement('div')
148 div.appendChild(subDiv)
149
150 const downloadIcon = document.createElement('span')
151 downloadIcon.classList.add('icon', 'icon-download')
152 subDiv.appendChild(downloadIcon)
153
154 const downloadSpeedText = document.createElement('span')
155 downloadSpeedText.classList.add('download-speed-text')
156 const downloadSpeedNumber = document.createElement('span')
157 downloadSpeedNumber.classList.add('download-speed-number')
158 const downloadSpeedUnit = document.createElement('span')
159 downloadSpeedText.appendChild(downloadSpeedNumber)
160 downloadSpeedText.appendChild(downloadSpeedUnit)
161 subDiv.appendChild(downloadSpeedText)
162
163 const uploadIcon = document.createElement('span')
164 uploadIcon.classList.add('icon', 'icon-upload')
165 subDiv.appendChild(uploadIcon)
166
167 const uploadSpeedText = document.createElement('span')
168 uploadSpeedText.classList.add('upload-speed-text')
169 const uploadSpeedNumber = document.createElement('span')
170 uploadSpeedNumber.classList.add('upload-speed-number')
171 const uploadSpeedUnit = document.createElement('span')
172 uploadSpeedText.appendChild(uploadSpeedNumber)
173 uploadSpeedText.appendChild(uploadSpeedUnit)
174 subDiv.appendChild(uploadSpeedText)
175
176 const peersText = document.createElement('span')
177 peersText.textContent = ' peers'
178 peersText.classList.add('peers-text')
179 const peersNumber = document.createElement('span')
180 peersNumber.classList.add('peers-number')
181 subDiv.appendChild(peersNumber)
182 subDiv.appendChild(peersText)
183
184 div.className = 'vjs-webtorrent'
185 // Hide the stats before we get the info
186 subDiv.className = 'vjs-webtorrent-hidden'
187
188 this.player_.peertube().on('torrentInfo', (event, data) => {
189 const downloadSpeed = bytes(data.downloadSpeed)
190 const uploadSpeed = bytes(data.uploadSpeed)
191 const numPeers = data.numPeers
192
193 downloadSpeedNumber.textContent = downloadSpeed[0]
194 downloadSpeedUnit.textContent = ' ' + downloadSpeed[1]
195
196 uploadSpeedNumber.textContent = uploadSpeed[0]
197 uploadSpeedUnit.textContent = ' ' + uploadSpeed[1]
198
199 peersNumber.textContent = numPeers
200
201 subDiv.className = 'vjs-webtorrent-displayed'
202 })
203
204 return div
205 }
206
207 dispose () {
208 this.parentNode.removeChild(this)
209 }
210 }
211 Button.registerComponent('WebTorrentButton', WebTorrentButton)
212
213 const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
214 class PeerTubePlugin extends Plugin {
215 private player: any
216 private currentVideoFile: VideoFile
217 private playerElement: HTMLVideoElement
218 private videoFiles: VideoFile[]
219 private torrent: WebTorrent.Torrent
220
221 constructor (player: videojs.Player, options: PeertubePluginOptions) {
222 super(player, options)
223
224 this.videoFiles = options.videoFiles
225
226 // Hack to "simulate" src link in video.js >= 6
227 // Without this, we can't play the video after pausing it
228 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
229 this.player.src = function () {
230 return true
231 }
232
233 this.playerElement = options.playerElement
234
235 this.player.ready(() => {
236 this.initializePlayer(options)
237 this.runTorrentInfoScheduler()
238 })
239 }
240
241 dispose () {
242 // Don't need to destroy renderer, video player will be destroyed
243 this.flushVideoFile(this.currentVideoFile, false)
244 }
245
246 getCurrentResolution () {
247 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
248 }
249
250 getCurrentResolutionLabel () {
251 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
252 }
253
254 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
255 if (done === undefined) {
256 done = () => { /* empty */ }
257 }
258
259 // Pick the first one
260 if (videoFile === undefined) {
261 videoFile = this.videoFiles[0]
262 }
263
264 // Don't add the same video file once again
265 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
266 return
267 }
268
269 const previousVideoFile = this.currentVideoFile
270 this.currentVideoFile = videoFile
271
272 console.log('Adding ' + videoFile.magnetUri + '.')
273 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
274 console.log('Added ' + videoFile.magnetUri + '.')
275
276 this.flushVideoFile(previousVideoFile)
277
278 const options = { autoplay: true, controls: true }
279 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
280 if (err) return this.handleError(err)
281
282 this.renderer = renderer
283 if (!this.player.paused()) this.player.play().then(done)
284 })
285 })
286
287 this.torrent.on('error', err => this.handleError(err))
288 this.torrent.on('warning', (err: any) => {
289 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
290 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
291 // Users don't care about issues with WebRTC, but developers do so log it in the console
292 if (err.message.indexOf('Ice connection failed') !== -1) {
293 console.error(err)
294 return
295 }
296
297 return this.handleError(err)
298 })
299
300 this.trigger('videoFileUpdate')
301 }
302
303 updateResolution (resolution) {
304 // Remember player state
305 const currentTime = this.player.currentTime()
306 const isPaused = this.player.paused()
307
308 // Remove poster to have black background
309 this.playerElement.poster = ''
310
311 // Hide bigPlayButton
312 if (!isPaused) {
313 this.player.bigPlayButton.hide()
314 }
315
316 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
317 this.updateVideoFile(newVideoFile, () => {
318 this.player.currentTime(currentTime)
319 this.player.handleTechSeeked_()
320 })
321 }
322
323 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
324 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
325 if (destroyRenderer === true) this.renderer.destroy()
326 webtorrent.remove(videoFile.magnetUri)
327 console.log('Removed ' + videoFile.magnetUri)
328 }
329 }
330
331 setVideoFiles (files: VideoFile[]) {
332 this.videoFiles = files
333
334 this.updateVideoFile(undefined, () => this.player.play())
335 }
336
337 private initializePlayer (options: PeertubePluginOptions) {
338 const controlBar = this.player.controlBar
339
340 const menuButton = new ResolutionMenuButton(this.player, options)
341 const fullscreenElement = controlBar.fullscreenToggle.el()
342 controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
343
344 if (options.peerTubeLink === true) {
345 const peerTubeLinkButton = new PeertubeLinkButton(this.player)
346 controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
347 }
348
349 const webTorrentButton = new WebTorrentButton(this.player)
350 controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
351
352 if (this.player.options_.autoplay === true) {
353 this.updateVideoFile()
354 } else {
355 this.player.one('play', () => {
356 // On firefox, we need to wait to load the video before playing
357 if (navigator.userAgent.toLowerCase().indexOf('firefox') !== -1) {
358 this.player.pause()
359 this.updateVideoFile(undefined, () => this.player.play())
360 return
361 }
362
363 this.updateVideoFile(undefined)
364 })
365 }
366 }
367
368 private runTorrentInfoScheduler () {
369 setInterval(() => {
370 if (this.torrent !== undefined) {
371 this.trigger('torrentInfo', {
372 downloadSpeed: this.torrent.downloadSpeed,
373 numPeers: this.torrent.numPeers,
374 uploadSpeed: this.torrent.uploadSpeed
375 })
376 }
377 }, 1000)
378 }
379
380 private handleError (err: Error | string) {
381 return this.player.trigger('customError', { err })
382 }
383 }
384 videojsUntyped.registerPlugin('peertube', PeerTubePlugin)