1 import 'videojs-hotkeys/videojs.hotkeys'
3 import 'videojs-contextmenu-pt'
4 import 'videojs-contrib-quality-levels'
5 import './upnext/end-card'
6 import './upnext/upnext-plugin'
7 import './stats/stats-card'
8 import './stats/stats-plugin'
9 import './bezels/bezels-plugin'
10 import './peertube-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 videojs from 'video.js'
25 import { isDefaultLocale } from '@shared/core-utils/i18n'
26 import { VideoFile } from '@shared/models'
27 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
28 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
29 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
30 import { getStoredP2PEnabled } from './peertube-player-local-storage'
32 NextPreviousVideoButtonOptions,
33 P2PMediaLoaderPluginOptions,
34 PlaylistPluginOptions,
38 } from './peertube-videojs-typings'
39 import { TranslationsManager } from './translations-manager'
40 import { buildVideoOrPlaylistEmbed, buildVideoLink, getRtcConfig, isSafari, isIOS } from './utils'
41 import { copyToClipboard } from '../../root-helpers/utils'
43 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
44 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
46 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
47 // Change Captions to Subtitles/CC
48 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
49 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
50 CaptionsButton.prototype.label_ = ' '
52 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
54 export type WebtorrentOptions = {
55 videoFiles: VideoFile[]
58 export type P2PMediaLoaderOptions = {
60 segmentsSha256Url: string
61 trackerAnnounce: string[]
62 redundancyBaseUrls: string[]
63 videoFiles: VideoFile[]
66 export interface CustomizationOptions {
67 startTime: number | string
68 stopTime: number | string
79 export interface CommonOptions extends CustomizationOptions {
80 playerElement: HTMLVideoElement
81 onPlayerElementChange: (element: HTMLVideoElement) => void
85 nextVideo?: () => void
86 hasNextVideo?: () => boolean
88 previousVideo?: () => void
89 hasPreviousVideo?: () => boolean
91 playlist?: PlaylistPluginOptions
94 enableHotkeys: boolean
95 inactivityTimeout: number
98 theaterButton: boolean
109 videoCaptions: VideoJSCaption[]
113 userWatching?: UserWatching
118 export type PeertubePlayerManagerOptions = {
119 common: CommonOptions,
120 webtorrent: WebtorrentOptions,
121 p2pMediaLoader?: P2PMediaLoaderOptions
124 export class PeertubePlayerManager {
125 private static playerElementClassName: string
126 private static onPlayerChange: (player: videojs.Player) => void
127 private static alreadyPlayed = false
129 static initState () {
130 PeertubePlayerManager.alreadyPlayed = false
133 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
134 let p2pMediaLoader: any
136 this.onPlayerChange = onPlayerChange
137 this.playerElementClassName = options.common.playerElement.className
139 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
140 if (mode === 'p2p-media-loader') {
141 [ p2pMediaLoader ] = await Promise.all([
142 import('p2p-media-loader-hlsjs'),
143 import('./p2p-media-loader/p2p-media-loader-plugin')
147 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
149 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
152 return new Promise(res => {
153 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
156 let alreadyFallback = false
158 player.tech(true).one('error', () => {
159 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
160 alreadyFallback = true
163 player.one('error', () => {
164 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
165 alreadyFallback = true
168 player.one('play', () => {
169 PeertubePlayerManager.alreadyPlayed = true
172 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
176 videoUUID: options.common.videoUUID,
177 videoIsLive: options.common.isLive,
186 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
187 if (currentMode === 'webtorrent') return
189 console.log('Fallback to webtorrent.')
191 const newVideoElement = document.createElement('video')
192 newVideoElement.className = this.playerElementClassName
194 // VideoJS wraps our video element inside a div
195 let currentParentPlayerElement = options.common.playerElement.parentNode
196 // Fix on IOS, don't ask me why
197 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
199 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
201 options.common.playerElement = newVideoElement
202 options.common.onPlayerElementChange(newVideoElement)
206 await import('./webtorrent/webtorrent-plugin')
208 const mode = 'webtorrent'
209 const videojsOptions = this.getVideojsOptions(mode, options)
212 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
215 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
217 PeertubePlayerManager.onPlayerChange(player)
221 private static getVideojsOptions (
223 options: PeertubePlayerManagerOptions,
224 p2pMediaLoaderModule?: any
225 ): videojs.PlayerOptions {
226 const commonOptions = options.common
227 const isHLS = mode === 'p2p-media-loader'
229 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
231 preloadTextTracks: false
234 const plugins: VideoJSPluginOptions = {
237 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
238 videoViewUrl: commonOptions.videoViewUrl,
239 videoDuration: commonOptions.videoDuration,
240 userWatching: commonOptions.userWatching,
241 subtitle: commonOptions.subtitle,
242 videoCaptions: commonOptions.videoCaptions,
243 stopTime: commonOptions.stopTime,
244 isLive: commonOptions.isLive,
245 videoUUID: commonOptions.videoUUID
249 if (commonOptions.playlist) {
250 plugins.playlist = commonOptions.playlist
253 if (commonOptions.enableHotkeys === true) {
254 PeertubePlayerManager.addHotkeysOptions(plugins)
258 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
260 Object.assign(html5, hlsjs.html5)
263 if (mode === 'webtorrent') {
264 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
266 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
270 const videojsOptions = {
273 // We don't use text track settings for now
274 textTrackSettings: false as any, // FIXME: typings
275 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
276 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
278 muted: commonOptions.muted !== undefined
279 ? commonOptions.muted
280 : undefined, // Undefined so the player knows it has to check the local storage
282 autoplay: this.getAutoPlayValue(autoplay),
284 poster: commonOptions.poster,
285 inactivityTimeout: commonOptions.inactivityTimeout,
286 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
291 children: this.getControlBarChildren(mode, {
292 captions: commonOptions.captions,
293 peertubeLink: commonOptions.peertubeLink,
294 theaterButton: commonOptions.theaterButton,
296 nextVideo: commonOptions.nextVideo,
297 hasNextVideo: commonOptions.hasNextVideo,
299 previousVideo: commonOptions.previousVideo,
300 hasPreviousVideo: commonOptions.hasPreviousVideo
301 }) as any // FIXME: typings
305 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
306 Object.assign(videojsOptions, { language: commonOptions.language })
309 return videojsOptions
312 private static addP2PMediaLoaderOptions (
313 plugins: VideoJSPluginOptions,
314 options: PeertubePlayerManagerOptions,
315 p2pMediaLoaderModule: any
317 const p2pMediaLoaderOptions = options.p2pMediaLoader
318 const commonOptions = options.common
320 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
321 .filter(t => t.startsWith('ws'))
323 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
325 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
326 redundancyUrlManager,
327 type: 'application/x-mpegURL',
328 startTime: commonOptions.startTime,
329 src: p2pMediaLoaderOptions.playlistUrl
332 let consumeOnly = false
334 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
335 console.log('We are on a cellular connection: disabling seeding.')
339 const p2pMediaLoaderConfig = {
342 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
343 rtcConfig: getRtcConfig(),
344 requiredSegmentsPriority: 1,
345 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
346 useP2P: getStoredP2PEnabled(),
350 swarmId: p2pMediaLoaderOptions.playlistUrl
354 levelLabelHandler: (level: { height: number, width: number }) => {
355 const resolution = Math.min(level.height || 0, level.width || 0)
357 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
358 // We don't have files for live videos
359 if (!file) return level.height
361 let label = file.resolution.label
362 if (file.fps >= 50) label += file.fps
368 capLevelToPlayerSize: true,
369 autoStartLoad: false,
370 liveSyncDurationCount: 5,
371 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
376 const toAssign = { p2pMediaLoader, hlsjs }
377 Object.assign(plugins, toAssign)
382 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
383 const commonOptions = options.common
384 const webtorrentOptions = options.webtorrent
386 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
392 videoDuration: commonOptions.videoDuration,
393 playerElement: commonOptions.playerElement,
394 videoFiles: webtorrentOptions.videoFiles,
395 startTime: commonOptions.startTime
398 Object.assign(plugins, { webtorrent })
401 private static getControlBarChildren (mode: PlayerMode, options: {
402 peertubeLink: boolean
403 theaterButton: boolean
407 hasNextVideo?: () => boolean
409 previousVideo?: Function
410 hasPreviousVideo?: () => boolean
412 const settingEntries = []
413 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
416 settingEntries.push('playbackRateMenuButton')
417 if (options.captions === true) settingEntries.push('captionsButton')
418 settingEntries.push('resolutionMenuButton')
422 if (options.previousVideo) {
423 const buttonOptions: NextPreviousVideoButtonOptions = {
425 handler: options.previousVideo,
427 if (!options.hasPreviousVideo) return false
429 return !options.hasPreviousVideo()
433 Object.assign(children, {
434 'previousVideoButton': buttonOptions
438 Object.assign(children, { playToggle: {} })
440 if (options.nextVideo) {
441 const buttonOptions: NextPreviousVideoButtonOptions = {
443 handler: options.nextVideo,
445 if (!options.hasNextVideo) return false
447 return !options.hasNextVideo()
451 Object.assign(children, {
452 'nextVideoButton': buttonOptions
456 Object.assign(children, {
457 'currentTimeDisplay': {},
459 'durationDisplay': {},
462 'flexibleWidthSpacer': {},
467 [loadProgressBar]: {},
468 'mouseTimeDisplay': {},
469 'playProgressBar': {}
484 entries: settingEntries
488 if (options.peertubeLink === true) {
489 Object.assign(children, {
490 'peerTubeLinkButton': {}
494 if (options.theaterButton === true) {
495 Object.assign(children, {
500 Object.assign(children, {
501 'fullscreenToggle': {}
507 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
508 const content = () => {
509 const isLoopEnabled = player.options_['loop']
513 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
514 listener: function () {
515 player.options_['loop'] = !isLoopEnabled
519 label: player.localize('Copy the video URL'),
520 listener: function () {
521 copyToClipboard(buildVideoLink())
525 label: player.localize('Copy the video URL at the current time'),
526 listener: function (this: videojs.Player) {
527 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
532 label: player.localize('Copy embed code'),
534 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
539 if (mode === 'webtorrent') {
541 label: player.localize('Copy magnet URI'),
542 listener: function (this: videojs.Player) {
543 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
550 label: player.localize('Stats for nerds'),
552 player.stats().show()
556 return items.map(i => ({
558 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
563 player.contextmenuUI({ content })
566 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
567 const isNaked = (event: KeyboardEvent, key: string) =>
568 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
570 Object.assign(plugins, {
572 skipInitialFocus: true,
573 enableInactiveFocus: false,
574 captureDocumentHotkeys: true,
575 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
576 const tagName = e.tagName.toLowerCase()
577 return e.id === 'content' || tagName === 'body' || tagName === 'video'
580 enableVolumeScroll: false,
581 enableModifiersForNumbers: false,
583 rewindKey: function (event: KeyboardEvent) {
584 return isNaked(event, 'ArrowLeft')
587 forwardKey: function (event: KeyboardEvent) {
588 return isNaked(event, 'ArrowRight')
591 fullscreenKey: function (event: KeyboardEvent) {
592 // fullscreen with the f key or Ctrl+Enter
593 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
597 increasePlaybackRateKey: {
598 key: function (event: KeyboardEvent) {
599 return isNaked(event, '>')
601 handler: function (player: videojs.Player) {
602 const newValue = Math.min(player.playbackRate() + 0.1, 5)
603 player.playbackRate(parseFloat(newValue.toFixed(2)))
606 decreasePlaybackRateKey: {
607 key: function (event: KeyboardEvent) {
608 return isNaked(event, '<')
610 handler: function (player: videojs.Player) {
611 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
612 player.playbackRate(parseFloat(newValue.toFixed(2)))
616 key: function (event: KeyboardEvent) {
617 return isNaked(event, '.')
619 handler: function (player: videojs.Player) {
621 // Calculate movement distance (assuming 30 fps)
623 player.currentTime(player.currentTime() + dist)
631 private static getAutoPlayValue (autoplay: any) {
632 if (autoplay !== true) return autoplay
634 // On first play, disable autoplay to avoid issues
635 // But if the player already played videos, we can safely autoplay next ones
636 if (isIOS() || isSafari()) {
637 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
644 // ############################################################################