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 './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
125 private static alreadyPlayed = false
127 static initState () {
128 PeertubePlayerManager.alreadyPlayed = false
131 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
132 let p2pMediaLoader: any
134 this.onPlayerChange = onPlayerChange
135 this.playerElementClassName = options.common.playerElement.className
137 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
138 if (mode === 'p2p-media-loader') {
139 [ p2pMediaLoader ] = await Promise.all([
140 import('p2p-media-loader-hlsjs'),
141 import('./p2p-media-loader/p2p-media-loader-plugin')
145 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
147 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
150 return new Promise(res => {
151 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
154 let alreadyFallback = false
156 player.tech(true).one('error', () => {
157 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
158 alreadyFallback = true
161 player.one('error', () => {
162 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
163 alreadyFallback = true
166 player.one('play', () => {
167 PeertubePlayerManager.alreadyPlayed = true
170 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
179 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
180 if (currentMode === 'webtorrent') return
182 console.log('Fallback to webtorrent.')
184 const newVideoElement = document.createElement('video')
185 newVideoElement.className = this.playerElementClassName
187 // VideoJS wraps our video element inside a div
188 let currentParentPlayerElement = options.common.playerElement.parentNode
189 // Fix on IOS, don't ask me why
190 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
192 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
194 options.common.playerElement = newVideoElement
195 options.common.onPlayerElementChange(newVideoElement)
199 await import('./webtorrent/webtorrent-plugin')
201 const mode = 'webtorrent'
202 const videojsOptions = this.getVideojsOptions(mode, options)
205 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
208 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
210 PeertubePlayerManager.onPlayerChange(player)
214 private static getVideojsOptions (
216 options: PeertubePlayerManagerOptions,
217 p2pMediaLoaderModule?: any
218 ): videojs.PlayerOptions {
219 const commonOptions = options.common
220 const isHLS = mode === 'p2p-media-loader'
222 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
224 preloadTextTracks: false
227 const plugins: VideoJSPluginOptions = {
230 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
231 videoViewUrl: commonOptions.videoViewUrl,
232 videoDuration: commonOptions.videoDuration,
233 userWatching: commonOptions.userWatching,
234 subtitle: commonOptions.subtitle,
235 videoCaptions: commonOptions.videoCaptions,
236 stopTime: commonOptions.stopTime,
237 isLive: commonOptions.isLive,
238 videoUUID: commonOptions.videoUUID
242 if (commonOptions.playlist) {
243 plugins.playlist = commonOptions.playlist
246 if (commonOptions.enableHotkeys === true) {
247 PeertubePlayerManager.addHotkeysOptions(plugins)
251 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
253 Object.assign(html5, hlsjs.html5)
256 if (mode === 'webtorrent') {
257 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
259 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
263 const videojsOptions = {
266 // We don't use text track settings for now
267 textTrackSettings: false as any, // FIXME: typings
268 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
269 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
271 muted: commonOptions.muted !== undefined
272 ? commonOptions.muted
273 : undefined, // Undefined so the player knows it has to check the local storage
275 autoplay: this.getAutoPlayValue(autoplay),
277 poster: commonOptions.poster,
278 inactivityTimeout: commonOptions.inactivityTimeout,
279 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
284 children: this.getControlBarChildren(mode, {
285 captions: commonOptions.captions,
286 peertubeLink: commonOptions.peertubeLink,
287 theaterButton: commonOptions.theaterButton,
289 nextVideo: commonOptions.nextVideo,
290 hasNextVideo: commonOptions.hasNextVideo,
292 previousVideo: commonOptions.previousVideo,
293 hasPreviousVideo: commonOptions.hasPreviousVideo
294 }) as any // FIXME: typings
298 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
299 Object.assign(videojsOptions, { language: commonOptions.language })
302 return videojsOptions
305 private static addP2PMediaLoaderOptions (
306 plugins: VideoJSPluginOptions,
307 options: PeertubePlayerManagerOptions,
308 p2pMediaLoaderModule: any
310 const p2pMediaLoaderOptions = options.p2pMediaLoader
311 const commonOptions = options.common
313 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
314 .filter(t => t.startsWith('ws'))
316 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
318 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
319 redundancyUrlManager,
320 type: 'application/x-mpegURL',
321 startTime: commonOptions.startTime,
322 src: p2pMediaLoaderOptions.playlistUrl
325 let consumeOnly = false
327 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
328 console.log('We are on a cellular connection: disabling seeding.')
332 const p2pMediaLoaderConfig = {
335 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
336 rtcConfig: getRtcConfig(),
337 requiredSegmentsPriority: 1,
338 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
339 useP2P: getStoredP2PEnabled(),
343 swarmId: p2pMediaLoaderOptions.playlistUrl
347 levelLabelHandler: (level: { height: number, width: number }) => {
348 const resolution = Math.min(level.height || 0, level.width || 0)
350 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
351 // We don't have files for live videos
352 if (!file) return level.height
354 let label = file.resolution.label
355 if (file.fps >= 50) label += file.fps
361 capLevelToPlayerSize: true,
362 autoStartLoad: false,
363 liveSyncDurationCount: 5,
364 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
369 const toAssign = { p2pMediaLoader, hlsjs }
370 Object.assign(plugins, toAssign)
375 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
376 const commonOptions = options.common
377 const webtorrentOptions = options.webtorrent
379 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
385 videoDuration: commonOptions.videoDuration,
386 playerElement: commonOptions.playerElement,
387 videoFiles: webtorrentOptions.videoFiles,
388 startTime: commonOptions.startTime
391 Object.assign(plugins, { webtorrent })
394 private static getControlBarChildren (mode: PlayerMode, options: {
395 peertubeLink: boolean
396 theaterButton: boolean
400 hasNextVideo?: () => boolean
402 previousVideo?: Function
403 hasPreviousVideo?: () => boolean
405 const settingEntries = []
406 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
409 settingEntries.push('playbackRateMenuButton')
410 if (options.captions === true) settingEntries.push('captionsButton')
411 settingEntries.push('resolutionMenuButton')
415 if (options.previousVideo) {
416 const buttonOptions: NextPreviousVideoButtonOptions = {
418 handler: options.previousVideo,
420 if (!options.hasPreviousVideo) return false
422 return !options.hasPreviousVideo()
426 Object.assign(children, {
427 'previousVideoButton': buttonOptions
431 Object.assign(children, { playToggle: {} })
433 if (options.nextVideo) {
434 const buttonOptions: NextPreviousVideoButtonOptions = {
436 handler: options.nextVideo,
438 if (!options.hasNextVideo) return false
440 return !options.hasNextVideo()
444 Object.assign(children, {
445 'nextVideoButton': buttonOptions
449 Object.assign(children, {
450 'currentTimeDisplay': {},
452 'durationDisplay': {},
455 'flexibleWidthSpacer': {},
460 [loadProgressBar]: {},
461 'mouseTimeDisplay': {},
462 'playProgressBar': {}
477 entries: settingEntries
481 if (options.peertubeLink === true) {
482 Object.assign(children, {
483 'peerTubeLinkButton': {}
487 if (options.theaterButton === true) {
488 Object.assign(children, {
493 Object.assign(children, {
494 'fullscreenToggle': {}
500 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
501 const content = () => {
502 const isLoopEnabled = player.options_['loop']
506 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
507 listener: function () {
508 player.options_['loop'] = !isLoopEnabled
512 label: player.localize('Copy the video URL'),
513 listener: function () {
514 copyToClipboard(buildVideoLink())
518 label: player.localize('Copy the video URL at the current time'),
519 listener: function (this: videojs.Player) {
520 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
525 label: player.localize('Copy embed code'),
527 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
532 if (mode === 'webtorrent') {
534 label: player.localize('Copy magnet URI'),
535 listener: function (this: videojs.Player) {
536 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
541 return items.map(i => ({
543 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
548 player.contextmenuUI({ content })
551 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
552 const isNaked = (event: KeyboardEvent, key: string) =>
553 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
555 Object.assign(plugins, {
557 skipInitialFocus: true,
558 enableInactiveFocus: false,
559 captureDocumentHotkeys: true,
560 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
561 const tagName = e.tagName.toLowerCase()
562 return e.id === 'content' || tagName === 'body' || tagName === 'video'
565 enableVolumeScroll: false,
566 enableModifiersForNumbers: false,
568 rewindKey: function (event: KeyboardEvent) {
569 return isNaked(event, 'ArrowLeft')
572 forwardKey: function (event: KeyboardEvent) {
573 return isNaked(event, 'ArrowRight')
576 fullscreenKey: function (event: KeyboardEvent) {
577 // fullscreen with the f key or Ctrl+Enter
578 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
582 increasePlaybackRateKey: {
583 key: function (event: KeyboardEvent) {
584 return isNaked(event, '>')
586 handler: function (player: videojs.Player) {
587 const newValue = Math.min(player.playbackRate() + 0.1, 5)
588 player.playbackRate(parseFloat(newValue.toFixed(2)))
591 decreasePlaybackRateKey: {
592 key: function (event: KeyboardEvent) {
593 return isNaked(event, '<')
595 handler: function (player: videojs.Player) {
596 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
597 player.playbackRate(parseFloat(newValue.toFixed(2)))
601 key: function (event: KeyboardEvent) {
602 return isNaked(event, '.')
604 handler: function (player: videojs.Player) {
606 // Calculate movement distance (assuming 30 fps)
608 player.currentTime(player.currentTime() + dist)
616 private static getAutoPlayValue (autoplay: any) {
617 if (autoplay !== true) return autoplay
619 // On first play, disable autoplay to avoid issues
620 // But if the player already played videos, we can safely autoplay next ones
621 if (isIOS() || isSafari()) {
622 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
629 // ############################################################################