1 import 'videojs-hotkeys/videojs.hotkeys'
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 { PluginsManager } from '@root-helpers/plugins-manager'
26 import { isDefaultLocale } from '@shared/core-utils/i18n'
27 import { VideoFile } from '@shared/models'
28 import { copyToClipboard } from '../../root-helpers/utils'
29 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
30 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
31 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
32 import { getStoredP2PEnabled } from './peertube-player-local-storage'
34 NextPreviousVideoButtonOptions,
35 P2PMediaLoaderPluginOptions,
36 PeerTubeLinkButtonOptions,
37 PlaylistPluginOptions,
41 } from './peertube-videojs-typings'
42 import { TranslationsManager } from './translations-manager'
43 import { buildVideoLink, buildVideoOrPlaylistEmbed, decorateVideoLink, getRtcConfig, isIOS, isSafari } from './utils'
45 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
46 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
48 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
49 // Change Captions to Subtitles/CC
50 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
51 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
52 CaptionsButton.prototype.label_ = ' '
54 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
56 export type WebtorrentOptions = {
57 videoFiles: VideoFile[]
60 export type P2PMediaLoaderOptions = {
62 segmentsSha256Url: string
63 trackerAnnounce: string[]
64 redundancyBaseUrls: string[]
65 videoFiles: VideoFile[]
68 export interface CustomizationOptions {
69 startTime: number | string
70 stopTime: number | string
81 export interface CommonOptions extends CustomizationOptions {
82 playerElement: HTMLVideoElement
83 onPlayerElementChange: (element: HTMLVideoElement) => void
87 nextVideo?: () => void
88 hasNextVideo?: () => boolean
90 previousVideo?: () => void
91 hasPreviousVideo?: () => boolean
93 playlist?: PlaylistPluginOptions
96 enableHotkeys: boolean
97 inactivityTimeout: number
100 theaterButton: boolean
111 videoCaptions: VideoJSCaption[]
114 videoShortUUID: string
116 userWatching?: UserWatching
121 export type PeertubePlayerManagerOptions = {
122 common: CommonOptions
123 webtorrent: WebtorrentOptions
124 p2pMediaLoader?: P2PMediaLoaderOptions
126 pluginsManager: PluginsManager
129 export class PeertubePlayerManager {
130 private static playerElementClassName: string
131 private static onPlayerChange: (player: videojs.Player) => void
132 private static alreadyPlayed = false
133 private static pluginsManager: PluginsManager
135 static initState () {
136 PeertubePlayerManager.alreadyPlayed = false
139 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
140 this.pluginsManager = options.pluginsManager
142 let p2pMediaLoader: any
144 this.onPlayerChange = onPlayerChange
145 this.playerElementClassName = options.common.playerElement.className
147 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
148 if (mode === 'p2p-media-loader') {
149 [ p2pMediaLoader ] = await Promise.all([
150 import('p2p-media-loader-hlsjs'),
151 import('./p2p-media-loader/p2p-media-loader-plugin')
155 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
157 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
160 return new Promise(res => {
161 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
164 let alreadyFallback = false
166 player.tech(true).one('error', () => {
167 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
168 alreadyFallback = true
171 player.one('error', () => {
172 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
173 alreadyFallback = true
176 player.one('play', () => {
177 PeertubePlayerManager.alreadyPlayed = true
180 self.addContextMenu({
183 videoShortUUID: options.common.videoShortUUID,
184 videoEmbedUrl: options.common.embedUrl,
185 videoEmbedTitle: options.common.embedTitle
190 videoUUID: options.common.videoUUID,
191 videoIsLive: options.common.isLive,
200 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
201 if (currentMode === 'webtorrent') return
203 console.log('Fallback to webtorrent.')
205 const newVideoElement = document.createElement('video')
206 newVideoElement.className = this.playerElementClassName
208 // VideoJS wraps our video element inside a div
209 let currentParentPlayerElement = options.common.playerElement.parentNode
210 // Fix on IOS, don't ask me why
211 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
213 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
215 options.common.playerElement = newVideoElement
216 options.common.onPlayerElementChange(newVideoElement)
220 await import('./webtorrent/webtorrent-plugin')
222 const mode = 'webtorrent'
223 const videojsOptions = await this.getVideojsOptions(mode, options)
226 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
229 self.addContextMenu({
232 videoShortUUID: options.common.videoShortUUID,
233 videoEmbedUrl: options.common.embedUrl,
234 videoEmbedTitle: options.common.embedTitle
237 PeertubePlayerManager.onPlayerChange(player)
241 private static async getVideojsOptions (
243 options: PeertubePlayerManagerOptions,
244 p2pMediaLoaderModule?: any
245 ): Promise<videojs.PlayerOptions> {
246 const commonOptions = options.common
247 const isHLS = mode === 'p2p-media-loader'
249 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
251 preloadTextTracks: false
254 const plugins: VideoJSPluginOptions = {
257 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
258 videoViewUrl: commonOptions.videoViewUrl,
259 videoDuration: commonOptions.videoDuration,
260 userWatching: commonOptions.userWatching,
261 subtitle: commonOptions.subtitle,
262 videoCaptions: commonOptions.videoCaptions,
263 stopTime: commonOptions.stopTime,
264 isLive: commonOptions.isLive,
265 videoUUID: commonOptions.videoUUID
269 if (commonOptions.playlist) {
270 plugins.playlist = commonOptions.playlist
273 if (commonOptions.enableHotkeys === true) {
274 PeertubePlayerManager.addHotkeysOptions(plugins)
278 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
280 Object.assign(html5, hlsjs.html5)
283 if (mode === 'webtorrent') {
284 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
286 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
290 const videojsOptions = {
293 // We don't use text track settings for now
294 textTrackSettings: false as any, // FIXME: typings
295 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
296 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
298 muted: commonOptions.muted !== undefined
299 ? commonOptions.muted
300 : undefined, // Undefined so the player knows it has to check the local storage
302 autoplay: this.getAutoPlayValue(autoplay),
304 poster: commonOptions.poster,
305 inactivityTimeout: commonOptions.inactivityTimeout,
306 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
311 children: this.getControlBarChildren(mode, {
312 videoShortUUID: commonOptions.videoShortUUID,
314 captions: commonOptions.captions,
315 peertubeLink: commonOptions.peertubeLink,
316 theaterButton: commonOptions.theaterButton,
318 nextVideo: commonOptions.nextVideo,
319 hasNextVideo: commonOptions.hasNextVideo,
321 previousVideo: commonOptions.previousVideo,
322 hasPreviousVideo: commonOptions.hasPreviousVideo
323 }) as any // FIXME: typings
327 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
328 Object.assign(videojsOptions, { language: commonOptions.language })
331 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
334 private static addP2PMediaLoaderOptions (
335 plugins: VideoJSPluginOptions,
336 options: PeertubePlayerManagerOptions,
337 p2pMediaLoaderModule: any
339 const p2pMediaLoaderOptions = options.p2pMediaLoader
340 const commonOptions = options.common
342 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
343 .filter(t => t.startsWith('ws'))
345 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
347 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
348 redundancyUrlManager,
349 type: 'application/x-mpegURL',
350 startTime: commonOptions.startTime,
351 src: p2pMediaLoaderOptions.playlistUrl
354 let consumeOnly = false
356 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
357 console.log('We are on a cellular connection: disabling seeding.')
361 const p2pMediaLoaderConfig = {
364 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
365 rtcConfig: getRtcConfig(),
366 requiredSegmentsPriority: 1,
367 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
368 useP2P: getStoredP2PEnabled(),
372 swarmId: p2pMediaLoaderOptions.playlistUrl
376 levelLabelHandler: (level: { height: number, width: number }) => {
377 const resolution = Math.min(level.height || 0, level.width || 0)
379 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
380 // We don't have files for live videos
381 if (!file) return level.height
383 let label = file.resolution.label
384 if (file.fps >= 50) label += file.fps
390 capLevelToPlayerSize: true,
391 autoStartLoad: false,
392 liveSyncDurationCount: 5,
393 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
398 const toAssign = { p2pMediaLoader, hlsjs }
399 Object.assign(plugins, toAssign)
404 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
405 const commonOptions = options.common
406 const webtorrentOptions = options.webtorrent
407 const p2pMediaLoaderOptions = options.p2pMediaLoader
409 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
415 videoDuration: commonOptions.videoDuration,
416 playerElement: commonOptions.playerElement,
417 videoFiles: webtorrentOptions.videoFiles.length !== 0
418 ? webtorrentOptions.videoFiles
419 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
420 : p2pMediaLoaderOptions?.videoFiles || [],
421 startTime: commonOptions.startTime
424 Object.assign(plugins, { webtorrent })
427 private static getControlBarChildren (mode: PlayerMode, options: {
428 videoShortUUID: string
430 peertubeLink: boolean
431 theaterButton: boolean
435 hasNextVideo?: () => boolean
437 previousVideo?: Function
438 hasPreviousVideo?: () => boolean
440 const settingEntries = []
441 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
444 settingEntries.push('playbackRateMenuButton')
445 if (options.captions === true) settingEntries.push('captionsButton')
446 settingEntries.push('resolutionMenuButton')
450 if (options.previousVideo) {
451 const buttonOptions: NextPreviousVideoButtonOptions = {
453 handler: options.previousVideo,
455 if (!options.hasPreviousVideo) return false
457 return !options.hasPreviousVideo()
461 Object.assign(children, {
462 'previousVideoButton': buttonOptions
466 Object.assign(children, { playToggle: {} })
468 if (options.nextVideo) {
469 const buttonOptions: NextPreviousVideoButtonOptions = {
471 handler: options.nextVideo,
473 if (!options.hasNextVideo) return false
475 return !options.hasNextVideo()
479 Object.assign(children, {
480 'nextVideoButton': buttonOptions
484 Object.assign(children, {
485 'currentTimeDisplay': {},
487 'durationDisplay': {},
490 'flexibleWidthSpacer': {},
495 [loadProgressBar]: {},
496 'mouseTimeDisplay': {},
497 'playProgressBar': {}
512 entries: settingEntries
516 if (options.peertubeLink === true) {
517 Object.assign(children, {
518 'peerTubeLinkButton': { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
522 if (options.theaterButton === true) {
523 Object.assign(children, {
528 Object.assign(children, {
529 'fullscreenToggle': {}
535 private static addContextMenu (options: {
537 player: videojs.Player
538 videoShortUUID: string
539 videoEmbedUrl: string
540 videoEmbedTitle: string
542 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
544 const content = () => {
545 const isLoopEnabled = player.options_['loop']
549 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
550 listener: function () {
551 player.options_['loop'] = !isLoopEnabled
555 label: player.localize('Copy the video URL'),
556 listener: function () {
557 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
561 label: player.localize('Copy the video URL at the current time'),
562 listener: function (this: videojs.Player) {
563 const url = buildVideoLink({ shortUUID: videoShortUUID })
565 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
570 label: player.localize('Copy embed code'),
572 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
577 if (mode === 'webtorrent') {
579 label: player.localize('Copy magnet URI'),
580 listener: function (this: videojs.Player) {
581 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
588 label: player.localize('Stats for nerds'),
590 player.stats().show()
594 return items.map(i => ({
596 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
601 player.contextmenuUI({ content })
604 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
605 const isNaked = (event: KeyboardEvent, key: string) =>
606 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
608 Object.assign(plugins, {
610 skipInitialFocus: true,
611 enableInactiveFocus: false,
612 captureDocumentHotkeys: true,
613 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
614 const tagName = e.tagName.toLowerCase()
615 return e.id === 'content' || tagName === 'body' || tagName === 'video'
618 enableVolumeScroll: false,
619 enableModifiersForNumbers: false,
621 rewindKey: function (event: KeyboardEvent) {
622 return isNaked(event, 'ArrowLeft')
625 forwardKey: function (event: KeyboardEvent) {
626 return isNaked(event, 'ArrowRight')
629 fullscreenKey: function (event: KeyboardEvent) {
630 // fullscreen with the f key or Ctrl+Enter
631 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
635 increasePlaybackRateKey: {
636 key: function (event: KeyboardEvent) {
637 return isNaked(event, '>')
639 handler: function (player: videojs.Player) {
640 const newValue = Math.min(player.playbackRate() + 0.1, 5)
641 player.playbackRate(parseFloat(newValue.toFixed(2)))
644 decreasePlaybackRateKey: {
645 key: function (event: KeyboardEvent) {
646 return isNaked(event, '<')
648 handler: function (player: videojs.Player) {
649 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
650 player.playbackRate(parseFloat(newValue.toFixed(2)))
654 key: function (event: KeyboardEvent) {
655 return isNaked(event, '.')
657 handler: function (player: videojs.Player) {
659 // Calculate movement distance (assuming 30 fps)
661 player.currentTime(player.currentTime() + dist)
669 private static getAutoPlayValue (autoplay: any) {
670 if (autoplay !== true) return autoplay
672 // On first play, disable autoplay to avoid issues
673 // But if the player already played videos, we can safely autoplay next ones
674 if (isIOS() || isSafari()) {
675 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
682 // ############################################################################