1 import 'videojs-hotkeys/videojs.hotkeys'
3 import 'videojs-contextmenu-ui'
4 import 'videojs-contrib-quality-levels'
5 import './upnext/end-card'
6 import './upnext/upnext-plugin'
7 import './bezels/bezels-plugin'
8 import './peertube-plugin'
9 import './videojs-components/next-previous-video-button'
10 import './videojs-components/p2p-info-button'
11 import './videojs-components/peertube-link-button'
12 import './videojs-components/peertube-load-progress-bar'
13 import './videojs-components/resolution-menu-button'
14 import './videojs-components/resolution-menu-item'
15 import './videojs-components/settings-dialog'
16 import './videojs-components/settings-menu-button'
17 import './videojs-components/settings-menu-item'
18 import './videojs-components/settings-panel'
19 import './videojs-components/settings-panel-child'
20 import './videojs-components/theater-button'
21 import './playlist/playlist-plugin'
22 import videojs from 'video.js'
23 import { isDefaultLocale } from '@shared/core-utils/i18n'
24 import { VideoFile } from '@shared/models'
25 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
26 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
27 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
28 import { getStoredP2PEnabled } from './peertube-player-local-storage'
30 NextPreviousVideoButtonOptions,
31 P2PMediaLoaderPluginOptions,
32 PlaylistPluginOptions,
36 } from './peertube-videojs-typings'
37 import { TranslationsManager } from './translations-manager'
38 import { buildVideoOrPlaylistEmbed, buildVideoLink, copyToClipboard, getRtcConfig, isSafari, isIOS } from './utils'
40 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
41 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
43 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
44 // Change Captions to Subtitles/CC
45 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
46 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
47 CaptionsButton.prototype.label_ = ' '
49 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
51 export type WebtorrentOptions = {
52 videoFiles: VideoFile[]
55 export type P2PMediaLoaderOptions = {
57 segmentsSha256Url: string
58 trackerAnnounce: string[]
59 redundancyBaseUrls: string[]
60 videoFiles: VideoFile[]
63 export interface CustomizationOptions {
64 startTime: number | string
65 stopTime: number | string
76 export interface CommonOptions extends CustomizationOptions {
77 playerElement: HTMLVideoElement
78 onPlayerElementChange: (element: HTMLVideoElement) => void
82 nextVideo?: () => void
83 hasNextVideo?: () => boolean
85 previousVideo?: () => void
86 hasPreviousVideo?: () => boolean
88 playlist?: PlaylistPluginOptions
91 enableHotkeys: boolean
92 inactivityTimeout: number
95 theaterButton: boolean
105 videoCaptions: VideoJSCaption[]
107 userWatching?: UserWatching
112 export type PeertubePlayerManagerOptions = {
113 common: CommonOptions,
114 webtorrent: WebtorrentOptions,
115 p2pMediaLoader?: P2PMediaLoaderOptions
118 export class PeertubePlayerManager {
119 private static playerElementClassName: string
120 private static onPlayerChange: (player: videojs.Player) => void
122 private static alreadyPlayed = false
124 static initState () {
125 PeertubePlayerManager.alreadyPlayed = false
128 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
129 let p2pMediaLoader: any
131 this.onPlayerChange = onPlayerChange
132 this.playerElementClassName = options.common.playerElement.className
134 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
135 if (mode === 'p2p-media-loader') {
136 [ p2pMediaLoader ] = await Promise.all([
137 import('p2p-media-loader-hlsjs'),
138 import('./p2p-media-loader/p2p-media-loader-plugin')
142 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
144 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
147 return new Promise(res => {
148 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
151 let alreadyFallback = false
153 player.tech(true).one('error', () => {
154 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
155 alreadyFallback = true
158 player.one('error', () => {
159 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
160 alreadyFallback = true
163 player.one('play', () => {
164 PeertubePlayerManager.alreadyPlayed = true
167 self.addContextMenu(mode, player, options.common.embedUrl)
176 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
177 if (currentMode === 'webtorrent') return
179 console.log('Fallback to webtorrent.')
181 const newVideoElement = document.createElement('video')
182 newVideoElement.className = this.playerElementClassName
184 // VideoJS wraps our video element inside a div
185 let currentParentPlayerElement = options.common.playerElement.parentNode
186 // Fix on IOS, don't ask me why
187 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
189 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
191 options.common.playerElement = newVideoElement
192 options.common.onPlayerElementChange(newVideoElement)
196 await import('./webtorrent/webtorrent-plugin')
198 const mode = 'webtorrent'
199 const videojsOptions = this.getVideojsOptions(mode, options)
202 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
205 self.addContextMenu(mode, player, options.common.embedUrl)
207 PeertubePlayerManager.onPlayerChange(player)
211 private static getVideojsOptions (
213 options: PeertubePlayerManagerOptions,
214 p2pMediaLoaderModule?: any
215 ): videojs.PlayerOptions {
216 const commonOptions = options.common
217 const isHLS = mode === 'p2p-media-loader'
219 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
222 const plugins: VideoJSPluginOptions = {
225 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
226 videoViewUrl: commonOptions.videoViewUrl,
227 videoDuration: commonOptions.videoDuration,
228 userWatching: commonOptions.userWatching,
229 subtitle: commonOptions.subtitle,
230 videoCaptions: commonOptions.videoCaptions,
231 stopTime: commonOptions.stopTime
235 if (commonOptions.playlist) {
236 plugins.playlist = commonOptions.playlist
239 if (commonOptions.enableHotkeys === true) {
240 PeertubePlayerManager.addHotkeysOptions(plugins)
244 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
249 if (mode === 'webtorrent') {
250 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
252 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
256 const videojsOptions = {
259 // We don't use text track settings for now
260 textTrackSettings: false as any, // FIXME: typings
261 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
262 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
264 muted: commonOptions.muted !== undefined
265 ? commonOptions.muted
266 : undefined, // Undefined so the player knows it has to check the local storage
268 autoplay: this.getAutoPlayValue(autoplay),
270 poster: commonOptions.poster,
271 inactivityTimeout: commonOptions.inactivityTimeout,
272 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
277 children: this.getControlBarChildren(mode, {
278 captions: commonOptions.captions,
279 peertubeLink: commonOptions.peertubeLink,
280 theaterButton: commonOptions.theaterButton,
282 nextVideo: commonOptions.nextVideo,
283 hasNextVideo: commonOptions.hasNextVideo,
285 previousVideo: commonOptions.previousVideo,
286 hasPreviousVideo: commonOptions.hasPreviousVideo
287 }) as any // FIXME: typings
291 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
292 Object.assign(videojsOptions, { language: commonOptions.language })
295 return videojsOptions
298 private static addP2PMediaLoaderOptions (
299 plugins: VideoJSPluginOptions,
300 options: PeertubePlayerManagerOptions,
301 p2pMediaLoaderModule: any
303 const p2pMediaLoaderOptions = options.p2pMediaLoader
304 const commonOptions = options.common
306 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
307 .filter(t => t.startsWith('ws'))
309 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
311 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
312 redundancyUrlManager,
313 type: 'application/x-mpegURL',
314 startTime: commonOptions.startTime,
315 src: p2pMediaLoaderOptions.playlistUrl
318 let consumeOnly = false
320 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
321 console.log('We are on a cellular connection: disabling seeding.')
325 const p2pMediaLoaderConfig = {
328 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
329 rtcConfig: getRtcConfig(),
330 requiredSegmentsPriority: 1,
331 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
332 useP2P: getStoredP2PEnabled(),
336 swarmId: p2pMediaLoaderOptions.playlistUrl
340 levelLabelHandler: (level: { height: number, width: number }) => {
341 const resolution = Math.min(level.height || 0, level.width || 0)
343 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
344 // We don't have files for live videos
345 if (!file) return level.height
347 let label = file.resolution.label
348 if (file.fps >= 50) label += file.fps
354 capLevelToPlayerSize: true,
355 autoStartLoad: false,
356 liveSyncDurationCount: 5,
357 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
362 const toAssign = { p2pMediaLoader, hlsjs }
363 Object.assign(plugins, toAssign)
368 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
369 const commonOptions = options.common
370 const webtorrentOptions = options.webtorrent
372 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
378 videoDuration: commonOptions.videoDuration,
379 playerElement: commonOptions.playerElement,
380 videoFiles: webtorrentOptions.videoFiles,
381 startTime: commonOptions.startTime
384 Object.assign(plugins, { webtorrent })
387 private static getControlBarChildren (mode: PlayerMode, options: {
388 peertubeLink: boolean
389 theaterButton: boolean
393 hasNextVideo?: () => boolean
395 previousVideo?: Function
396 hasPreviousVideo?: () => boolean
398 const settingEntries = []
399 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
402 settingEntries.push('playbackRateMenuButton')
403 if (options.captions === true) settingEntries.push('captionsButton')
404 settingEntries.push('resolutionMenuButton')
408 if (options.previousVideo) {
409 const buttonOptions: NextPreviousVideoButtonOptions = {
411 handler: options.previousVideo,
413 if (!options.hasPreviousVideo) return false
415 return !options.hasPreviousVideo()
419 Object.assign(children, {
420 'previousVideoButton': buttonOptions
424 Object.assign(children, { playToggle: {} })
426 if (options.nextVideo) {
427 const buttonOptions: NextPreviousVideoButtonOptions = {
429 handler: options.nextVideo,
431 if (!options.hasNextVideo) return false
433 return !options.hasNextVideo()
437 Object.assign(children, {
438 'nextVideoButton': buttonOptions
442 Object.assign(children, {
443 'currentTimeDisplay': {},
445 'durationDisplay': {},
448 'flexibleWidthSpacer': {},
453 [loadProgressBar]: {},
454 'mouseTimeDisplay': {},
455 'playProgressBar': {}
470 entries: settingEntries
474 if (options.peertubeLink === true) {
475 Object.assign(children, {
476 'peerTubeLinkButton': {}
480 if (options.theaterButton === true) {
481 Object.assign(children, {
486 Object.assign(children, {
487 'fullscreenToggle': {}
493 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
496 label: player.localize('Copy the video URL'),
497 listener: function () {
498 copyToClipboard(buildVideoLink())
502 label: player.localize('Copy the video URL at the current time'),
503 listener: function (this: videojs.Player) {
504 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
508 label: player.localize('Copy embed code'),
510 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl))
515 if (mode === 'webtorrent') {
517 label: player.localize('Copy magnet URI'),
518 listener: function (this: videojs.Player) {
519 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
524 player.contextmenuUI({ content })
527 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
528 Object.assign(plugins, {
530 skipInitialFocus: true,
531 enableInactiveFocus: false,
532 captureDocumentHotkeys: true,
533 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
534 const tagName = e.tagName.toLowerCase()
535 return e.id === 'content' || tagName === 'body' || tagName === 'video'
538 enableVolumeScroll: false,
539 enableModifiersForNumbers: false,
541 fullscreenKey: function (event: KeyboardEvent) {
542 // fullscreen with the f key or Ctrl+Enter
543 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
546 seekStep: function (event: KeyboardEvent) {
547 // mimic VLC seek behavior, and default to 5 (original value is 5).
548 if (event.ctrlKey && event.altKey) {
550 } else if (event.ctrlKey) {
552 } else if (event.altKey) {
560 increasePlaybackRateKey: {
561 key: function (event: KeyboardEvent) {
562 return event.key === '>'
564 handler: function (player: videojs.Player) {
565 const newValue = Math.min(player.playbackRate() + 0.1, 5)
566 player.playbackRate(parseFloat(newValue.toFixed(2)))
569 decreasePlaybackRateKey: {
570 key: function (event: KeyboardEvent) {
571 return event.key === '<'
573 handler: function (player: videojs.Player) {
574 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
575 player.playbackRate(parseFloat(newValue.toFixed(2)))
579 key: function (event: KeyboardEvent) {
580 return event.key === '.'
582 handler: function (player: videojs.Player) {
584 // Calculate movement distance (assuming 30 fps)
586 player.currentTime(player.currentTime() + dist)
594 private static getAutoPlayValue (autoplay: any) {
595 if (autoplay !== true) return autoplay
597 // On first play, disable autoplay to avoid issues
598 // But if the player already played videos, we can safely autoplay next ones
599 if (isIOS() || isSafari()) {
600 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
607 // ############################################################################