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
103 videoCaptions: VideoJSCaption[]
105 userWatching?: UserWatching
110 export type PeertubePlayerManagerOptions = {
111 common: CommonOptions,
112 webtorrent: WebtorrentOptions,
113 p2pMediaLoader?: P2PMediaLoaderOptions
116 export class PeertubePlayerManager {
117 private static playerElementClassName: string
118 private static onPlayerChange: (player: videojs.Player) => void
120 private static alreadyPlayed = false
122 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
123 let p2pMediaLoader: any
125 this.onPlayerChange = onPlayerChange
126 this.playerElementClassName = options.common.playerElement.className
128 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
129 if (mode === 'p2p-media-loader') {
130 [ p2pMediaLoader ] = await Promise.all([
131 import('p2p-media-loader-hlsjs'),
132 import('./p2p-media-loader/p2p-media-loader-plugin')
136 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
138 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
141 return new Promise(res => {
142 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
145 let alreadyFallback = false
147 player.tech(true).one('error', () => {
148 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
149 alreadyFallback = true
152 player.one('error', () => {
153 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
154 alreadyFallback = true
157 player.one('play', () => {
158 PeertubePlayerManager.alreadyPlayed = true
161 self.addContextMenu(mode, player, options.common.embedUrl)
170 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
171 if (currentMode === 'webtorrent') return
173 console.log('Fallback to webtorrent.')
175 const newVideoElement = document.createElement('video')
176 newVideoElement.className = this.playerElementClassName
178 // VideoJS wraps our video element inside a div
179 let currentParentPlayerElement = options.common.playerElement.parentNode
180 // Fix on IOS, don't ask me why
181 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
183 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
185 options.common.playerElement = newVideoElement
186 options.common.onPlayerElementChange(newVideoElement)
190 await import('./webtorrent/webtorrent-plugin')
192 const mode = 'webtorrent'
193 const videojsOptions = this.getVideojsOptions(mode, options)
196 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
199 self.addContextMenu(mode, player, options.common.embedUrl)
201 PeertubePlayerManager.onPlayerChange(player)
205 private static getVideojsOptions (
207 options: PeertubePlayerManagerOptions,
208 p2pMediaLoaderModule?: any
209 ): videojs.PlayerOptions {
210 const commonOptions = options.common
211 const isHLS = mode === 'p2p-media-loader'
213 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
216 const plugins: VideoJSPluginOptions = {
219 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
220 videoViewUrl: commonOptions.videoViewUrl,
221 videoDuration: commonOptions.videoDuration,
222 userWatching: commonOptions.userWatching,
223 subtitle: commonOptions.subtitle,
224 videoCaptions: commonOptions.videoCaptions,
225 stopTime: commonOptions.stopTime
229 if (commonOptions.playlist) {
230 plugins.playlist = commonOptions.playlist
233 if (commonOptions.enableHotkeys === true) {
234 PeertubePlayerManager.addHotkeysOptions(plugins)
238 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
243 if (mode === 'webtorrent') {
244 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
246 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
250 const videojsOptions = {
253 // We don't use text track settings for now
254 textTrackSettings: false as any, // FIXME: typings
255 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
256 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
258 muted: commonOptions.muted !== undefined
259 ? commonOptions.muted
260 : undefined, // Undefined so the player knows it has to check the local storage
262 autoplay: this.getAutoPlayValue(autoplay),
264 poster: commonOptions.poster,
265 inactivityTimeout: commonOptions.inactivityTimeout,
266 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
271 children: this.getControlBarChildren(mode, {
272 captions: commonOptions.captions,
273 peertubeLink: commonOptions.peertubeLink,
274 theaterButton: commonOptions.theaterButton,
276 nextVideo: commonOptions.nextVideo,
277 hasNextVideo: commonOptions.hasNextVideo,
279 previousVideo: commonOptions.previousVideo,
280 hasPreviousVideo: commonOptions.hasPreviousVideo
281 }) as any // FIXME: typings
285 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
286 Object.assign(videojsOptions, { language: commonOptions.language })
289 return videojsOptions
292 private static addP2PMediaLoaderOptions (
293 plugins: VideoJSPluginOptions,
294 options: PeertubePlayerManagerOptions,
295 p2pMediaLoaderModule: any
297 const p2pMediaLoaderOptions = options.p2pMediaLoader
298 const commonOptions = options.common
300 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
301 .filter(t => t.startsWith('ws'))
303 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
305 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
306 redundancyUrlManager,
307 type: 'application/x-mpegURL',
308 startTime: commonOptions.startTime,
309 src: p2pMediaLoaderOptions.playlistUrl
312 let consumeOnly = false
314 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
315 console.log('We are on a cellular connection: disabling seeding.')
319 const p2pMediaLoaderConfig = {
322 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
323 rtcConfig: getRtcConfig(),
324 requiredSegmentsPriority: 5,
325 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
326 useP2P: getStoredP2PEnabled(),
330 swarmId: p2pMediaLoaderOptions.playlistUrl
334 levelLabelHandler: (level: { height: number, width: number }) => {
335 const resolution = Math.min(level.height || 0, level.width || 0)
337 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
339 console.error('Cannot find video file for level %d.', level.height)
343 let label = file.resolution.label
344 if (file.fps >= 50) label += file.fps
350 capLevelToPlayerSize: true,
351 autoStartLoad: false,
352 liveSyncDurationCount: 7,
353 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
358 const toAssign = { p2pMediaLoader, hlsjs }
359 Object.assign(plugins, toAssign)
364 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
365 const commonOptions = options.common
366 const webtorrentOptions = options.webtorrent
368 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
374 videoDuration: commonOptions.videoDuration,
375 playerElement: commonOptions.playerElement,
376 videoFiles: webtorrentOptions.videoFiles,
377 startTime: commonOptions.startTime
380 Object.assign(plugins, { webtorrent })
383 private static getControlBarChildren (mode: PlayerMode, options: {
384 peertubeLink: boolean
385 theaterButton: boolean
389 hasNextVideo?: () => boolean
391 previousVideo?: Function
392 hasPreviousVideo?: () => boolean
394 const settingEntries = []
395 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
398 settingEntries.push('playbackRateMenuButton')
399 if (options.captions === true) settingEntries.push('captionsButton')
400 settingEntries.push('resolutionMenuButton')
404 if (options.previousVideo) {
405 const buttonOptions: NextPreviousVideoButtonOptions = {
407 handler: options.previousVideo,
409 if (!options.hasPreviousVideo) return false
411 return !options.hasPreviousVideo()
415 Object.assign(children, {
416 'previousVideoButton': buttonOptions
420 Object.assign(children, { playToggle: {} })
422 if (options.nextVideo) {
423 const buttonOptions: NextPreviousVideoButtonOptions = {
425 handler: options.nextVideo,
427 if (!options.hasNextVideo) return false
429 return !options.hasNextVideo()
433 Object.assign(children, {
434 'nextVideoButton': buttonOptions
438 Object.assign(children, {
439 'currentTimeDisplay': {},
441 'durationDisplay': {},
444 'flexibleWidthSpacer': {},
449 [loadProgressBar]: {},
450 'mouseTimeDisplay': {},
451 'playProgressBar': {}
466 entries: settingEntries
470 if (options.peertubeLink === true) {
471 Object.assign(children, {
472 'peerTubeLinkButton': {}
476 if (options.theaterButton === true) {
477 Object.assign(children, {
482 Object.assign(children, {
483 'fullscreenToggle': {}
489 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
492 label: player.localize('Copy the video URL'),
493 listener: function () {
494 copyToClipboard(buildVideoLink())
498 label: player.localize('Copy the video URL at the current time'),
499 listener: function (this: videojs.Player) {
500 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
504 label: player.localize('Copy embed code'),
506 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl))
511 if (mode === 'webtorrent') {
513 label: player.localize('Copy magnet URI'),
514 listener: function (this: videojs.Player) {
515 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
520 player.contextmenuUI({ content })
523 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
524 Object.assign(plugins, {
526 skipInitialFocus: true,
527 enableInactiveFocus: false,
528 captureDocumentHotkeys: true,
529 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
530 const tagName = e.tagName.toLowerCase()
531 return e.id === 'content' || tagName === 'body' || tagName === 'video'
534 enableVolumeScroll: false,
535 enableModifiersForNumbers: false,
537 fullscreenKey: function (event: KeyboardEvent) {
538 // fullscreen with the f key or Ctrl+Enter
539 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
542 seekStep: function (event: KeyboardEvent) {
543 // mimic VLC seek behavior, and default to 5 (original value is 5).
544 if (event.ctrlKey && event.altKey) {
546 } else if (event.ctrlKey) {
548 } else if (event.altKey) {
556 increasePlaybackRateKey: {
557 key: function (event: KeyboardEvent) {
558 return event.key === '>'
560 handler: function (player: videojs.Player) {
561 const newValue = Math.min(player.playbackRate() + 0.1, 5)
562 player.playbackRate(parseFloat(newValue.toFixed(2)))
565 decreasePlaybackRateKey: {
566 key: function (event: KeyboardEvent) {
567 return event.key === '<'
569 handler: function (player: videojs.Player) {
570 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
571 player.playbackRate(parseFloat(newValue.toFixed(2)))
575 key: function (event: KeyboardEvent) {
576 return event.key === '.'
578 handler: function (player: videojs.Player) {
580 // Calculate movement distance (assuming 30 fps)
582 player.currentTime(player.currentTime() + dist)
590 private static getAutoPlayValue (autoplay: any) {
591 if (autoplay !== true) return autoplay
593 // On first play, disable autoplay to avoid issues
594 // But if the player already played videos, we can safely autoplay next ones
595 if (isIOS() || isSafari()) {
596 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
603 // ############################################################################