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, isIOS, isSafari } 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 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
121 let p2pMediaLoader: any
123 this.onPlayerChange = onPlayerChange
124 this.playerElementClassName = options.common.playerElement.className
126 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
127 if (mode === 'p2p-media-loader') {
128 [ p2pMediaLoader ] = await Promise.all([
129 import('p2p-media-loader-hlsjs'),
130 import('./p2p-media-loader/p2p-media-loader-plugin')
134 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
136 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
139 return new Promise(res => {
140 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
143 let alreadyFallback = false
145 player.tech(true).one('error', () => {
146 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
147 alreadyFallback = true
150 player.one('error', () => {
151 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
152 alreadyFallback = true
155 self.addContextMenu(mode, player, options.common.embedUrl)
164 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
165 if (currentMode === 'webtorrent') return
167 console.log('Fallback to webtorrent.')
169 const newVideoElement = document.createElement('video')
170 newVideoElement.className = this.playerElementClassName
172 // VideoJS wraps our video element inside a div
173 let currentParentPlayerElement = options.common.playerElement.parentNode
174 // Fix on IOS, don't ask me why
175 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
177 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
179 options.common.playerElement = newVideoElement
180 options.common.onPlayerElementChange(newVideoElement)
184 await import('./webtorrent/webtorrent-plugin')
186 const mode = 'webtorrent'
187 const videojsOptions = this.getVideojsOptions(mode, options)
190 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
193 self.addContextMenu(mode, player, options.common.embedUrl)
195 PeertubePlayerManager.onPlayerChange(player)
199 private static getVideojsOptions (
201 options: PeertubePlayerManagerOptions,
202 p2pMediaLoaderModule?: any
203 ): videojs.PlayerOptions {
204 const commonOptions = options.common
206 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
209 const plugins: VideoJSPluginOptions = {
212 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
213 videoViewUrl: commonOptions.videoViewUrl,
214 videoDuration: commonOptions.videoDuration,
215 userWatching: commonOptions.userWatching,
216 subtitle: commonOptions.subtitle,
217 videoCaptions: commonOptions.videoCaptions,
218 stopTime: commonOptions.stopTime
222 if (commonOptions.playlist) {
223 plugins.playlist = commonOptions.playlist
226 if (commonOptions.enableHotkeys === true) {
227 PeertubePlayerManager.addHotkeysOptions(plugins)
230 if (mode === 'p2p-media-loader') {
231 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
236 if (mode === 'webtorrent') {
237 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
239 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
243 const videojsOptions = {
246 // We don't use text track settings for now
247 textTrackSettings: false as any, // FIXME: typings
248 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
249 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
251 muted: commonOptions.muted !== undefined
252 ? commonOptions.muted
253 : undefined, // Undefined so the player knows it has to check the local storage
255 autoplay: this.getAutoPlayValue(autoplay),
257 poster: commonOptions.poster,
258 inactivityTimeout: commonOptions.inactivityTimeout,
259 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
264 children: this.getControlBarChildren(mode, {
265 captions: commonOptions.captions,
266 peertubeLink: commonOptions.peertubeLink,
267 theaterButton: commonOptions.theaterButton,
269 nextVideo: commonOptions.nextVideo,
270 hasNextVideo: commonOptions.hasNextVideo,
272 previousVideo: commonOptions.previousVideo,
273 hasPreviousVideo: commonOptions.hasPreviousVideo
274 }) as any // FIXME: typings
278 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
279 Object.assign(videojsOptions, { language: commonOptions.language })
282 return videojsOptions
285 private static addP2PMediaLoaderOptions (
286 plugins: VideoJSPluginOptions,
287 options: PeertubePlayerManagerOptions,
288 p2pMediaLoaderModule: any
290 const p2pMediaLoaderOptions = options.p2pMediaLoader
291 const commonOptions = options.common
293 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
294 .filter(t => t.startsWith('ws'))
296 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
298 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
299 redundancyUrlManager,
300 type: 'application/x-mpegURL',
301 startTime: commonOptions.startTime,
302 src: p2pMediaLoaderOptions.playlistUrl
305 let consumeOnly = false
307 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
308 console.log('We are on a cellular connection: disabling seeding.')
312 const p2pMediaLoaderConfig = {
315 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
316 rtcConfig: getRtcConfig(),
317 requiredSegmentsPriority: 5,
318 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
319 useP2P: getStoredP2PEnabled(),
323 swarmId: p2pMediaLoaderOptions.playlistUrl
327 levelLabelHandler: (level: { height: number, width: number }) => {
328 const resolution = Math.min(level.height || 0, level.width || 0)
330 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
332 console.error('Cannot find video file for level %d.', level.height)
336 let label = file.resolution.label
337 if (file.fps >= 50) label += file.fps
343 capLevelToPlayerSize: true,
344 autoStartLoad: false,
345 liveSyncDurationCount: 7,
346 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
351 const toAssign = { p2pMediaLoader, hlsjs }
352 Object.assign(plugins, toAssign)
357 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
358 const commonOptions = options.common
359 const webtorrentOptions = options.webtorrent
362 autoplay: commonOptions.autoplay,
363 videoDuration: commonOptions.videoDuration,
364 playerElement: commonOptions.playerElement,
365 videoFiles: webtorrentOptions.videoFiles,
366 startTime: commonOptions.startTime
369 Object.assign(plugins, { webtorrent })
372 private static getControlBarChildren (mode: PlayerMode, options: {
373 peertubeLink: boolean
374 theaterButton: boolean
378 hasNextVideo?: () => boolean
380 previousVideo?: Function
381 hasPreviousVideo?: () => boolean
383 const settingEntries = []
384 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
387 settingEntries.push('playbackRateMenuButton')
388 if (options.captions === true) settingEntries.push('captionsButton')
389 settingEntries.push('resolutionMenuButton')
393 if (options.previousVideo) {
394 const buttonOptions: NextPreviousVideoButtonOptions = {
396 handler: options.previousVideo,
398 if (!options.hasPreviousVideo) return false
400 return !options.hasPreviousVideo()
404 Object.assign(children, {
405 'previousVideoButton': buttonOptions
409 Object.assign(children, { playToggle: {} })
411 if (options.nextVideo) {
412 const buttonOptions: NextPreviousVideoButtonOptions = {
414 handler: options.nextVideo,
416 if (!options.hasNextVideo) return false
418 return !options.hasNextVideo()
422 Object.assign(children, {
423 'nextVideoButton': buttonOptions
427 Object.assign(children, {
428 'currentTimeDisplay': {},
430 'durationDisplay': {},
433 'flexibleWidthSpacer': {},
438 [loadProgressBar]: {},
439 'mouseTimeDisplay': {},
440 'playProgressBar': {}
455 entries: settingEntries
459 if (options.peertubeLink === true) {
460 Object.assign(children, {
461 'peerTubeLinkButton': {}
465 if (options.theaterButton === true) {
466 Object.assign(children, {
471 Object.assign(children, {
472 'fullscreenToggle': {}
478 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
481 label: player.localize('Copy the video URL'),
482 listener: function () {
483 copyToClipboard(buildVideoLink())
487 label: player.localize('Copy the video URL at the current time'),
488 listener: function (this: videojs.Player) {
489 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
493 label: player.localize('Copy embed code'),
495 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl))
500 if (mode === 'webtorrent') {
502 label: player.localize('Copy magnet URI'),
503 listener: function (this: videojs.Player) {
504 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
509 player.contextmenuUI({ content })
512 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
513 Object.assign(plugins, {
515 skipInitialFocus: true,
516 enableInactiveFocus: false,
517 captureDocumentHotkeys: true,
518 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
519 const tagName = e.tagName.toLowerCase()
520 return e.id === 'content' || tagName === 'body' || tagName === 'video'
523 enableVolumeScroll: false,
524 enableModifiersForNumbers: false,
526 fullscreenKey: function (event: KeyboardEvent) {
527 // fullscreen with the f key or Ctrl+Enter
528 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
531 seekStep: function (event: KeyboardEvent) {
532 // mimic VLC seek behavior, and default to 5 (original value is 5).
533 if (event.ctrlKey && event.altKey) {
535 } else if (event.ctrlKey) {
537 } else if (event.altKey) {
545 increasePlaybackRateKey: {
546 key: function (event: KeyboardEvent) {
547 return event.key === '>'
549 handler: function (player: videojs.Player) {
550 const newValue = Math.min(player.playbackRate() + 0.1, 5)
551 player.playbackRate(parseFloat(newValue.toFixed(2)))
554 decreasePlaybackRateKey: {
555 key: function (event: KeyboardEvent) {
556 return event.key === '<'
558 handler: function (player: videojs.Player) {
559 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
560 player.playbackRate(parseFloat(newValue.toFixed(2)))
564 key: function (event: KeyboardEvent) {
565 return event.key === '.'
567 handler: function (player: videojs.Player) {
569 // Calculate movement distance (assuming 30 fps)
571 player.currentTime(player.currentTime() + dist)
579 private static getAutoPlayValue (autoplay: any) {
580 if (autoplay !== true) return autoplay
582 // Giving up with iOS
583 if (isIOS()) return false
585 // We have issues with autoplay and Safari.
586 // any that tries to play using auto mute seems to work
587 if (isSafari()) return 'any'
593 // ############################################################################