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 { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
27 import { isDefaultLocale } from '@shared/core-utils/i18n'
28 import { VideoFile } from '@shared/models'
29 import { copyToClipboard } from '../../root-helpers/utils'
30 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
31 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
32 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
33 import { getStoredP2PEnabled } from './peertube-player-local-storage'
35 NextPreviousVideoButtonOptions,
36 P2PMediaLoaderPluginOptions,
37 PeerTubeLinkButtonOptions,
38 PlaylistPluginOptions,
42 } from './peertube-videojs-typings'
43 import { TranslationsManager } from './translations-manager'
44 import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isSafari } from './utils'
46 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
47 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
49 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
50 // Change Captions to Subtitles/CC
51 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
52 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
53 CaptionsButton.prototype.label_ = ' '
55 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
57 export type WebtorrentOptions = {
58 videoFiles: VideoFile[]
61 export type P2PMediaLoaderOptions = {
63 segmentsSha256Url: string
64 trackerAnnounce: string[]
65 redundancyBaseUrls: string[]
66 videoFiles: VideoFile[]
69 export interface CustomizationOptions {
70 startTime: number | string
71 stopTime: number | string
82 export interface CommonOptions extends CustomizationOptions {
83 playerElement: HTMLVideoElement
84 onPlayerElementChange: (element: HTMLVideoElement) => void
88 nextVideo?: () => void
89 hasNextVideo?: () => boolean
91 previousVideo?: () => void
92 hasPreviousVideo?: () => boolean
94 playlist?: PlaylistPluginOptions
97 enableHotkeys: boolean
98 inactivityTimeout: number
101 theaterButton: boolean
112 videoCaptions: VideoJSCaption[]
115 videoShortUUID: string
117 userWatching?: UserWatching
122 export type PeertubePlayerManagerOptions = {
123 common: CommonOptions
124 webtorrent: WebtorrentOptions
125 p2pMediaLoader?: P2PMediaLoaderOptions
127 pluginsManager: PluginsManager
130 export class PeertubePlayerManager {
131 private static playerElementClassName: string
132 private static onPlayerChange: (player: videojs.Player) => void
133 private static alreadyPlayed = false
134 private static pluginsManager: PluginsManager
136 static initState () {
137 PeertubePlayerManager.alreadyPlayed = false
140 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
141 this.pluginsManager = options.pluginsManager
143 let p2pMediaLoader: any
145 this.onPlayerChange = onPlayerChange
146 this.playerElementClassName = options.common.playerElement.className
148 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
149 if (mode === 'p2p-media-loader') {
150 [ p2pMediaLoader ] = await Promise.all([
151 import('p2p-media-loader-hlsjs'),
152 import('./p2p-media-loader/p2p-media-loader-plugin')
156 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
158 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
161 return new Promise(res => {
162 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
165 let alreadyFallback = false
167 player.tech(true).one('error', () => {
168 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
169 alreadyFallback = true
172 player.one('error', () => {
173 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
174 alreadyFallback = true
177 player.one('play', () => {
178 PeertubePlayerManager.alreadyPlayed = true
181 self.addContextMenu({
184 videoShortUUID: options.common.videoShortUUID,
185 videoEmbedUrl: options.common.embedUrl,
186 videoEmbedTitle: options.common.embedTitle
191 videoUUID: options.common.videoUUID,
192 videoIsLive: options.common.isLive,
201 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
202 if (currentMode === 'webtorrent') return
204 console.log('Fallback to webtorrent.')
206 const newVideoElement = document.createElement('video')
207 newVideoElement.className = this.playerElementClassName
209 // VideoJS wraps our video element inside a div
210 let currentParentPlayerElement = options.common.playerElement.parentNode
211 // Fix on IOS, don't ask me why
212 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
214 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
216 options.common.playerElement = newVideoElement
217 options.common.onPlayerElementChange(newVideoElement)
221 await import('./webtorrent/webtorrent-plugin')
223 const mode = 'webtorrent'
224 const videojsOptions = await this.getVideojsOptions(mode, options)
227 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
230 self.addContextMenu({
233 videoShortUUID: options.common.videoShortUUID,
234 videoEmbedUrl: options.common.embedUrl,
235 videoEmbedTitle: options.common.embedTitle
238 PeertubePlayerManager.onPlayerChange(player)
242 private static async getVideojsOptions (
244 options: PeertubePlayerManagerOptions,
245 p2pMediaLoaderModule?: any
246 ): Promise<videojs.PlayerOptions> {
247 const commonOptions = options.common
248 const isHLS = mode === 'p2p-media-loader'
250 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
252 preloadTextTracks: false
255 const plugins: VideoJSPluginOptions = {
258 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
259 videoViewUrl: commonOptions.videoViewUrl,
260 videoDuration: commonOptions.videoDuration,
261 userWatching: commonOptions.userWatching,
262 subtitle: commonOptions.subtitle,
263 videoCaptions: commonOptions.videoCaptions,
264 stopTime: commonOptions.stopTime,
265 isLive: commonOptions.isLive,
266 videoUUID: commonOptions.videoUUID
270 if (commonOptions.playlist) {
271 plugins.playlist = commonOptions.playlist
274 if (commonOptions.enableHotkeys === true) {
275 PeertubePlayerManager.addHotkeysOptions(plugins)
279 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
281 Object.assign(html5, hlsjs.html5)
284 if (mode === 'webtorrent') {
285 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
287 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
291 const videojsOptions = {
294 // We don't use text track settings for now
295 textTrackSettings: false as any, // FIXME: typings
296 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
297 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
299 muted: commonOptions.muted !== undefined
300 ? commonOptions.muted
301 : undefined, // Undefined so the player knows it has to check the local storage
303 autoplay: this.getAutoPlayValue(autoplay),
305 poster: commonOptions.poster,
306 inactivityTimeout: commonOptions.inactivityTimeout,
307 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
312 children: this.getControlBarChildren(mode, {
313 videoShortUUID: commonOptions.videoShortUUID,
315 captions: commonOptions.captions,
316 peertubeLink: commonOptions.peertubeLink,
317 theaterButton: commonOptions.theaterButton,
319 nextVideo: commonOptions.nextVideo,
320 hasNextVideo: commonOptions.hasNextVideo,
322 previousVideo: commonOptions.previousVideo,
323 hasPreviousVideo: commonOptions.hasPreviousVideo
324 }) as any // FIXME: typings
328 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
329 Object.assign(videojsOptions, { language: commonOptions.language })
332 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
335 private static addP2PMediaLoaderOptions (
336 plugins: VideoJSPluginOptions,
337 options: PeertubePlayerManagerOptions,
338 p2pMediaLoaderModule: any
340 const p2pMediaLoaderOptions = options.p2pMediaLoader
341 const commonOptions = options.common
343 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
344 .filter(t => t.startsWith('ws'))
346 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
348 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
349 redundancyUrlManager,
350 type: 'application/x-mpegURL',
351 startTime: commonOptions.startTime,
352 src: p2pMediaLoaderOptions.playlistUrl
355 let consumeOnly = false
357 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
358 console.log('We are on a cellular connection: disabling seeding.')
362 const p2pMediaLoaderConfig = {
365 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
366 rtcConfig: getRtcConfig(),
367 requiredSegmentsPriority: 1,
368 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
369 useP2P: getStoredP2PEnabled(),
373 swarmId: p2pMediaLoaderOptions.playlistUrl
377 levelLabelHandler: (level: { height: number, width: number }) => {
378 const resolution = Math.min(level.height || 0, level.width || 0)
380 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
381 // We don't have files for live videos
382 if (!file) return level.height
384 let label = file.resolution.label
385 if (file.fps >= 50) label += file.fps
391 capLevelToPlayerSize: true,
392 autoStartLoad: false,
393 liveSyncDurationCount: 5,
394 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
399 const toAssign = { p2pMediaLoader, hlsjs }
400 Object.assign(plugins, toAssign)
405 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
406 const commonOptions = options.common
407 const webtorrentOptions = options.webtorrent
408 const p2pMediaLoaderOptions = options.p2pMediaLoader
410 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
416 videoDuration: commonOptions.videoDuration,
417 playerElement: commonOptions.playerElement,
418 videoFiles: webtorrentOptions.videoFiles.length !== 0
419 ? webtorrentOptions.videoFiles
420 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
421 : p2pMediaLoaderOptions?.videoFiles || [],
422 startTime: commonOptions.startTime
425 Object.assign(plugins, { webtorrent })
428 private static getControlBarChildren (mode: PlayerMode, options: {
429 videoShortUUID: string
431 peertubeLink: boolean
432 theaterButton: boolean
436 hasNextVideo?: () => boolean
438 previousVideo?: Function
439 hasPreviousVideo?: () => boolean
441 const settingEntries = []
442 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
445 settingEntries.push('playbackRateMenuButton')
446 if (options.captions === true) settingEntries.push('captionsButton')
447 settingEntries.push('resolutionMenuButton')
451 if (options.previousVideo) {
452 const buttonOptions: NextPreviousVideoButtonOptions = {
454 handler: options.previousVideo,
456 if (!options.hasPreviousVideo) return false
458 return !options.hasPreviousVideo()
462 Object.assign(children, {
463 'previousVideoButton': buttonOptions
467 Object.assign(children, { playToggle: {} })
469 if (options.nextVideo) {
470 const buttonOptions: NextPreviousVideoButtonOptions = {
472 handler: options.nextVideo,
474 if (!options.hasNextVideo) return false
476 return !options.hasNextVideo()
480 Object.assign(children, {
481 'nextVideoButton': buttonOptions
485 Object.assign(children, {
486 'currentTimeDisplay': {},
488 'durationDisplay': {},
491 'flexibleWidthSpacer': {},
496 [loadProgressBar]: {},
497 'mouseTimeDisplay': {},
498 'playProgressBar': {}
513 entries: settingEntries
517 if (options.peertubeLink === true) {
518 Object.assign(children, {
519 'peerTubeLinkButton': { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
523 if (options.theaterButton === true) {
524 Object.assign(children, {
529 Object.assign(children, {
530 'fullscreenToggle': {}
536 private static addContextMenu (options: {
538 player: videojs.Player
539 videoShortUUID: string
540 videoEmbedUrl: string
541 videoEmbedTitle: string
543 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
545 const content = () => {
546 const isLoopEnabled = player.options_['loop']
550 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
551 listener: function () {
552 player.options_['loop'] = !isLoopEnabled
556 label: player.localize('Copy the video URL'),
557 listener: function () {
558 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
562 label: player.localize('Copy the video URL at the current time'),
563 listener: function (this: videojs.Player) {
564 const url = buildVideoLink({ shortUUID: videoShortUUID })
566 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
571 label: player.localize('Copy embed code'),
573 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
578 if (mode === 'webtorrent') {
580 label: player.localize('Copy magnet URI'),
581 listener: function (this: videojs.Player) {
582 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
589 label: player.localize('Stats for nerds'),
591 player.stats().show()
595 return items.map(i => ({
597 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
602 player.contextmenuUI({ content })
605 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
606 const isNaked = (event: KeyboardEvent, key: string) =>
607 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
609 Object.assign(plugins, {
611 skipInitialFocus: true,
612 enableInactiveFocus: false,
613 captureDocumentHotkeys: true,
614 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
615 const tagName = e.tagName.toLowerCase()
616 return e.id === 'content' || tagName === 'body' || tagName === 'video'
619 enableVolumeScroll: false,
620 enableModifiersForNumbers: false,
622 rewindKey: function (event: KeyboardEvent) {
623 return isNaked(event, 'ArrowLeft')
626 forwardKey: function (event: KeyboardEvent) {
627 return isNaked(event, 'ArrowRight')
630 fullscreenKey: function (event: KeyboardEvent) {
631 // fullscreen with the f key or Ctrl+Enter
632 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
636 increasePlaybackRateKey: {
637 key: function (event: KeyboardEvent) {
638 return isNaked(event, '>')
640 handler: function (player: videojs.Player) {
641 const newValue = Math.min(player.playbackRate() + 0.1, 5)
642 player.playbackRate(parseFloat(newValue.toFixed(2)))
645 decreasePlaybackRateKey: {
646 key: function (event: KeyboardEvent) {
647 return isNaked(event, '<')
649 handler: function (player: videojs.Player) {
650 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
651 player.playbackRate(parseFloat(newValue.toFixed(2)))
655 key: function (event: KeyboardEvent) {
656 return isNaked(event, '.')
658 handler: function (player: videojs.Player) {
660 // Calculate movement distance (assuming 30 fps)
662 player.currentTime(player.currentTime() + dist)
670 private static getAutoPlayValue (autoplay: any) {
671 if (autoplay !== true) return autoplay
673 // On first play, disable autoplay to avoid issues
674 // But if the player already played videos, we can safely autoplay next ones
675 if (isIOS() || isSafari()) {
676 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
683 // ############################################################################