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 { 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
365 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
366 console.log('We are on a cellular connection: disabling seeding.')
370 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
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(),
382 swarmId: p2pMediaLoaderOptions.playlistUrl
387 levelLabelHandler: (level: { height: number, width: number }) => {
388 const resolution = Math.min(level.height || 0, level.width || 0)
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
394 let label = file.resolution.label
395 if (file.fps >= 50) label += file.fps
400 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderModule, p2pMediaLoaderConfig)
404 const toAssign = { p2pMediaLoader, hlsjs }
405 Object.assign(plugins, toAssign)
410 private static getHLSOptions (p2pMediaLoaderModule: any, p2pMediaLoaderConfig: HlsJsEngineSettings) {
412 capLevelToPlayerSize: true,
413 autoStartLoad: false,
414 liveSyncDurationCount: 5,
416 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
419 const averageBandwidth = getAverageBandwidthInStore()
420 if (!averageBandwidth) return base
425 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
427 testBandwidth: false,
432 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
433 const commonOptions = options.common
434 const webtorrentOptions = options.webtorrent
435 const p2pMediaLoaderOptions = options.p2pMediaLoader
437 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
443 videoDuration: commonOptions.videoDuration,
444 playerElement: commonOptions.playerElement,
445 videoFiles: webtorrentOptions.videoFiles.length !== 0
446 ? webtorrentOptions.videoFiles
447 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
448 : p2pMediaLoaderOptions?.videoFiles || [],
449 startTime: commonOptions.startTime
452 Object.assign(plugins, { webtorrent })
455 private static getControlBarChildren (mode: PlayerMode, options: {
456 videoShortUUID: string
458 peertubeLink: boolean
459 theaterButton: boolean
463 hasNextVideo?: () => boolean
465 previousVideo?: Function
466 hasPreviousVideo?: () => boolean
468 const settingEntries = []
469 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
472 settingEntries.push('playbackRateMenuButton')
473 if (options.captions === true) settingEntries.push('captionsButton')
474 settingEntries.push('resolutionMenuButton')
478 if (options.previousVideo) {
479 const buttonOptions: NextPreviousVideoButtonOptions = {
481 handler: options.previousVideo,
483 if (!options.hasPreviousVideo) return false
485 return !options.hasPreviousVideo()
489 Object.assign(children, {
490 'previousVideoButton': buttonOptions
494 Object.assign(children, { playToggle: {} })
496 if (options.nextVideo) {
497 const buttonOptions: NextPreviousVideoButtonOptions = {
499 handler: options.nextVideo,
501 if (!options.hasNextVideo) return false
503 return !options.hasNextVideo()
507 Object.assign(children, {
508 'nextVideoButton': buttonOptions
512 Object.assign(children, {
513 'currentTimeDisplay': {},
515 'durationDisplay': {},
518 'flexibleWidthSpacer': {},
523 [loadProgressBar]: {},
524 'mouseTimeDisplay': {},
525 'playProgressBar': {}
540 entries: settingEntries
544 if (options.peertubeLink === true) {
545 Object.assign(children, {
546 'peerTubeLinkButton': { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
550 if (options.theaterButton === true) {
551 Object.assign(children, {
556 Object.assign(children, {
557 'fullscreenToggle': {}
563 private static addContextMenu (options: {
565 player: videojs.Player
566 videoShortUUID: string
567 videoEmbedUrl: string
568 videoEmbedTitle: string
570 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
572 const content = () => {
573 const isLoopEnabled = player.options_['loop']
577 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
578 listener: function () {
579 player.options_['loop'] = !isLoopEnabled
583 label: player.localize('Copy the video URL'),
584 listener: function () {
585 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
589 label: player.localize('Copy the video URL at the current time'),
590 listener: function (this: videojs.Player) {
591 const url = buildVideoLink({ shortUUID: videoShortUUID })
593 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
598 label: player.localize('Copy embed code'),
600 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
605 if (mode === 'webtorrent') {
607 label: player.localize('Copy magnet URI'),
608 listener: function (this: videojs.Player) {
609 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
616 label: player.localize('Stats for nerds'),
618 player.stats().show()
622 return items.map(i => ({
624 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
629 player.contextmenuUI({ content })
632 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
633 const isNaked = (event: KeyboardEvent, key: string) =>
634 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
636 Object.assign(plugins, {
638 skipInitialFocus: true,
639 enableInactiveFocus: false,
640 captureDocumentHotkeys: true,
641 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
642 const tagName = e.tagName.toLowerCase()
643 return e.id === 'content' || tagName === 'body' || tagName === 'video'
646 enableVolumeScroll: false,
647 enableModifiersForNumbers: false,
649 rewindKey: function (event: KeyboardEvent) {
650 return isNaked(event, 'ArrowLeft')
653 forwardKey: function (event: KeyboardEvent) {
654 return isNaked(event, 'ArrowRight')
657 fullscreenKey: function (event: KeyboardEvent) {
658 // fullscreen with the f key or Ctrl+Enter
659 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
663 increasePlaybackRateKey: {
664 key: function (event: KeyboardEvent) {
665 return isNaked(event, '>')
667 handler: function (player: videojs.Player) {
668 const newValue = Math.min(player.playbackRate() + 0.1, 5)
669 player.playbackRate(parseFloat(newValue.toFixed(2)))
672 decreasePlaybackRateKey: {
673 key: function (event: KeyboardEvent) {
674 return isNaked(event, '<')
676 handler: function (player: videojs.Player) {
677 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
678 player.playbackRate(parseFloat(newValue.toFixed(2)))
682 key: function (event: KeyboardEvent) {
683 return isNaked(event, '.')
685 handler: function (player: videojs.Player) {
687 // Calculate movement distance (assuming 30 fps)
689 player.currentTime(player.currentTime() + dist)
697 private static getAutoPlayValue (autoplay: any) {
698 if (autoplay !== true) return autoplay
700 // On first play, disable autoplay to avoid issues
701 // But if the player already played videos, we can safely autoplay next ones
702 if (isIOS() || isSafari()) {
703 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
710 // ############################################################################