1 import 'videojs-hotkeys/videojs.hotkeys'
3 import 'videojs-contextmenu-pt'
4 import './upnext/end-card'
5 import './upnext/upnext-plugin'
6 import './stats/stats-card'
7 import './stats/stats-plugin'
8 import './bezels/bezels-plugin'
9 import './peertube-plugin'
10 import './peertube-resolutions-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'
36 NextPreviousVideoButtonOptions,
37 P2PMediaLoaderPluginOptions,
38 PeerTubeLinkButtonOptions,
40 PlaylistPluginOptions,
44 } from './peertube-videojs-typings'
45 import { TranslationsManager } from './translations-manager'
46 import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isSafari } from './utils'
48 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
49 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
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_ = ' '
57 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
59 export type WebtorrentOptions = {
60 videoFiles: VideoFile[]
63 export type P2PMediaLoaderOptions = {
65 segmentsSha256Url: string
66 trackerAnnounce: string[]
67 redundancyBaseUrls: string[]
68 videoFiles: VideoFile[]
71 export interface CustomizationOptions {
72 startTime: number | string
73 stopTime: number | string
84 export interface CommonOptions extends CustomizationOptions {
85 playerElement: HTMLVideoElement
86 onPlayerElementChange: (element: HTMLVideoElement) => void
90 nextVideo?: () => void
91 hasNextVideo?: () => boolean
93 previousVideo?: () => void
94 hasPreviousVideo?: () => boolean
96 playlist?: PlaylistPluginOptions
99 enableHotkeys: boolean
100 inactivityTimeout: number
103 theaterButton: boolean
114 videoCaptions: VideoJSCaption[]
117 videoShortUUID: string
119 userWatching?: UserWatching
124 export type PeertubePlayerManagerOptions = {
125 common: CommonOptions
126 webtorrent: WebtorrentOptions
127 p2pMediaLoader?: P2PMediaLoaderOptions
129 pluginsManager: PluginsManager
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
138 static initState () {
139 PeertubePlayerManager.alreadyPlayed = false
142 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
143 this.pluginsManager = options.pluginsManager
145 let p2pMediaLoader: any
147 this.onPlayerChange = onPlayerChange
148 this.playerElementClassName = options.common.playerElement.className
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')
158 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
160 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
163 return new Promise(res => {
164 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
167 let alreadyFallback = false
169 player.tech(true).one('error', () => {
170 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
171 alreadyFallback = true
174 player.one('error', () => {
175 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
176 alreadyFallback = true
179 player.one('play', () => {
180 PeertubePlayerManager.alreadyPlayed = true
183 self.addContextMenu({
186 videoShortUUID: options.common.videoShortUUID,
187 videoEmbedUrl: options.common.embedUrl,
188 videoEmbedTitle: options.common.embedTitle
193 videoUUID: options.common.videoUUID,
194 videoIsLive: options.common.isLive,
198 player.on('p2pInfo', (_, data: PlayerNetworkInfo) => {
199 if (data.source !== 'p2p-media-loader' || isNaN(data.bandwidthEstimate)) return
201 saveAverageBandwidth(data.bandwidthEstimate)
209 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
210 if (currentMode === 'webtorrent') return
212 console.log('Fallback to webtorrent.')
214 const newVideoElement = document.createElement('video')
215 newVideoElement.className = this.playerElementClassName
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
222 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
224 options.common.playerElement = newVideoElement
225 options.common.onPlayerElementChange(newVideoElement)
229 await import('./webtorrent/webtorrent-plugin')
231 const mode = 'webtorrent'
232 const videojsOptions = await this.getVideojsOptions(mode, options)
235 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
238 self.addContextMenu({
241 videoShortUUID: options.common.videoShortUUID,
242 videoEmbedUrl: options.common.embedUrl,
243 videoEmbedTitle: options.common.embedTitle
246 PeertubePlayerManager.onPlayerChange(player)
250 private static async getVideojsOptions (
252 options: PeertubePlayerManagerOptions,
253 p2pMediaLoaderModule?: any
254 ): Promise<videojs.PlayerOptions> {
255 const commonOptions = options.common
256 const isHLS = mode === 'p2p-media-loader'
258 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
260 preloadTextTracks: false
263 const plugins: VideoJSPluginOptions = {
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
278 if (commonOptions.playlist) {
279 plugins.playlist = commonOptions.playlist
282 if (commonOptions.enableHotkeys === true) {
283 PeertubePlayerManager.addHotkeysOptions(plugins)
287 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
289 Object.assign(html5, hlsjs.html5)
292 if (mode === 'webtorrent') {
293 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
295 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
299 const videojsOptions = {
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,
307 muted: commonOptions.muted !== undefined
308 ? commonOptions.muted
309 : undefined, // Undefined so the player knows it has to check the local storage
311 autoplay: this.getAutoPlayValue(autoplay),
313 poster: commonOptions.poster,
314 inactivityTimeout: commonOptions.inactivityTimeout,
315 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
320 children: this.getControlBarChildren(mode, {
321 videoShortUUID: commonOptions.videoShortUUID,
323 captions: commonOptions.captions,
324 peertubeLink: commonOptions.peertubeLink,
325 theaterButton: commonOptions.theaterButton,
327 nextVideo: commonOptions.nextVideo,
328 hasNextVideo: commonOptions.hasNextVideo,
330 previousVideo: commonOptions.previousVideo,
331 hasPreviousVideo: commonOptions.hasPreviousVideo
332 }) as any // FIXME: typings
336 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
337 Object.assign(videojsOptions, { language: commonOptions.language })
340 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
343 private static addP2PMediaLoaderOptions (
344 plugins: VideoJSPluginOptions,
345 options: PeertubePlayerManagerOptions,
346 p2pMediaLoaderModule: any
348 const p2pMediaLoaderOptions = options.p2pMediaLoader
349 const commonOptions = options.common
351 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
352 .filter(t => t.startsWith('ws'))
354 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
356 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
357 redundancyUrlManager,
358 type: 'application/x-mpegURL',
359 startTime: commonOptions.startTime,
360 src: p2pMediaLoaderOptions.playlistUrl
363 let consumeOnly = false
364 if ((navigator as any)?.connection?.type === 'cellular') {
365 console.log('We are on a cellular connection: disabling seeding.')
369 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
372 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
373 rtcConfig: getRtcConfig(),
374 requiredSegmentsPriority: 1,
375 simultaneousHttpDownloads: 1,
376 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager, 1),
377 useP2P: getStoredP2PEnabled(),
381 swarmId: p2pMediaLoaderOptions.playlistUrl
386 levelLabelHandler: (level: { height: number, width: number }) => {
387 const resolution = Math.min(level.height || 0, level.width || 0)
389 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
390 // We don't have files for live videos
391 if (!file) return level.height
393 let label = file.resolution.label
394 if (file.fps >= 50) label += file.fps
399 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderModule, p2pMediaLoaderConfig)
403 const toAssign = { p2pMediaLoader, hlsjs }
404 Object.assign(plugins, toAssign)
409 private static getHLSOptions (p2pMediaLoaderModule: any, p2pMediaLoaderConfig: HlsJsEngineSettings) {
411 capLevelToPlayerSize: true,
412 autoStartLoad: false,
413 liveSyncDurationCount: 5,
415 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
418 const averageBandwidth = getAverageBandwidthInStore()
419 if (!averageBandwidth) return base
424 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
426 testBandwidth: false,
431 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
432 const commonOptions = options.common
433 const webtorrentOptions = options.webtorrent
434 const p2pMediaLoaderOptions = options.p2pMediaLoader
436 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
440 videoDuration: commonOptions.videoDuration,
441 playerElement: commonOptions.playerElement,
442 videoFiles: webtorrentOptions.videoFiles.length !== 0
443 ? webtorrentOptions.videoFiles
444 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
445 : p2pMediaLoaderOptions?.videoFiles || [],
446 startTime: commonOptions.startTime
449 Object.assign(plugins, { webtorrent })
452 private static getControlBarChildren (mode: PlayerMode, options: {
453 videoShortUUID: string
455 peertubeLink: boolean
456 theaterButton: boolean
459 nextVideo?: () => void
460 hasNextVideo?: () => boolean
462 previousVideo?: () => void
463 hasPreviousVideo?: () => boolean
465 const settingEntries = []
466 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
469 settingEntries.push('playbackRateMenuButton')
470 if (options.captions === true) settingEntries.push('captionsButton')
471 settingEntries.push('resolutionMenuButton')
475 if (options.previousVideo) {
476 const buttonOptions: NextPreviousVideoButtonOptions = {
478 handler: options.previousVideo,
480 if (!options.hasPreviousVideo) return false
482 return !options.hasPreviousVideo()
486 Object.assign(children, {
487 previousVideoButton: buttonOptions
491 Object.assign(children, { playToggle: {} })
493 if (options.nextVideo) {
494 const buttonOptions: NextPreviousVideoButtonOptions = {
496 handler: options.nextVideo,
498 if (!options.hasNextVideo) return false
500 return !options.hasNextVideo()
504 Object.assign(children, {
505 nextVideoButton: buttonOptions
509 Object.assign(children, {
510 currentTimeDisplay: {},
515 flexibleWidthSpacer: {},
520 [loadProgressBar]: {},
521 mouseTimeDisplay: {},
537 entries: settingEntries
541 if (options.peertubeLink === true) {
542 Object.assign(children, {
543 peerTubeLinkButton: { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
547 if (options.theaterButton === true) {
548 Object.assign(children, {
553 Object.assign(children, {
560 private static addContextMenu (options: {
562 player: videojs.Player
563 videoShortUUID: string
564 videoEmbedUrl: string
565 videoEmbedTitle: string
567 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
569 const content = () => {
570 const isLoopEnabled = player.options_['loop']
574 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
575 listener: function () {
576 player.options_['loop'] = !isLoopEnabled
580 label: player.localize('Copy the video URL'),
581 listener: function () {
582 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
586 label: player.localize('Copy the video URL at the current time'),
587 listener: function (this: videojs.Player) {
588 const url = buildVideoLink({ shortUUID: videoShortUUID })
590 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
595 label: player.localize('Copy embed code'),
597 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
602 if (mode === 'webtorrent') {
604 label: player.localize('Copy magnet URI'),
605 listener: function (this: videojs.Player) {
606 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
613 label: player.localize('Stats for nerds'),
615 player.stats().show()
619 return items.map(i => ({
621 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
626 player.contextmenuUI({ content })
629 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
630 const isNaked = (event: KeyboardEvent, key: string) =>
631 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
633 Object.assign(plugins, {
635 skipInitialFocus: true,
636 enableInactiveFocus: false,
637 captureDocumentHotkeys: true,
638 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
639 const tagName = e.tagName.toLowerCase()
640 return e.id === 'content' || tagName === 'body' || tagName === 'video'
643 enableVolumeScroll: false,
644 enableModifiersForNumbers: false,
646 rewindKey: function (event: KeyboardEvent) {
647 return isNaked(event, 'ArrowLeft')
650 forwardKey: function (event: KeyboardEvent) {
651 return isNaked(event, 'ArrowRight')
654 fullscreenKey: function (event: KeyboardEvent) {
655 // fullscreen with the f key or Ctrl+Enter
656 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
660 increasePlaybackRateKey: {
661 key: function (event: KeyboardEvent) {
662 return isNaked(event, '>')
664 handler: function (player: videojs.Player) {
665 const newValue = Math.min(player.playbackRate() + 0.1, 5)
666 player.playbackRate(parseFloat(newValue.toFixed(2)))
669 decreasePlaybackRateKey: {
670 key: function (event: KeyboardEvent) {
671 return isNaked(event, '<')
673 handler: function (player: videojs.Player) {
674 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
675 player.playbackRate(parseFloat(newValue.toFixed(2)))
679 key: function (event: KeyboardEvent) {
680 return isNaked(event, '.')
682 handler: function (player: videojs.Player) {
684 // Calculate movement distance (assuming 30 fps)
686 player.currentTime(player.currentTime() + dist)
694 private static getAutoPlayValue (autoplay: any) {
695 if (autoplay !== true) return autoplay
697 // On first play, disable autoplay to avoid issues
698 // But if the player already played videos, we can safely autoplay next ones
699 if (isIOS() || isSafari()) {
700 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
707 // ############################################################################