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, getRtcConfig, isSafari, isIOS } from './utils'
39 import { copyToClipboard } from '../../root-helpers/utils'
41 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
42 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
44 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
45 // Change Captions to Subtitles/CC
46 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
47 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
48 CaptionsButton.prototype.label_ = ' '
50 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
52 export type WebtorrentOptions = {
53 videoFiles: VideoFile[]
56 export type P2PMediaLoaderOptions = {
58 segmentsSha256Url: string
59 trackerAnnounce: string[]
60 redundancyBaseUrls: string[]
61 videoFiles: VideoFile[]
64 export interface CustomizationOptions {
65 startTime: number | string
66 stopTime: number | string
77 export interface CommonOptions extends CustomizationOptions {
78 playerElement: HTMLVideoElement
79 onPlayerElementChange: (element: HTMLVideoElement) => void
83 nextVideo?: () => void
84 hasNextVideo?: () => boolean
86 previousVideo?: () => void
87 hasPreviousVideo?: () => boolean
89 playlist?: PlaylistPluginOptions
92 enableHotkeys: boolean
93 inactivityTimeout: number
96 theaterButton: boolean
107 videoCaptions: VideoJSCaption[]
111 userWatching?: UserWatching
116 export type PeertubePlayerManagerOptions = {
117 common: CommonOptions,
118 webtorrent: WebtorrentOptions,
119 p2pMediaLoader?: P2PMediaLoaderOptions
122 export class PeertubePlayerManager {
123 private static playerElementClassName: string
124 private static onPlayerChange: (player: videojs.Player) => void
126 private static alreadyPlayed = false
128 static initState () {
129 PeertubePlayerManager.alreadyPlayed = false
132 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
133 let p2pMediaLoader: any
135 this.onPlayerChange = onPlayerChange
136 this.playerElementClassName = options.common.playerElement.className
138 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
139 if (mode === 'p2p-media-loader') {
140 [ p2pMediaLoader ] = await Promise.all([
141 import('p2p-media-loader-hlsjs'),
142 import('./p2p-media-loader/p2p-media-loader-plugin')
146 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
148 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
151 return new Promise(res => {
152 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
155 let alreadyFallback = false
157 player.tech(true).one('error', () => {
158 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
159 alreadyFallback = true
162 player.one('error', () => {
163 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
164 alreadyFallback = true
167 player.one('play', () => {
168 PeertubePlayerManager.alreadyPlayed = true
171 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
180 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
181 if (currentMode === 'webtorrent') return
183 console.log('Fallback to webtorrent.')
185 const newVideoElement = document.createElement('video')
186 newVideoElement.className = this.playerElementClassName
188 // VideoJS wraps our video element inside a div
189 let currentParentPlayerElement = options.common.playerElement.parentNode
190 // Fix on IOS, don't ask me why
191 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
193 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
195 options.common.playerElement = newVideoElement
196 options.common.onPlayerElementChange(newVideoElement)
200 await import('./webtorrent/webtorrent-plugin')
202 const mode = 'webtorrent'
203 const videojsOptions = this.getVideojsOptions(mode, options)
206 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
209 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
211 PeertubePlayerManager.onPlayerChange(player)
215 private static getVideojsOptions (
217 options: PeertubePlayerManagerOptions,
218 p2pMediaLoaderModule?: any
219 ): videojs.PlayerOptions {
220 const commonOptions = options.common
221 const isHLS = mode === 'p2p-media-loader'
223 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
226 const plugins: VideoJSPluginOptions = {
229 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
230 videoViewUrl: commonOptions.videoViewUrl,
231 videoDuration: commonOptions.videoDuration,
232 userWatching: commonOptions.userWatching,
233 subtitle: commonOptions.subtitle,
234 videoCaptions: commonOptions.videoCaptions,
235 stopTime: commonOptions.stopTime,
236 isLive: commonOptions.isLive,
237 videoUUID: commonOptions.videoUUID
241 if (commonOptions.playlist) {
242 plugins.playlist = commonOptions.playlist
245 if (commonOptions.enableHotkeys === true) {
246 PeertubePlayerManager.addHotkeysOptions(plugins)
250 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
255 if (mode === 'webtorrent') {
256 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
258 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
262 const videojsOptions = {
265 // We don't use text track settings for now
266 textTrackSettings: false as any, // FIXME: typings
267 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
268 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
270 muted: commonOptions.muted !== undefined
271 ? commonOptions.muted
272 : undefined, // Undefined so the player knows it has to check the local storage
274 autoplay: this.getAutoPlayValue(autoplay),
276 poster: commonOptions.poster,
277 inactivityTimeout: commonOptions.inactivityTimeout,
278 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
283 children: this.getControlBarChildren(mode, {
284 captions: commonOptions.captions,
285 peertubeLink: commonOptions.peertubeLink,
286 theaterButton: commonOptions.theaterButton,
288 nextVideo: commonOptions.nextVideo,
289 hasNextVideo: commonOptions.hasNextVideo,
291 previousVideo: commonOptions.previousVideo,
292 hasPreviousVideo: commonOptions.hasPreviousVideo
293 }) as any // FIXME: typings
297 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
298 Object.assign(videojsOptions, { language: commonOptions.language })
301 return videojsOptions
304 private static addP2PMediaLoaderOptions (
305 plugins: VideoJSPluginOptions,
306 options: PeertubePlayerManagerOptions,
307 p2pMediaLoaderModule: any
309 const p2pMediaLoaderOptions = options.p2pMediaLoader
310 const commonOptions = options.common
312 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
313 .filter(t => t.startsWith('ws'))
315 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
317 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
318 redundancyUrlManager,
319 type: 'application/x-mpegURL',
320 startTime: commonOptions.startTime,
321 src: p2pMediaLoaderOptions.playlistUrl
324 let consumeOnly = false
326 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
327 console.log('We are on a cellular connection: disabling seeding.')
331 const p2pMediaLoaderConfig = {
334 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
335 rtcConfig: getRtcConfig(),
336 requiredSegmentsPriority: 1,
337 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
338 useP2P: getStoredP2PEnabled(),
342 swarmId: p2pMediaLoaderOptions.playlistUrl
346 levelLabelHandler: (level: { height: number, width: number }) => {
347 const resolution = Math.min(level.height || 0, level.width || 0)
349 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
350 // We don't have files for live videos
351 if (!file) return level.height
353 let label = file.resolution.label
354 if (file.fps >= 50) label += file.fps
360 capLevelToPlayerSize: true,
361 autoStartLoad: false,
362 liveSyncDurationCount: 5,
363 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
368 const toAssign = { p2pMediaLoader, hlsjs }
369 Object.assign(plugins, toAssign)
374 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
375 const commonOptions = options.common
376 const webtorrentOptions = options.webtorrent
378 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
384 videoDuration: commonOptions.videoDuration,
385 playerElement: commonOptions.playerElement,
386 videoFiles: webtorrentOptions.videoFiles,
387 startTime: commonOptions.startTime
390 Object.assign(plugins, { webtorrent })
393 private static getControlBarChildren (mode: PlayerMode, options: {
394 peertubeLink: boolean
395 theaterButton: boolean
399 hasNextVideo?: () => boolean
401 previousVideo?: Function
402 hasPreviousVideo?: () => boolean
404 const settingEntries = []
405 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
408 settingEntries.push('playbackRateMenuButton')
409 if (options.captions === true) settingEntries.push('captionsButton')
410 settingEntries.push('resolutionMenuButton')
414 if (options.previousVideo) {
415 const buttonOptions: NextPreviousVideoButtonOptions = {
417 handler: options.previousVideo,
419 if (!options.hasPreviousVideo) return false
421 return !options.hasPreviousVideo()
425 Object.assign(children, {
426 'previousVideoButton': buttonOptions
430 Object.assign(children, { playToggle: {} })
432 if (options.nextVideo) {
433 const buttonOptions: NextPreviousVideoButtonOptions = {
435 handler: options.nextVideo,
437 if (!options.hasNextVideo) return false
439 return !options.hasNextVideo()
443 Object.assign(children, {
444 'nextVideoButton': buttonOptions
448 Object.assign(children, {
449 'currentTimeDisplay': {},
451 'durationDisplay': {},
454 'flexibleWidthSpacer': {},
459 [loadProgressBar]: {},
460 'mouseTimeDisplay': {},
461 'playProgressBar': {}
476 entries: settingEntries
480 if (options.peertubeLink === true) {
481 Object.assign(children, {
482 'peerTubeLinkButton': {}
486 if (options.theaterButton === true) {
487 Object.assign(children, {
492 Object.assign(children, {
493 'fullscreenToggle': {}
499 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
502 label: player.localize('Copy the video URL'),
503 listener: function () {
504 copyToClipboard(buildVideoLink())
508 label: player.localize('Copy the video URL at the current time'),
509 listener: function (this: videojs.Player) {
510 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
514 label: player.localize('Copy embed code'),
516 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
521 if (mode === 'webtorrent') {
523 label: player.localize('Copy magnet URI'),
524 listener: function (this: videojs.Player) {
525 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
530 player.contextmenuUI({ content })
533 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
534 const isNaked = (event: KeyboardEvent, key: string) =>
535 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
537 Object.assign(plugins, {
539 skipInitialFocus: true,
540 enableInactiveFocus: false,
541 captureDocumentHotkeys: true,
542 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
543 const tagName = e.tagName.toLowerCase()
544 return e.id === 'content' || tagName === 'body' || tagName === 'video'
547 enableVolumeScroll: false,
548 enableModifiersForNumbers: false,
550 rewindKey: function (event: KeyboardEvent) {
551 return isNaked(event, 'ArrowLeft')
554 forwardKey: function (event: KeyboardEvent) {
555 return isNaked(event, 'ArrowRight')
558 fullscreenKey: function (event: KeyboardEvent) {
559 // fullscreen with the f key or Ctrl+Enter
560 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
564 increasePlaybackRateKey: {
565 key: function (event: KeyboardEvent) {
566 return isNaked(event, '>')
568 handler: function (player: videojs.Player) {
569 const newValue = Math.min(player.playbackRate() + 0.1, 5)
570 player.playbackRate(parseFloat(newValue.toFixed(2)))
573 decreasePlaybackRateKey: {
574 key: function (event: KeyboardEvent) {
575 return isNaked(event, '<')
577 handler: function (player: videojs.Player) {
578 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
579 player.playbackRate(parseFloat(newValue.toFixed(2)))
583 key: function (event: KeyboardEvent) {
584 return isNaked(event, '.')
586 handler: function (player: videojs.Player) {
588 // Calculate movement distance (assuming 30 fps)
590 player.currentTime(player.currentTime() + dist)
598 private static getAutoPlayValue (autoplay: any) {
599 if (autoplay !== true) return autoplay
601 // On first play, disable autoplay to avoid issues
602 // But if the player already played videos, we can safely autoplay next ones
603 if (isIOS() || isSafari()) {
604 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
611 // ############################################################################