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