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 initState () {
123 PeertubePlayerManager.alreadyPlayed = false
126 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
127 let p2pMediaLoader: any
129 this.onPlayerChange = onPlayerChange
130 this.playerElementClassName = options.common.playerElement.className
132 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
133 if (mode === 'p2p-media-loader') {
134 [ p2pMediaLoader ] = await Promise.all([
135 import('p2p-media-loader-hlsjs'),
136 import('./p2p-media-loader/p2p-media-loader-plugin')
140 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
142 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
145 return new Promise(res => {
146 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
149 let alreadyFallback = false
151 player.tech(true).one('error', () => {
152 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
153 alreadyFallback = true
156 player.one('error', () => {
157 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
158 alreadyFallback = true
161 player.one('play', () => {
162 PeertubePlayerManager.alreadyPlayed = true
165 self.addContextMenu(mode, player, options.common.embedUrl)
174 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
175 if (currentMode === 'webtorrent') return
177 console.log('Fallback to webtorrent.')
179 const newVideoElement = document.createElement('video')
180 newVideoElement.className = this.playerElementClassName
182 // VideoJS wraps our video element inside a div
183 let currentParentPlayerElement = options.common.playerElement.parentNode
184 // Fix on IOS, don't ask me why
185 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
187 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
189 options.common.playerElement = newVideoElement
190 options.common.onPlayerElementChange(newVideoElement)
194 await import('./webtorrent/webtorrent-plugin')
196 const mode = 'webtorrent'
197 const videojsOptions = this.getVideojsOptions(mode, options)
200 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
203 self.addContextMenu(mode, player, options.common.embedUrl)
205 PeertubePlayerManager.onPlayerChange(player)
209 private static getVideojsOptions (
211 options: PeertubePlayerManagerOptions,
212 p2pMediaLoaderModule?: any
213 ): videojs.PlayerOptions {
214 const commonOptions = options.common
215 const isHLS = mode === 'p2p-media-loader'
217 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
220 const plugins: VideoJSPluginOptions = {
223 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
224 videoViewUrl: commonOptions.videoViewUrl,
225 videoDuration: commonOptions.videoDuration,
226 userWatching: commonOptions.userWatching,
227 subtitle: commonOptions.subtitle,
228 videoCaptions: commonOptions.videoCaptions,
229 stopTime: commonOptions.stopTime
233 if (commonOptions.playlist) {
234 plugins.playlist = commonOptions.playlist
237 if (commonOptions.enableHotkeys === true) {
238 PeertubePlayerManager.addHotkeysOptions(plugins)
242 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
247 if (mode === 'webtorrent') {
248 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
250 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
254 const videojsOptions = {
257 // We don't use text track settings for now
258 textTrackSettings: false as any, // FIXME: typings
259 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
260 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
262 muted: commonOptions.muted !== undefined
263 ? commonOptions.muted
264 : undefined, // Undefined so the player knows it has to check the local storage
266 autoplay: this.getAutoPlayValue(autoplay),
268 poster: commonOptions.poster,
269 inactivityTimeout: commonOptions.inactivityTimeout,
270 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
275 children: this.getControlBarChildren(mode, {
276 captions: commonOptions.captions,
277 peertubeLink: commonOptions.peertubeLink,
278 theaterButton: commonOptions.theaterButton,
280 nextVideo: commonOptions.nextVideo,
281 hasNextVideo: commonOptions.hasNextVideo,
283 previousVideo: commonOptions.previousVideo,
284 hasPreviousVideo: commonOptions.hasPreviousVideo
285 }) as any // FIXME: typings
289 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
290 Object.assign(videojsOptions, { language: commonOptions.language })
293 return videojsOptions
296 private static addP2PMediaLoaderOptions (
297 plugins: VideoJSPluginOptions,
298 options: PeertubePlayerManagerOptions,
299 p2pMediaLoaderModule: any
301 const p2pMediaLoaderOptions = options.p2pMediaLoader
302 const commonOptions = options.common
304 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
305 .filter(t => t.startsWith('ws'))
307 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
309 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
310 redundancyUrlManager,
311 type: 'application/x-mpegURL',
312 startTime: commonOptions.startTime,
313 src: p2pMediaLoaderOptions.playlistUrl
316 let consumeOnly = false
318 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
319 console.log('We are on a cellular connection: disabling seeding.')
323 const p2pMediaLoaderConfig = {
326 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
327 rtcConfig: getRtcConfig(),
328 requiredSegmentsPriority: 1,
329 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
330 useP2P: getStoredP2PEnabled(),
334 swarmId: p2pMediaLoaderOptions.playlistUrl
338 levelLabelHandler: (level: { height: number, width: number }) => {
339 const resolution = Math.min(level.height || 0, level.width || 0)
341 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
342 // We don't have files for live videos
343 if (!file) return level.height
345 let label = file.resolution.label
346 if (file.fps >= 50) label += file.fps
352 capLevelToPlayerSize: true,
353 autoStartLoad: false,
354 liveSyncDurationCount: 5,
355 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
360 const toAssign = { p2pMediaLoader, hlsjs }
361 Object.assign(plugins, toAssign)
366 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
367 const commonOptions = options.common
368 const webtorrentOptions = options.webtorrent
370 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
376 videoDuration: commonOptions.videoDuration,
377 playerElement: commonOptions.playerElement,
378 videoFiles: webtorrentOptions.videoFiles,
379 startTime: commonOptions.startTime
382 Object.assign(plugins, { webtorrent })
385 private static getControlBarChildren (mode: PlayerMode, options: {
386 peertubeLink: boolean
387 theaterButton: boolean
391 hasNextVideo?: () => boolean
393 previousVideo?: Function
394 hasPreviousVideo?: () => boolean
396 const settingEntries = []
397 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
400 settingEntries.push('playbackRateMenuButton')
401 if (options.captions === true) settingEntries.push('captionsButton')
402 settingEntries.push('resolutionMenuButton')
406 if (options.previousVideo) {
407 const buttonOptions: NextPreviousVideoButtonOptions = {
409 handler: options.previousVideo,
411 if (!options.hasPreviousVideo) return false
413 return !options.hasPreviousVideo()
417 Object.assign(children, {
418 'previousVideoButton': buttonOptions
422 Object.assign(children, { playToggle: {} })
424 if (options.nextVideo) {
425 const buttonOptions: NextPreviousVideoButtonOptions = {
427 handler: options.nextVideo,
429 if (!options.hasNextVideo) return false
431 return !options.hasNextVideo()
435 Object.assign(children, {
436 'nextVideoButton': buttonOptions
440 Object.assign(children, {
441 'currentTimeDisplay': {},
443 'durationDisplay': {},
446 'flexibleWidthSpacer': {},
451 [loadProgressBar]: {},
452 'mouseTimeDisplay': {},
453 'playProgressBar': {}
468 entries: settingEntries
472 if (options.peertubeLink === true) {
473 Object.assign(children, {
474 'peerTubeLinkButton': {}
478 if (options.theaterButton === true) {
479 Object.assign(children, {
484 Object.assign(children, {
485 'fullscreenToggle': {}
491 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
494 label: player.localize('Copy the video URL'),
495 listener: function () {
496 copyToClipboard(buildVideoLink())
500 label: player.localize('Copy the video URL at the current time'),
501 listener: function (this: videojs.Player) {
502 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
506 label: player.localize('Copy embed code'),
508 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl))
513 if (mode === 'webtorrent') {
515 label: player.localize('Copy magnet URI'),
516 listener: function (this: videojs.Player) {
517 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
522 player.contextmenuUI({ content })
525 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
526 Object.assign(plugins, {
528 skipInitialFocus: true,
529 enableInactiveFocus: false,
530 captureDocumentHotkeys: true,
531 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
532 const tagName = e.tagName.toLowerCase()
533 return e.id === 'content' || tagName === 'body' || tagName === 'video'
536 enableVolumeScroll: false,
537 enableModifiersForNumbers: false,
539 fullscreenKey: function (event: KeyboardEvent) {
540 // fullscreen with the f key or Ctrl+Enter
541 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
544 seekStep: function (event: KeyboardEvent) {
545 // mimic VLC seek behavior, and default to 5 (original value is 5).
546 if (event.ctrlKey && event.altKey) {
548 } else if (event.ctrlKey) {
550 } else if (event.altKey) {
558 increasePlaybackRateKey: {
559 key: function (event: KeyboardEvent) {
560 return event.key === '>'
562 handler: function (player: videojs.Player) {
563 const newValue = Math.min(player.playbackRate() + 0.1, 5)
564 player.playbackRate(parseFloat(newValue.toFixed(2)))
567 decreasePlaybackRateKey: {
568 key: function (event: KeyboardEvent) {
569 return event.key === '<'
571 handler: function (player: videojs.Player) {
572 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
573 player.playbackRate(parseFloat(newValue.toFixed(2)))
577 key: function (event: KeyboardEvent) {
578 return event.key === '.'
580 handler: function (player: videojs.Player) {
582 // Calculate movement distance (assuming 30 fps)
584 player.currentTime(player.currentTime() + dist)
592 private static getAutoPlayValue (autoplay: any) {
593 if (autoplay !== true) return autoplay
595 // On first play, disable autoplay to avoid issues
596 // But if the player already played videos, we can safely autoplay next ones
597 if (isIOS() || isSafari()) {
598 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
605 // ############################################################################