]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-videojs-plugin.ts
Fix video play on google chrome
[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) {
531ab5b6
C
59 super.handleClick(event)
60
a22bfc3e 61 this.player_.peertube().updateResolution(this.options_.id)
aa8b6df4 62 }
a22bfc3e 63}
aa8b6df4
C
64MenuItem.registerComponent('ResolutionMenuItem', ResolutionMenuItem)
65
a22bfc3e
C
66const MenuButton: VideoJSComponentInterface = videojsUntyped.getComponent('MenuButton')
67class ResolutionMenuButton extends MenuButton {
68 label: HTMLElement
69
339632b4 70 constructor (player: videojs.Player, options) {
aa8b6df4 71 options.label = 'Quality'
a22bfc3e
C
72 super(player, options)
73
74 this.label = document.createElement('span')
aa8b6df4 75
aa8b6df4
C
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
a22bfc3e
C
82 player.peertube().on('videoFileUpdate', () => this.update())
83 }
aa8b6df4 84
a22bfc3e 85 createItems () {
aa8b6df4 86 const menuItems = []
a22bfc3e 87 for (const videoFile of this.player_.peertube().videoFiles) {
aa8b6df4
C
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
a22bfc3e
C
100 }
101
102 update () {
103 if (!this.label) return
aa8b6df4 104
a22bfc3e 105 this.label.innerHTML = this.player_.peertube().getCurrentResolutionLabel()
be6a4802 106 this.hide()
a22bfc3e
C
107 return super.update()
108 }
109
110 buildCSSClass () {
111 return super.buildCSSClass() + ' vjs-resolution-button'
112 }
aa8b6df4 113
a22bfc3e
C
114 dispose () {
115 this.parentNode.removeChild(this)
aa8b6df4 116 }
a22bfc3e 117}
aa8b6df4
C
118MenuButton.registerComponent('ResolutionMenuButton', ResolutionMenuButton)
119
a22bfc3e
C
120const Button: VideoJSComponentInterface = videojsUntyped.getComponent('Button')
121class PeertubeLinkButton extends Button {
aa8b6df4 122
a22bfc3e 123 createEl () {
aa8b6df4
C
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
a22bfc3e 132 }
aa8b6df4 133
a22bfc3e 134 handleClick () {
be6a4802 135 this.player_.pause()
aa8b6df4 136 }
aa8b6df4 137
a22bfc3e
C
138 dispose () {
139 this.parentNode.removeChild(this)
140 }
141}
142Button.registerComponent('PeerTubeLinkButton', PeertubeLinkButton)
be6a4802 143
a22bfc3e
C
144class WebTorrentButton extends Button {
145 createEl () {
be6a4802 146 const div = document.createElement('div')
a06a31c7
C
147 const subDiv = document.createElement('div')
148 div.appendChild(subDiv)
be6a4802
C
149
150 const downloadIcon = document.createElement('span')
151 downloadIcon.classList.add('icon', 'icon-download')
a06a31c7 152 subDiv.appendChild(downloadIcon)
be6a4802
C
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)
a06a31c7 161 subDiv.appendChild(downloadSpeedText)
be6a4802
C
162
163 const uploadIcon = document.createElement('span')
164 uploadIcon.classList.add('icon', 'icon-upload')
a06a31c7 165 subDiv.appendChild(uploadIcon)
be6a4802
C
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)
a06a31c7 174 subDiv.appendChild(uploadSpeedText)
be6a4802
C
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')
a06a31c7
C
181 subDiv.appendChild(peersNumber)
182 subDiv.appendChild(peersText)
be6a4802
C
183
184 div.className = 'vjs-webtorrent'
185 // Hide the stats before we get the info
a86309b4 186 subDiv.className = 'vjs-webtorrent-hidden'
be6a4802 187
a22bfc3e 188 this.player_.peertube().on('torrentInfo', (event, data) => {
be6a4802
C
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
a86309b4 201 subDiv.className = 'vjs-webtorrent-displayed'
be6a4802
C
202 })
203
204 return div
205 }
be6a4802 206
a22bfc3e
C
207 dispose () {
208 this.parentNode.removeChild(this)
209 }
aa8b6df4 210}
a22bfc3e
C
211Button.registerComponent('WebTorrentButton', WebTorrentButton)
212
213const Plugin: VideoJSComponentInterface = videojsUntyped.getPlugin('plugin')
214class PeerTubePlugin extends Plugin {
215 private player: any
216 private currentVideoFile: VideoFile
217 private playerElement: HTMLVideoElement
218 private videoFiles: VideoFile[]
219 private torrent: WebTorrent.Torrent
481d3596 220 private autoplay = false
a22bfc3e 221
339632b4 222 constructor (player: videojs.Player, options: PeertubePluginOptions) {
a22bfc3e
C
223 super(player, options)
224
481d3596
C
225 // Fix canplay event on google chrome by disabling default videojs autoplay
226 this.autoplay = this.player.options_.autoplay
227 this.player.options_.autoplay = false
228
a22bfc3e
C
229 this.videoFiles = options.videoFiles
230
231 // Hack to "simulate" src link in video.js >= 6
232 // Without this, we can't play the video after pausing it
233 // https://github.com/videojs/video.js/blob/master/src/js/player.js#L1633
234 this.player.src = function () {
235 return true
236 }
237
238 this.playerElement = options.playerElement
239
240 this.player.ready(() => {
241 this.initializePlayer(options)
242 this.runTorrentInfoScheduler()
243 })
244 }
245
246 dispose () {
247 // Don't need to destroy renderer, video player will be destroyed
248 this.flushVideoFile(this.currentVideoFile, false)
aa8b6df4
C
249 }
250
a22bfc3e
C
251 getCurrentResolution () {
252 return this.currentVideoFile ? this.currentVideoFile.resolution : -1
aa8b6df4
C
253 }
254
a22bfc3e
C
255 getCurrentResolutionLabel () {
256 return this.currentVideoFile ? this.currentVideoFile.resolutionLabel : ''
aa8b6df4
C
257 }
258
a22bfc3e 259 updateVideoFile (videoFile?: VideoFile, done?: () => void) {
aa8b6df4
C
260 if (done === undefined) {
261 done = () => { /* empty */ }
262 }
263
264 // Pick the first one
265 if (videoFile === undefined) {
a22bfc3e 266 videoFile = this.videoFiles[0]
aa8b6df4
C
267 }
268
269 // Don't add the same video file once again
a22bfc3e 270 if (this.currentVideoFile !== undefined && this.currentVideoFile.magnetUri === videoFile.magnetUri) {
aa8b6df4
C
271 return
272 }
273
a22bfc3e
C
274 const previousVideoFile = this.currentVideoFile
275 this.currentVideoFile = videoFile
aa8b6df4
C
276
277 console.log('Adding ' + videoFile.magnetUri + '.')
a22bfc3e 278 this.torrent = webtorrent.add(videoFile.magnetUri, torrent => {
aa8b6df4
C
279 console.log('Added ' + videoFile.magnetUri + '.')
280
281 this.flushVideoFile(previousVideoFile)
282
283 const options = { autoplay: true, controls: true }
a22bfc3e
C
284 renderVideo(torrent.files[0], this.playerElement, options,(err, renderer) => {
285 if (err) return this.handleError(err)
aa8b6df4
C
286
287 this.renderer = renderer
531ab5b6 288 if (!this.player.paused()) this.player.play().then(done)
481d3596 289 else done()
aa8b6df4
C
290 })
291 })
292
a22bfc3e
C
293 this.torrent.on('error', err => this.handleError(err))
294 this.torrent.on('warning', (err: any) => {
a96aed15 295 // We don't support HTTP tracker but we don't care -> we use the web socket tracker
531ab5b6 296 if (err.message.indexOf('Unsupported tracker protocol') !== -1) return
7dbdc3ba
C
297 // Users don't care about issues with WebRTC, but developers do so log it in the console
298 if (err.message.indexOf('Ice connection failed') !== -1) {
299 console.error(err)
300 return
301 }
a96aed15 302
a22bfc3e 303 return this.handleError(err)
a96aed15 304 })
aa8b6df4 305
a22bfc3e 306 this.trigger('videoFileUpdate')
aa8b6df4
C
307 }
308
a22bfc3e 309 updateResolution (resolution) {
aa8b6df4 310 // Remember player state
a22bfc3e
C
311 const currentTime = this.player.currentTime()
312 const isPaused = this.player.paused()
aa8b6df4 313
531ab5b6
C
314 // Remove poster to have black background
315 this.playerElement.poster = ''
316
aa8b6df4 317 // Hide bigPlayButton
8fa5653a 318 if (!isPaused) {
a22bfc3e 319 this.player.bigPlayButton.hide()
aa8b6df4
C
320 }
321
a22bfc3e
C
322 const newVideoFile = this.videoFiles.find(f => f.resolution === resolution)
323 this.updateVideoFile(newVideoFile, () => {
324 this.player.currentTime(currentTime)
325 this.player.handleTechSeeked_()
aa8b6df4
C
326 })
327 }
328
a22bfc3e 329 flushVideoFile (videoFile: VideoFile, destroyRenderer = true) {
aa8b6df4
C
330 if (videoFile !== undefined && webtorrent.get(videoFile.magnetUri)) {
331 if (destroyRenderer === true) this.renderer.destroy()
332 webtorrent.remove(videoFile.magnetUri)
a22bfc3e 333 console.log('Removed ' + videoFile.magnetUri)
aa8b6df4
C
334 }
335 }
336
a22bfc3e
C
337 setVideoFiles (files: VideoFile[]) {
338 this.videoFiles = files
ed9f9f5f 339
a22bfc3e 340 this.updateVideoFile(undefined, () => this.player.play())
ed9f9f5f
C
341 }
342
a22bfc3e
C
343 private initializePlayer (options: PeertubePluginOptions) {
344 const controlBar = this.player.controlBar
aa8b6df4 345
a22bfc3e 346 const menuButton = new ResolutionMenuButton(this.player, options)
aa8b6df4
C
347 const fullscreenElement = controlBar.fullscreenToggle.el()
348 controlBar.resolutionSwitcher = controlBar.el().insertBefore(menuButton.el(), fullscreenElement)
aa8b6df4
C
349
350 if (options.peerTubeLink === true) {
a22bfc3e 351 const peerTubeLinkButton = new PeertubeLinkButton(this.player)
aa8b6df4 352 controlBar.peerTubeLink = controlBar.el().insertBefore(peerTubeLinkButton.el(), fullscreenElement)
aa8b6df4
C
353 }
354
a22bfc3e 355 const webTorrentButton = new WebTorrentButton(this.player)
be6a4802 356 controlBar.webTorrent = controlBar.el().insertBefore(webTorrentButton.el(), controlBar.progressControl.el())
be6a4802 357
481d3596
C
358 if (this.autoplay === true) {
359 this.updateVideoFile(undefined, () => this.player.play())
aa8b6df4 360 } else {
a22bfc3e 361 this.player.one('play', () => {
481d3596
C
362 this.player.pause()
363 this.updateVideoFile(undefined, () => this.player.play())
4dd551a0 364 })
aa8b6df4 365 }
a22bfc3e 366 }
aa8b6df4 367
a22bfc3e 368 private runTorrentInfoScheduler () {
aa8b6df4 369 setInterval(() => {
a22bfc3e
C
370 if (this.torrent !== undefined) {
371 this.trigger('torrentInfo', {
372 downloadSpeed: this.torrent.downloadSpeed,
373 numPeers: this.torrent.numPeers,
374 uploadSpeed: this.torrent.uploadSpeed
aa8b6df4
C
375 })
376 }
377 }, 1000)
a22bfc3e 378 }
aa8b6df4 379
a22bfc3e
C
380 private handleError (err: Error | string) {
381 return this.player.trigger('customError', { err })
aa8b6df4
C
382 }
383}
a22bfc3e 384videojsUntyped.registerPlugin('peertube', PeerTubePlugin)