1 import 'videojs-hotkeys/videojs.hotkeys'
3 import '@peertube/videojs-contextmenu'
4 import './upnext/end-card'
5 import './upnext/upnext-plugin'
6 import './stats/stats-card'
7 import './stats/stats-plugin'
8 import './bezels/bezels-plugin'
9 import './peertube-plugin'
10 import './peertube-resolutions-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 './mobile/peertube-mobile-plugin'
25 import './mobile/peertube-mobile-buttons'
26 import videojs from 'video.js'
27 import { HlsJsEngineSettings } from '@peertube/p2p-media-loader-hlsjs'
28 import { PluginsManager } from '@root-helpers/plugins-manager'
29 import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
30 import { isDefaultLocale } from '@shared/core-utils/i18n'
31 import { VideoFile } from '@shared/models'
32 import { copyToClipboard } from '../../root-helpers/utils'
33 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
34 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
35 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
36 import { getAverageBandwidthInStore, saveAverageBandwidth } from './peertube-player-local-storage'
38 NextPreviousVideoButtonOptions,
39 P2PMediaLoaderPluginOptions,
40 PeerTubeLinkButtonOptions,
42 PlaylistPluginOptions,
46 } from './peertube-videojs-typings'
47 import { TranslationsManager } from './translations-manager'
48 import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isMobile, isSafari } from './utils'
50 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
51 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
53 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
54 // Change Captions to Subtitles/CC
55 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
56 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
57 CaptionsButton.prototype.label_ = ' '
59 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
61 export type WebtorrentOptions = {
62 videoFiles: VideoFile[]
65 export type P2PMediaLoaderOptions = {
67 segmentsSha256Url: string
68 trackerAnnounce: string[]
69 redundancyBaseUrls: string[]
70 videoFiles: VideoFile[]
73 export interface CustomizationOptions {
74 startTime: number | string
75 stopTime: number | string
86 export interface CommonOptions extends CustomizationOptions {
87 playerElement: HTMLVideoElement
88 onPlayerElementChange: (element: HTMLVideoElement) => void
93 nextVideo?: () => void
94 hasNextVideo?: () => boolean
96 previousVideo?: () => void
97 hasPreviousVideo?: () => boolean
99 playlist?: PlaylistPluginOptions
101 videoDuration: number
102 enableHotkeys: boolean
103 inactivityTimeout: number
106 theaterButton: boolean
117 videoCaptions: VideoJSCaption[]
120 videoShortUUID: string
122 userWatching?: UserWatching
127 export type PeertubePlayerManagerOptions = {
128 common: CommonOptions
129 webtorrent: WebtorrentOptions
130 p2pMediaLoader?: P2PMediaLoaderOptions
132 pluginsManager: PluginsManager
135 export class PeertubePlayerManager {
136 private static playerElementClassName: string
137 private static onPlayerChange: (player: videojs.Player) => void
138 private static alreadyPlayed = false
139 private static pluginsManager: PluginsManager
141 static initState () {
142 PeertubePlayerManager.alreadyPlayed = false
145 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
146 this.pluginsManager = options.pluginsManager
148 let p2pMediaLoader: any
150 this.onPlayerChange = onPlayerChange
151 this.playerElementClassName = options.common.playerElement.className
153 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
154 if (mode === 'p2p-media-loader') {
155 [ p2pMediaLoader ] = await Promise.all([
156 import('@peertube/p2p-media-loader-hlsjs'),
157 import('./p2p-media-loader/p2p-media-loader-plugin')
161 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
163 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
166 return new Promise(res => {
167 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
170 let alreadyFallback = false
172 player.tech(true).one('error', () => {
173 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
174 alreadyFallback = true
177 player.one('error', () => {
178 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
179 alreadyFallback = true
182 player.one('play', () => {
183 PeertubePlayerManager.alreadyPlayed = true
186 self.addContextMenu({
189 videoShortUUID: options.common.videoShortUUID,
190 videoEmbedUrl: options.common.embedUrl,
191 videoEmbedTitle: options.common.embedTitle
194 if (isMobile()) player.peertubeMobile()
199 videoUUID: options.common.videoUUID,
200 videoIsLive: options.common.isLive,
202 p2pEnabled: options.common.p2pEnabled
205 player.on('p2pInfo', (_, data: PlayerNetworkInfo) => {
206 if (data.source !== 'p2p-media-loader' || isNaN(data.bandwidthEstimate)) return
208 saveAverageBandwidth(data.bandwidthEstimate)
216 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
217 if (currentMode === 'webtorrent') return
219 console.log('Fallback to webtorrent.')
221 const newVideoElement = document.createElement('video')
222 newVideoElement.className = this.playerElementClassName
224 // VideoJS wraps our video element inside a div
225 let currentParentPlayerElement = options.common.playerElement.parentNode
226 // Fix on IOS, don't ask me why
227 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
229 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
231 options.common.playerElement = newVideoElement
232 options.common.onPlayerElementChange(newVideoElement)
236 await import('./webtorrent/webtorrent-plugin')
238 const mode = 'webtorrent'
239 const videojsOptions = await this.getVideojsOptions(mode, options)
242 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
245 self.addContextMenu({
248 videoShortUUID: options.common.videoShortUUID,
249 videoEmbedUrl: options.common.embedUrl,
250 videoEmbedTitle: options.common.embedTitle
253 PeertubePlayerManager.onPlayerChange(player)
257 private static async getVideojsOptions (
259 options: PeertubePlayerManagerOptions,
260 p2pMediaLoaderModule?: any
261 ): Promise<videojs.PlayerOptions> {
262 const commonOptions = options.common
263 const isHLS = mode === 'p2p-media-loader'
265 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
267 preloadTextTracks: false
270 const plugins: VideoJSPluginOptions = {
273 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
274 videoViewUrl: commonOptions.videoViewUrl,
275 videoDuration: commonOptions.videoDuration,
276 userWatching: commonOptions.userWatching,
277 subtitle: commonOptions.subtitle,
278 videoCaptions: commonOptions.videoCaptions,
279 stopTime: commonOptions.stopTime,
280 isLive: commonOptions.isLive,
281 videoUUID: commonOptions.videoUUID
285 if (commonOptions.playlist) {
286 plugins.playlist = commonOptions.playlist
289 if (commonOptions.enableHotkeys === true) {
290 PeertubePlayerManager.addHotkeysOptions(plugins)
294 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
296 Object.assign(html5, hlsjs.html5)
299 if (mode === 'webtorrent') {
300 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
302 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
306 const videojsOptions = {
309 // We don't use text track settings for now
310 textTrackSettings: false as any, // FIXME: typings
311 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
312 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
314 muted: commonOptions.muted !== undefined
315 ? commonOptions.muted
316 : undefined, // Undefined so the player knows it has to check the local storage
318 autoplay: this.getAutoPlayValue(autoplay),
320 poster: commonOptions.poster,
321 inactivityTimeout: commonOptions.inactivityTimeout,
322 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
327 children: this.getControlBarChildren(mode, {
328 videoShortUUID: commonOptions.videoShortUUID,
329 p2pEnabled: commonOptions.p2pEnabled,
331 captions: commonOptions.captions,
332 peertubeLink: commonOptions.peertubeLink,
333 theaterButton: commonOptions.theaterButton,
335 nextVideo: commonOptions.nextVideo,
336 hasNextVideo: commonOptions.hasNextVideo,
338 previousVideo: commonOptions.previousVideo,
339 hasPreviousVideo: commonOptions.hasPreviousVideo
340 }) as any // FIXME: typings
344 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
345 Object.assign(videojsOptions, { language: commonOptions.language })
348 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
351 private static addP2PMediaLoaderOptions (
352 plugins: VideoJSPluginOptions,
353 options: PeertubePlayerManagerOptions,
354 p2pMediaLoaderModule: any
356 const p2pMediaLoaderOptions = options.p2pMediaLoader
357 const commonOptions = options.common
359 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
360 .filter(t => t.startsWith('ws'))
362 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
364 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
365 redundancyUrlManager,
366 type: 'application/x-mpegURL',
367 startTime: commonOptions.startTime,
368 src: p2pMediaLoaderOptions.playlistUrl
371 let consumeOnly = false
372 if ((navigator as any)?.connection?.type === 'cellular') {
373 console.log('We are on a cellular connection: disabling seeding.')
377 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
380 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
381 rtcConfig: getRtcConfig(),
382 requiredSegmentsPriority: 1,
383 simultaneousHttpDownloads: 1,
384 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager, 1),
385 useP2P: commonOptions.p2pEnabled,
389 swarmId: p2pMediaLoaderOptions.playlistUrl
394 levelLabelHandler: (level: { height: number, width: number }) => {
395 const resolution = Math.min(level.height || 0, level.width || 0)
397 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
398 // We don't have files for live videos
399 if (!file) return level.height
401 let label = file.resolution.label
402 if (file.fps >= 50) label += file.fps
407 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderModule, p2pMediaLoaderConfig)
411 const toAssign = { p2pMediaLoader, hlsjs }
412 Object.assign(plugins, toAssign)
417 private static getHLSOptions (p2pMediaLoaderModule: any, p2pMediaLoaderConfig: HlsJsEngineSettings) {
419 capLevelToPlayerSize: true,
420 autoStartLoad: false,
421 liveSyncDurationCount: 5,
423 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
426 const averageBandwidth = getAverageBandwidthInStore()
427 if (!averageBandwidth) return base
432 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
434 testBandwidth: false,
439 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
440 const commonOptions = options.common
441 const webtorrentOptions = options.webtorrent
442 const p2pMediaLoaderOptions = options.p2pMediaLoader
444 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
448 playerRefusedP2P: commonOptions.p2pEnabled === false,
449 videoDuration: commonOptions.videoDuration,
450 playerElement: commonOptions.playerElement,
451 videoFiles: webtorrentOptions.videoFiles.length !== 0
452 ? webtorrentOptions.videoFiles
453 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
454 : p2pMediaLoaderOptions?.videoFiles || [],
455 startTime: commonOptions.startTime
458 Object.assign(plugins, { webtorrent })
461 private static getControlBarChildren (mode: PlayerMode, options: {
463 videoShortUUID: string
465 peertubeLink: boolean
466 theaterButton: boolean
469 nextVideo?: () => void
470 hasNextVideo?: () => boolean
472 previousVideo?: () => void
473 hasPreviousVideo?: () => boolean
475 const settingEntries = []
476 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
479 settingEntries.push('playbackRateMenuButton')
480 if (options.captions === true) settingEntries.push('captionsButton')
481 settingEntries.push('resolutionMenuButton')
485 if (options.previousVideo) {
486 const buttonOptions: NextPreviousVideoButtonOptions = {
488 handler: options.previousVideo,
490 if (!options.hasPreviousVideo) return false
492 return !options.hasPreviousVideo()
496 Object.assign(children, {
497 previousVideoButton: buttonOptions
501 Object.assign(children, { playToggle: {} })
503 if (options.nextVideo) {
504 const buttonOptions: NextPreviousVideoButtonOptions = {
506 handler: options.nextVideo,
508 if (!options.hasNextVideo) return false
510 return !options.hasNextVideo()
514 Object.assign(children, {
515 nextVideoButton: buttonOptions
519 Object.assign(children, {
520 currentTimeDisplay: {},
525 flexibleWidthSpacer: {},
530 [loadProgressBar]: {},
531 mouseTimeDisplay: {},
539 p2pEnabled: options.p2pEnabled
549 entries: settingEntries
553 if (options.peertubeLink === true) {
554 Object.assign(children, {
555 peerTubeLinkButton: { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
559 if (options.theaterButton === true) {
560 Object.assign(children, {
565 Object.assign(children, {
572 private static addContextMenu (options: {
574 player: videojs.Player
575 videoShortUUID: string
576 videoEmbedUrl: string
577 videoEmbedTitle: string
579 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
581 const content = () => {
582 const isLoopEnabled = player.options_['loop']
586 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
587 listener: function () {
588 player.options_['loop'] = !isLoopEnabled
592 label: player.localize('Copy the video URL'),
593 listener: function () {
594 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
598 label: player.localize('Copy the video URL at the current time'),
599 listener: function (this: videojs.Player) {
600 const url = buildVideoLink({ shortUUID: videoShortUUID })
602 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
607 label: player.localize('Copy embed code'),
609 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
614 if (mode === 'webtorrent') {
616 label: player.localize('Copy magnet URI'),
617 listener: function (this: videojs.Player) {
618 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
625 label: player.localize('Stats for nerds'),
627 player.stats().show()
631 return items.map(i => ({
633 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
638 player.contextmenuUI({ content })
641 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
642 const isNaked = (event: KeyboardEvent, key: string) =>
643 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
645 Object.assign(plugins, {
647 skipInitialFocus: true,
648 enableInactiveFocus: false,
649 captureDocumentHotkeys: true,
650 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
651 const tagName = e.tagName.toLowerCase()
652 return e.id === 'content' || tagName === 'body' || tagName === 'video'
655 enableVolumeScroll: false,
656 enableModifiersForNumbers: false,
658 rewindKey: function (event: KeyboardEvent) {
659 return isNaked(event, 'ArrowLeft')
662 forwardKey: function (event: KeyboardEvent) {
663 return isNaked(event, 'ArrowRight')
666 fullscreenKey: function (event: KeyboardEvent) {
667 // fullscreen with the f key or Ctrl+Enter
668 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
672 increasePlaybackRateKey: {
673 key: function (event: KeyboardEvent) {
674 return isNaked(event, '>')
676 handler: function (player: videojs.Player) {
677 const newValue = Math.min(player.playbackRate() + 0.1, 5)
678 player.playbackRate(parseFloat(newValue.toFixed(2)))
681 decreasePlaybackRateKey: {
682 key: function (event: KeyboardEvent) {
683 return isNaked(event, '<')
685 handler: function (player: videojs.Player) {
686 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
687 player.playbackRate(parseFloat(newValue.toFixed(2)))
691 key: function (event: KeyboardEvent) {
692 return isNaked(event, '.')
694 handler: function (player: videojs.Player) {
696 // Calculate movement distance (assuming 30 fps)
698 player.currentTime(player.currentTime() + dist)
706 private static getAutoPlayValue (autoplay: any) {
707 if (autoplay !== true) return autoplay
709 // On first play, disable autoplay to avoid issues
710 // But if the player already played videos, we can safely autoplay next ones
711 if (isIOS() || isSafari()) {
712 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
719 // ############################################################################