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-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 videojs from 'video.js'
22 import { isDefaultLocale, VideoFile } from '@shared/models'
23 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
24 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
25 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
26 import { getStoredP2PEnabled } from './peertube-player-local-storage'
27 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings'
28 import { TranslationsManager } from './translations-manager'
29 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig, isIOS, isSafari } from './utils'
31 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
32 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
34 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
35 // Change Captions to Subtitles/CC
36 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
37 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
38 CaptionsButton.prototype.label_ = ' '
40 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
42 export type WebtorrentOptions = {
43 videoFiles: VideoFile[]
46 export type P2PMediaLoaderOptions = {
48 segmentsSha256Url: string
49 trackerAnnounce: string[]
50 redundancyBaseUrls: string[]
51 videoFiles: VideoFile[]
54 export interface CustomizationOptions {
55 startTime: number | string
56 stopTime: number | string
67 export interface CommonOptions extends CustomizationOptions {
68 playerElement: HTMLVideoElement
69 onPlayerElementChange: (element: HTMLVideoElement) => void
74 enableHotkeys: boolean
75 inactivityTimeout: number
78 theaterButton: boolean
86 videoCaptions: VideoJSCaption[]
88 userWatching?: UserWatching
93 export type PeertubePlayerManagerOptions = {
94 common: CommonOptions,
95 webtorrent: WebtorrentOptions,
96 p2pMediaLoader?: P2PMediaLoaderOptions
99 export class PeertubePlayerManager {
100 private static playerElementClassName: string
101 private static onPlayerChange: (player: videojs.Player) => void
103 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
104 let p2pMediaLoader: any
106 this.onPlayerChange = onPlayerChange
107 this.playerElementClassName = options.common.playerElement.className
109 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
110 if (mode === 'p2p-media-loader') {
111 [ p2pMediaLoader ] = await Promise.all([
112 import('p2p-media-loader-hlsjs'),
113 import('./p2p-media-loader/p2p-media-loader-plugin')
117 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
119 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
122 return new Promise(res => {
123 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
126 let alreadyFallback = false
128 player.tech(true).one('error', () => {
129 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
130 alreadyFallback = true
133 player.one('error', () => {
134 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
135 alreadyFallback = true
138 self.addContextMenu(mode, player, options.common.embedUrl)
147 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
148 if (currentMode === 'webtorrent') return
150 console.log('Fallback to webtorrent.')
152 const newVideoElement = document.createElement('video')
153 newVideoElement.className = this.playerElementClassName
155 // VideoJS wraps our video element inside a div
156 let currentParentPlayerElement = options.common.playerElement.parentNode
157 // Fix on IOS, don't ask me why
158 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
160 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
162 options.common.playerElement = newVideoElement
163 options.common.onPlayerElementChange(newVideoElement)
167 await import('./webtorrent/webtorrent-plugin')
169 const mode = 'webtorrent'
170 const videojsOptions = this.getVideojsOptions(mode, options)
173 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
176 self.addContextMenu(mode, player, options.common.embedUrl)
178 PeertubePlayerManager.onPlayerChange(player)
182 private static getVideojsOptions (
184 options: PeertubePlayerManagerOptions,
185 p2pMediaLoaderModule?: any
186 ): videojs.PlayerOptions {
187 const commonOptions = options.common
189 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
192 const plugins: VideoJSPluginOptions = {
195 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
196 videoViewUrl: commonOptions.videoViewUrl,
197 videoDuration: commonOptions.videoDuration,
198 userWatching: commonOptions.userWatching,
199 subtitle: commonOptions.subtitle,
200 videoCaptions: commonOptions.videoCaptions,
201 stopTime: commonOptions.stopTime
205 if (commonOptions.enableHotkeys === true) {
206 PeertubePlayerManager.addHotkeysOptions(plugins)
209 if (mode === 'p2p-media-loader') {
210 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
215 if (mode === 'webtorrent') {
216 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
218 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
222 const videojsOptions = {
225 // We don't use text track settings for now
226 textTrackSettings: false as any, // FIXME: typings
227 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
228 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
230 muted: commonOptions.muted !== undefined
231 ? commonOptions.muted
232 : undefined, // Undefined so the player knows it has to check the local storage
234 autoplay: this.getAutoPlayValue(autoplay),
236 poster: commonOptions.poster,
237 inactivityTimeout: commonOptions.inactivityTimeout,
238 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
243 children: this.getControlBarChildren(mode, {
244 captions: commonOptions.captions,
245 peertubeLink: commonOptions.peertubeLink,
246 theaterButton: commonOptions.theaterButton,
247 nextVideo: commonOptions.nextVideo
248 }) as any // FIXME: typings
252 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
253 Object.assign(videojsOptions, { language: commonOptions.language })
256 return videojsOptions
259 private static addP2PMediaLoaderOptions (
260 plugins: VideoJSPluginOptions,
261 options: PeertubePlayerManagerOptions,
262 p2pMediaLoaderModule: any
264 const p2pMediaLoaderOptions = options.p2pMediaLoader
265 const commonOptions = options.common
267 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
268 .filter(t => t.startsWith('ws'))
270 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
272 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
273 redundancyUrlManager,
274 type: 'application/x-mpegURL',
275 startTime: commonOptions.startTime,
276 src: p2pMediaLoaderOptions.playlistUrl
279 let consumeOnly = false
281 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
282 console.log('We are on a cellular connection: disabling seeding.')
286 const p2pMediaLoaderConfig = {
289 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
290 rtcConfig: getRtcConfig(),
291 requiredSegmentsPriority: 5,
292 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
293 useP2P: getStoredP2PEnabled(),
297 swarmId: p2pMediaLoaderOptions.playlistUrl
301 levelLabelHandler: (level: { height: number, width: number }) => {
302 const resolution = Math.min(level.height || 0, level.width || 0)
304 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
306 console.error('Cannot find video file for level %d.', level.height)
310 let label = file.resolution.label
311 if (file.fps >= 50) label += file.fps
317 capLevelToPlayerSize: true,
318 autoStartLoad: false,
319 liveSyncDurationCount: 7,
320 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
325 const toAssign = { p2pMediaLoader, hlsjs }
326 Object.assign(plugins, toAssign)
331 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
332 const commonOptions = options.common
333 const webtorrentOptions = options.webtorrent
336 autoplay: commonOptions.autoplay,
337 videoDuration: commonOptions.videoDuration,
338 playerElement: commonOptions.playerElement,
339 videoFiles: webtorrentOptions.videoFiles,
340 startTime: commonOptions.startTime
343 Object.assign(plugins, { webtorrent })
346 private static getControlBarChildren (mode: PlayerMode, options: {
347 peertubeLink: boolean
348 theaterButton: boolean,
352 const settingEntries = []
353 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
356 settingEntries.push('playbackRateMenuButton')
357 if (options.captions === true) settingEntries.push('captionsButton')
358 settingEntries.push('resolutionMenuButton')
364 if (options.nextVideo) {
365 Object.assign(children, {
367 handler: options.nextVideo
372 Object.assign(children, {
373 'currentTimeDisplay': {},
375 'durationDisplay': {},
378 'flexibleWidthSpacer': {},
383 [loadProgressBar]: {},
384 'mouseTimeDisplay': {},
385 'playProgressBar': {}
400 entries: settingEntries
404 if (options.peertubeLink === true) {
405 Object.assign(children, {
406 'peerTubeLinkButton': {}
410 if (options.theaterButton === true) {
411 Object.assign(children, {
416 Object.assign(children, {
417 'fullscreenToggle': {}
423 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
426 label: player.localize('Copy the video URL'),
427 listener: function () {
428 copyToClipboard(buildVideoLink())
432 label: player.localize('Copy the video URL at the current time'),
433 listener: function (this: videojs.Player) {
434 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
438 label: player.localize('Copy embed code'),
440 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
445 if (mode === 'webtorrent') {
447 label: player.localize('Copy magnet URI'),
448 listener: function (this: videojs.Player) {
449 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
454 player.contextmenuUI({ content })
457 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
458 Object.assign(plugins, {
460 skipInitialFocus: true,
461 enableInactiveFocus: false,
462 captureDocumentHotkeys: true,
463 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
464 const tagName = e.tagName.toLowerCase()
465 return e.id === 'content' || tagName === 'body' || tagName === 'video'
468 enableVolumeScroll: false,
469 enableModifiersForNumbers: false,
471 fullscreenKey: function (event: KeyboardEvent) {
472 // fullscreen with the f key or Ctrl+Enter
473 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
476 seekStep: function (event: KeyboardEvent) {
477 // mimic VLC seek behavior, and default to 5 (original value is 5).
478 if (event.ctrlKey && event.altKey) {
480 } else if (event.ctrlKey) {
482 } else if (event.altKey) {
490 increasePlaybackRateKey: {
491 key: function (event: KeyboardEvent) {
492 return event.key === '>'
494 handler: function (player: videojs.Player) {
495 const newValue = Math.min(player.playbackRate() + 0.1, 5)
496 player.playbackRate(parseFloat(newValue.toFixed(2)))
499 decreasePlaybackRateKey: {
500 key: function (event: KeyboardEvent) {
501 return event.key === '<'
503 handler: function (player: videojs.Player) {
504 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
505 player.playbackRate(parseFloat(newValue.toFixed(2)))
509 key: function (event: KeyboardEvent) {
510 return event.key === '.'
512 handler: function (player: videojs.Player) {
514 // Calculate movement distance (assuming 30 fps)
516 player.currentTime(player.currentTime() + dist)
524 private static getAutoPlayValue (autoplay: any) {
525 if (autoplay !== true) return autoplay
527 // Giving up with iOS
528 if (isIOS()) return false
530 // We have issues with autoplay and Safari.
531 // any that tries to play using auto mute seems to work
532 if (isSafari()) return 'any'
538 // ############################################################################