]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
Migrate client to eslint
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
1 import 'videojs-hotkeys/videojs.hotkeys'
2 import 'videojs-dock'
3 import 'videojs-contextmenu-pt'
4 import 'videojs-contrib-quality-levels'
5 import './upnext/end-card'
6 import './upnext/upnext-plugin'
7 import './stats/stats-card'
8 import './stats/stats-plugin'
9 import './bezels/bezels-plugin'
10 import './peertube-plugin'
11 import './videojs-components/next-previous-video-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-link-button'
14 import './videojs-components/peertube-load-progress-bar'
15 import './videojs-components/resolution-menu-button'
16 import './videojs-components/resolution-menu-item'
17 import './videojs-components/settings-dialog'
18 import './videojs-components/settings-menu-button'
19 import './videojs-components/settings-menu-item'
20 import './videojs-components/settings-panel'
21 import './videojs-components/settings-panel-child'
22 import './videojs-components/theater-button'
23 import './playlist/playlist-plugin'
24 import videojs from 'video.js'
25 import { HlsJsEngineSettings } from '@peertube/p2p-media-loader-hlsjs'
26 import { PluginsManager } from '@root-helpers/plugins-manager'
27 import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
28 import { isDefaultLocale } from '@shared/core-utils/i18n'
29 import { VideoFile } from '@shared/models'
30 import { copyToClipboard } from '../../root-helpers/utils'
31 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
32 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
33 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
34 import { getAverageBandwidthInStore, getStoredP2PEnabled, saveAverageBandwidth } from './peertube-player-local-storage'
35 import {
36 NextPreviousVideoButtonOptions,
37 P2PMediaLoaderPluginOptions,
38 PeerTubeLinkButtonOptions,
39 PlayerNetworkInfo,
40 PlaylistPluginOptions,
41 UserWatching,
42 VideoJSCaption,
43 VideoJSPluginOptions
44 } from './peertube-videojs-typings'
45 import { TranslationsManager } from './translations-manager'
46 import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isSafari } from './utils'
47
48 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
49 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
50
51 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
52 // Change Captions to Subtitles/CC
53 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
54 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
55 CaptionsButton.prototype.label_ = ' '
56
57 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
58
59 export type WebtorrentOptions = {
60 videoFiles: VideoFile[]
61 }
62
63 export type P2PMediaLoaderOptions = {
64 playlistUrl: string
65 segmentsSha256Url: string
66 trackerAnnounce: string[]
67 redundancyBaseUrls: string[]
68 videoFiles: VideoFile[]
69 }
70
71 export interface CustomizationOptions {
72 startTime: number | string
73 stopTime: number | string
74
75 controls?: boolean
76 muted?: boolean
77 loop?: boolean
78 subtitle?: string
79 resume?: string
80
81 peertubeLink: boolean
82 }
83
84 export interface CommonOptions extends CustomizationOptions {
85 playerElement: HTMLVideoElement
86 onPlayerElementChange: (element: HTMLVideoElement) => void
87
88 autoplay: boolean
89
90 nextVideo?: () => void
91 hasNextVideo?: () => boolean
92
93 previousVideo?: () => void
94 hasPreviousVideo?: () => boolean
95
96 playlist?: PlaylistPluginOptions
97
98 videoDuration: number
99 enableHotkeys: boolean
100 inactivityTimeout: number
101 poster: string
102
103 theaterButton: boolean
104 captions: boolean
105
106 videoViewUrl: string
107 embedUrl: string
108 embedTitle: string
109
110 isLive: boolean
111
112 language?: string
113
114 videoCaptions: VideoJSCaption[]
115
116 videoUUID: string
117 videoShortUUID: string
118
119 userWatching?: UserWatching
120
121 serverUrl: string
122 }
123
124 export type PeertubePlayerManagerOptions = {
125 common: CommonOptions
126 webtorrent: WebtorrentOptions
127 p2pMediaLoader?: P2PMediaLoaderOptions
128
129 pluginsManager: PluginsManager
130 }
131
132 export class PeertubePlayerManager {
133 private static playerElementClassName: string
134 private static onPlayerChange: (player: videojs.Player) => void
135 private static alreadyPlayed = false
136 private static pluginsManager: PluginsManager
137
138 static initState () {
139 PeertubePlayerManager.alreadyPlayed = false
140 }
141
142 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
143 this.pluginsManager = options.pluginsManager
144
145 let p2pMediaLoader: any
146
147 this.onPlayerChange = onPlayerChange
148 this.playerElementClassName = options.common.playerElement.className
149
150 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
151 if (mode === 'p2p-media-loader') {
152 [ p2pMediaLoader ] = await Promise.all([
153 import('@peertube/p2p-media-loader-hlsjs'),
154 import('./p2p-media-loader/p2p-media-loader-plugin')
155 ])
156 }
157
158 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
159
160 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
161
162 const self = this
163 return new Promise(res => {
164 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
165 const player = this
166
167 let alreadyFallback = false
168
169 player.tech(true).one('error', () => {
170 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
171 alreadyFallback = true
172 })
173
174 player.one('error', () => {
175 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
176 alreadyFallback = true
177 })
178
179 player.one('play', () => {
180 PeertubePlayerManager.alreadyPlayed = true
181 })
182
183 self.addContextMenu({
184 mode,
185 player,
186 videoShortUUID: options.common.videoShortUUID,
187 videoEmbedUrl: options.common.embedUrl,
188 videoEmbedTitle: options.common.embedTitle
189 })
190
191 player.bezels()
192 player.stats({
193 videoUUID: options.common.videoUUID,
194 videoIsLive: options.common.isLive,
195 mode
196 })
197
198 player.on('p2pInfo', (_, data: PlayerNetworkInfo) => {
199 if (data.source !== 'p2p-media-loader' || isNaN(data.bandwidthEstimate)) return
200
201 saveAverageBandwidth(data.bandwidthEstimate)
202 })
203
204 return res(player)
205 })
206 })
207 }
208
209 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
210 if (currentMode === 'webtorrent') return
211
212 console.log('Fallback to webtorrent.')
213
214 const newVideoElement = document.createElement('video')
215 newVideoElement.className = this.playerElementClassName
216
217 // VideoJS wraps our video element inside a div
218 let currentParentPlayerElement = options.common.playerElement.parentNode
219 // Fix on IOS, don't ask me why
220 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
221
222 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
223
224 options.common.playerElement = newVideoElement
225 options.common.onPlayerElementChange(newVideoElement)
226
227 player.dispose()
228
229 await import('./webtorrent/webtorrent-plugin')
230
231 const mode = 'webtorrent'
232 const videojsOptions = await this.getVideojsOptions(mode, options)
233
234 const self = this
235 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
236 const player = this
237
238 self.addContextMenu({
239 mode,
240 player,
241 videoShortUUID: options.common.videoShortUUID,
242 videoEmbedUrl: options.common.embedUrl,
243 videoEmbedTitle: options.common.embedTitle
244 })
245
246 PeertubePlayerManager.onPlayerChange(player)
247 })
248 }
249
250 private static async getVideojsOptions (
251 mode: PlayerMode,
252 options: PeertubePlayerManagerOptions,
253 p2pMediaLoaderModule?: any
254 ): Promise<videojs.PlayerOptions> {
255 const commonOptions = options.common
256 const isHLS = mode === 'p2p-media-loader'
257
258 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
259 const html5 = {
260 preloadTextTracks: false
261 }
262
263 const plugins: VideoJSPluginOptions = {
264 peertube: {
265 mode,
266 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
267 videoViewUrl: commonOptions.videoViewUrl,
268 videoDuration: commonOptions.videoDuration,
269 userWatching: commonOptions.userWatching,
270 subtitle: commonOptions.subtitle,
271 videoCaptions: commonOptions.videoCaptions,
272 stopTime: commonOptions.stopTime,
273 isLive: commonOptions.isLive,
274 videoUUID: commonOptions.videoUUID
275 }
276 }
277
278 if (commonOptions.playlist) {
279 plugins.playlist = commonOptions.playlist
280 }
281
282 if (commonOptions.enableHotkeys === true) {
283 PeertubePlayerManager.addHotkeysOptions(plugins)
284 }
285
286 if (isHLS) {
287 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
288
289 Object.assign(html5, hlsjs.html5)
290 }
291
292 if (mode === 'webtorrent') {
293 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
294
295 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
296 autoplay = false
297 }
298
299 const videojsOptions = {
300 html5,
301
302 // We don't use text track settings for now
303 textTrackSettings: false as any, // FIXME: typings
304 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
305 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
306
307 muted: commonOptions.muted !== undefined
308 ? commonOptions.muted
309 : undefined, // Undefined so the player knows it has to check the local storage
310
311 autoplay: this.getAutoPlayValue(autoplay),
312
313 poster: commonOptions.poster,
314 inactivityTimeout: commonOptions.inactivityTimeout,
315 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
316
317 plugins,
318
319 controlBar: {
320 children: this.getControlBarChildren(mode, {
321 videoShortUUID: commonOptions.videoShortUUID,
322
323 captions: commonOptions.captions,
324 peertubeLink: commonOptions.peertubeLink,
325 theaterButton: commonOptions.theaterButton,
326
327 nextVideo: commonOptions.nextVideo,
328 hasNextVideo: commonOptions.hasNextVideo,
329
330 previousVideo: commonOptions.previousVideo,
331 hasPreviousVideo: commonOptions.hasPreviousVideo
332 }) as any // FIXME: typings
333 }
334 }
335
336 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
337 Object.assign(videojsOptions, { language: commonOptions.language })
338 }
339
340 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
341 }
342
343 private static addP2PMediaLoaderOptions (
344 plugins: VideoJSPluginOptions,
345 options: PeertubePlayerManagerOptions,
346 p2pMediaLoaderModule: any
347 ) {
348 const p2pMediaLoaderOptions = options.p2pMediaLoader
349 const commonOptions = options.common
350
351 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
352 .filter(t => t.startsWith('ws'))
353
354 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
355
356 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
357 redundancyUrlManager,
358 type: 'application/x-mpegURL',
359 startTime: commonOptions.startTime,
360 src: p2pMediaLoaderOptions.playlistUrl
361 }
362
363 let consumeOnly = false
364 // FIXME: typings
365 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
366 console.log('We are on a cellular connection: disabling seeding.')
367 consumeOnly = true
368 }
369
370 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
371 loader: {
372 trackerAnnounce,
373 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
374 rtcConfig: getRtcConfig(),
375 requiredSegmentsPriority: 1,
376 simultaneousHttpDownloads: 1,
377 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
378 useP2P: getStoredP2PEnabled(),
379 consumeOnly
380 },
381 segments: {
382 swarmId: p2pMediaLoaderOptions.playlistUrl
383 }
384 }
385
386 const hlsjs = {
387 levelLabelHandler: (level: { height: number, width: number }) => {
388 const resolution = Math.min(level.height || 0, level.width || 0)
389
390 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
391 // We don't have files for live videos
392 if (!file) return level.height
393
394 let label = file.resolution.label
395 if (file.fps >= 50) label += file.fps
396
397 return label
398 },
399 html5: {
400 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderModule, p2pMediaLoaderConfig)
401 }
402 }
403
404 const toAssign = { p2pMediaLoader, hlsjs }
405 Object.assign(plugins, toAssign)
406
407 return toAssign
408 }
409
410 private static getHLSOptions (p2pMediaLoaderModule: any, p2pMediaLoaderConfig: HlsJsEngineSettings) {
411 const base = {
412 capLevelToPlayerSize: true,
413 autoStartLoad: false,
414 liveSyncDurationCount: 5,
415
416 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
417 }
418
419 const averageBandwidth = getAverageBandwidthInStore()
420 if (!averageBandwidth) return base
421
422 return {
423 ...base,
424
425 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
426 startLevel: -1,
427 testBandwidth: false,
428 debug: false
429 }
430 }
431
432 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
433 const commonOptions = options.common
434 const webtorrentOptions = options.webtorrent
435 const p2pMediaLoaderOptions = options.p2pMediaLoader
436
437 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
438
439 const webtorrent = {
440 autoplay,
441 videoDuration: commonOptions.videoDuration,
442 playerElement: commonOptions.playerElement,
443 videoFiles: webtorrentOptions.videoFiles.length !== 0
444 ? webtorrentOptions.videoFiles
445 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
446 : p2pMediaLoaderOptions?.videoFiles || [],
447 startTime: commonOptions.startTime
448 }
449
450 Object.assign(plugins, { webtorrent })
451 }
452
453 private static getControlBarChildren (mode: PlayerMode, options: {
454 videoShortUUID: string
455
456 peertubeLink: boolean
457 theaterButton: boolean
458 captions: boolean
459
460 nextVideo?: () => void
461 hasNextVideo?: () => boolean
462
463 previousVideo?: () => void
464 hasPreviousVideo?: () => boolean
465 }) {
466 const settingEntries = []
467 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
468
469 // Keep an order
470 settingEntries.push('playbackRateMenuButton')
471 if (options.captions === true) settingEntries.push('captionsButton')
472 settingEntries.push('resolutionMenuButton')
473
474 const children = {}
475
476 if (options.previousVideo) {
477 const buttonOptions: NextPreviousVideoButtonOptions = {
478 type: 'previous',
479 handler: options.previousVideo,
480 isDisabled: () => {
481 if (!options.hasPreviousVideo) return false
482
483 return !options.hasPreviousVideo()
484 }
485 }
486
487 Object.assign(children, {
488 previousVideoButton: buttonOptions
489 })
490 }
491
492 Object.assign(children, { playToggle: {} })
493
494 if (options.nextVideo) {
495 const buttonOptions: NextPreviousVideoButtonOptions = {
496 type: 'next',
497 handler: options.nextVideo,
498 isDisabled: () => {
499 if (!options.hasNextVideo) return false
500
501 return !options.hasNextVideo()
502 }
503 }
504
505 Object.assign(children, {
506 nextVideoButton: buttonOptions
507 })
508 }
509
510 Object.assign(children, {
511 currentTimeDisplay: {},
512 timeDivider: {},
513 durationDisplay: {},
514 liveDisplay: {},
515
516 flexibleWidthSpacer: {},
517 progressControl: {
518 children: {
519 seekBar: {
520 children: {
521 [loadProgressBar]: {},
522 mouseTimeDisplay: {},
523 playProgressBar: {}
524 }
525 }
526 }
527 },
528
529 p2PInfoButton: {},
530
531 muteToggle: {},
532 volumeControl: {},
533
534 settingsButton: {
535 setup: {
536 maxHeightOffset: 40
537 },
538 entries: settingEntries
539 }
540 })
541
542 if (options.peertubeLink === true) {
543 Object.assign(children, {
544 peerTubeLinkButton: { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
545 })
546 }
547
548 if (options.theaterButton === true) {
549 Object.assign(children, {
550 theaterButton: {}
551 })
552 }
553
554 Object.assign(children, {
555 fullscreenToggle: {}
556 })
557
558 return children
559 }
560
561 private static addContextMenu (options: {
562 mode: PlayerMode
563 player: videojs.Player
564 videoShortUUID: string
565 videoEmbedUrl: string
566 videoEmbedTitle: string
567 }) {
568 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
569
570 const content = () => {
571 const isLoopEnabled = player.options_['loop']
572 const items = [
573 {
574 icon: 'repeat',
575 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
576 listener: function () {
577 player.options_['loop'] = !isLoopEnabled
578 }
579 },
580 {
581 label: player.localize('Copy the video URL'),
582 listener: function () {
583 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
584 }
585 },
586 {
587 label: player.localize('Copy the video URL at the current time'),
588 listener: function (this: videojs.Player) {
589 const url = buildVideoLink({ shortUUID: videoShortUUID })
590
591 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
592 }
593 },
594 {
595 icon: 'code',
596 label: player.localize('Copy embed code'),
597 listener: () => {
598 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
599 }
600 }
601 ]
602
603 if (mode === 'webtorrent') {
604 items.push({
605 label: player.localize('Copy magnet URI'),
606 listener: function (this: videojs.Player) {
607 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
608 }
609 })
610 }
611
612 items.push({
613 icon: 'info',
614 label: player.localize('Stats for nerds'),
615 listener: () => {
616 player.stats().show()
617 }
618 })
619
620 return items.map(i => ({
621 ...i,
622 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
623 }))
624 }
625
626 // adding the menu
627 player.contextmenuUI({ content })
628 }
629
630 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
631 const isNaked = (event: KeyboardEvent, key: string) =>
632 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
633
634 Object.assign(plugins, {
635 hotkeys: {
636 skipInitialFocus: true,
637 enableInactiveFocus: false,
638 captureDocumentHotkeys: true,
639 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
640 const tagName = e.tagName.toLowerCase()
641 return e.id === 'content' || tagName === 'body' || tagName === 'video'
642 },
643
644 enableVolumeScroll: false,
645 enableModifiersForNumbers: false,
646
647 rewindKey: function (event: KeyboardEvent) {
648 return isNaked(event, 'ArrowLeft')
649 },
650
651 forwardKey: function (event: KeyboardEvent) {
652 return isNaked(event, 'ArrowRight')
653 },
654
655 fullscreenKey: function (event: KeyboardEvent) {
656 // fullscreen with the f key or Ctrl+Enter
657 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
658 },
659
660 customKeys: {
661 increasePlaybackRateKey: {
662 key: function (event: KeyboardEvent) {
663 return isNaked(event, '>')
664 },
665 handler: function (player: videojs.Player) {
666 const newValue = Math.min(player.playbackRate() + 0.1, 5)
667 player.playbackRate(parseFloat(newValue.toFixed(2)))
668 }
669 },
670 decreasePlaybackRateKey: {
671 key: function (event: KeyboardEvent) {
672 return isNaked(event, '<')
673 },
674 handler: function (player: videojs.Player) {
675 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
676 player.playbackRate(parseFloat(newValue.toFixed(2)))
677 }
678 },
679 frameByFrame: {
680 key: function (event: KeyboardEvent) {
681 return isNaked(event, '.')
682 },
683 handler: function (player: videojs.Player) {
684 player.pause()
685 // Calculate movement distance (assuming 30 fps)
686 const dist = 1 / 30
687 player.currentTime(player.currentTime() + dist)
688 }
689 }
690 }
691 }
692 })
693 }
694
695 private static getAutoPlayValue (autoplay: any) {
696 if (autoplay !== true) return autoplay
697
698 // On first play, disable autoplay to avoid issues
699 // But if the player already played videos, we can safely autoplay next ones
700 if (isIOS() || isSafari()) {
701 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
702 }
703
704 return 'play'
705 }
706 }
707
708 // ############################################################################
709
710 export {
711 videojs
712 }