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'
23 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
24 import { VideoFile } from '../../../../shared/models/videos'
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'
29 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings'
30 import { TranslationsManager } from './translations-manager'
31 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig, isIOS, isSafari } from './utils'
33 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
34 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
36 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
37 // Change Captions to Subtitles/CC
38 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
39 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
40 CaptionsButton.prototype.label_ = ' '
42 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
44 export type WebtorrentOptions = {
45 videoFiles: VideoFile[]
48 export type P2PMediaLoaderOptions = {
50 segmentsSha256Url: string
51 trackerAnnounce: string[]
52 redundancyBaseUrls: string[]
53 videoFiles: VideoFile[]
56 export interface CustomizationOptions {
57 startTime: number | string
58 stopTime: number | string
69 export interface CommonOptions extends CustomizationOptions {
70 playerElement: HTMLVideoElement
71 onPlayerElementChange: (element: HTMLVideoElement) => void
76 enableHotkeys: boolean
77 inactivityTimeout: number
80 theaterButton: boolean
88 videoCaptions: VideoJSCaption[]
90 userWatching?: UserWatching
95 export type PeertubePlayerManagerOptions = {
96 common: CommonOptions,
97 webtorrent: WebtorrentOptions,
98 p2pMediaLoader?: P2PMediaLoaderOptions
101 export class PeertubePlayerManager {
102 private static playerElementClassName: string
103 private static onPlayerChange: (player: videojs.Player) => void
105 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
106 let p2pMediaLoader: any
108 this.onPlayerChange = onPlayerChange
109 this.playerElementClassName = options.common.playerElement.className
111 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
112 if (mode === 'p2p-media-loader') {
113 [ p2pMediaLoader ] = await Promise.all([
114 import('p2p-media-loader-hlsjs'),
115 import('./p2p-media-loader/p2p-media-loader-plugin')
119 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
121 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
124 return new Promise(res => {
125 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
128 let alreadyFallback = false
130 player.tech(true).one('error', () => {
131 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
132 alreadyFallback = true
135 player.one('error', () => {
136 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
137 alreadyFallback = true
140 self.addContextMenu(mode, player, options.common.embedUrl)
149 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
150 if (currentMode === 'webtorrent') return
152 console.log('Fallback to webtorrent.')
154 const newVideoElement = document.createElement('video')
155 newVideoElement.className = this.playerElementClassName
157 // VideoJS wraps our video element inside a div
158 let currentParentPlayerElement = options.common.playerElement.parentNode
159 // Fix on IOS, don't ask me why
160 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
162 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
164 options.common.playerElement = newVideoElement
165 options.common.onPlayerElementChange(newVideoElement)
169 await import('./webtorrent/webtorrent-plugin')
171 const mode = 'webtorrent'
172 const videojsOptions = this.getVideojsOptions(mode, options)
175 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
178 self.addContextMenu(mode, player, options.common.embedUrl)
180 PeertubePlayerManager.onPlayerChange(player)
184 private static getVideojsOptions (
186 options: PeertubePlayerManagerOptions,
187 p2pMediaLoaderModule?: any
188 ): videojs.PlayerOptions {
189 const commonOptions = options.common
191 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
194 const plugins: VideoJSPluginOptions = {
197 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
198 videoViewUrl: commonOptions.videoViewUrl,
199 videoDuration: commonOptions.videoDuration,
200 userWatching: commonOptions.userWatching,
201 subtitle: commonOptions.subtitle,
202 videoCaptions: commonOptions.videoCaptions,
203 stopTime: commonOptions.stopTime
207 if (commonOptions.enableHotkeys === true) {
208 PeertubePlayerManager.addHotkeysOptions(plugins)
211 if (mode === 'p2p-media-loader') {
212 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
217 if (mode === 'webtorrent') {
218 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
220 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
224 const videojsOptions = {
227 // We don't use text track settings for now
228 textTrackSettings: false as any, // FIXME: typings
229 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
230 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
232 muted: commonOptions.muted !== undefined
233 ? commonOptions.muted
234 : undefined, // Undefined so the player knows it has to check the local storage
236 autoplay: this.getAutoPlayValue(autoplay),
238 poster: commonOptions.poster,
239 inactivityTimeout: commonOptions.inactivityTimeout,
240 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
245 children: this.getControlBarChildren(mode, {
246 captions: commonOptions.captions,
247 peertubeLink: commonOptions.peertubeLink,
248 theaterButton: commonOptions.theaterButton,
249 nextVideo: commonOptions.nextVideo
250 }) as any // FIXME: typings
254 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
255 Object.assign(videojsOptions, { language: commonOptions.language })
258 return videojsOptions
261 private static addP2PMediaLoaderOptions (
262 plugins: VideoJSPluginOptions,
263 options: PeertubePlayerManagerOptions,
264 p2pMediaLoaderModule: any
266 const p2pMediaLoaderOptions = options.p2pMediaLoader
267 const commonOptions = options.common
269 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
270 .filter(t => t.startsWith('ws'))
272 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
274 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
275 redundancyUrlManager,
276 type: 'application/x-mpegURL',
277 startTime: commonOptions.startTime,
278 src: p2pMediaLoaderOptions.playlistUrl
281 let consumeOnly = false
283 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
284 console.log('We are on a cellular connection: disabling seeding.')
288 const p2pMediaLoaderConfig = {
291 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
292 rtcConfig: getRtcConfig(),
293 requiredSegmentsPriority: 5,
294 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
295 useP2P: getStoredP2PEnabled(),
299 swarmId: p2pMediaLoaderOptions.playlistUrl
303 levelLabelHandler: (level: { height: number, width: number }) => {
304 const resolution = Math.min(level.height || 0, level.width || 0)
306 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
308 console.error('Cannot find video file for level %d.', level.height)
312 let label = file.resolution.label
313 if (file.fps >= 50) label += file.fps
319 capLevelToPlayerSize: true,
320 autoStartLoad: false,
321 liveSyncDurationCount: 7,
322 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
327 const toAssign = { p2pMediaLoader, hlsjs }
328 Object.assign(plugins, toAssign)
333 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
334 const commonOptions = options.common
335 const webtorrentOptions = options.webtorrent
338 autoplay: commonOptions.autoplay,
339 videoDuration: commonOptions.videoDuration,
340 playerElement: commonOptions.playerElement,
341 videoFiles: webtorrentOptions.videoFiles,
342 startTime: commonOptions.startTime
345 Object.assign(plugins, { webtorrent })
348 private static getControlBarChildren (mode: PlayerMode, options: {
349 peertubeLink: boolean
350 theaterButton: boolean,
354 const settingEntries = []
355 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
358 settingEntries.push('playbackRateMenuButton')
359 if (options.captions === true) settingEntries.push('captionsButton')
360 settingEntries.push('resolutionMenuButton')
366 if (options.nextVideo) {
367 Object.assign(children, {
369 handler: options.nextVideo
374 Object.assign(children, {
375 'currentTimeDisplay': {},
377 'durationDisplay': {},
380 'flexibleWidthSpacer': {},
385 [loadProgressBar]: {},
386 'mouseTimeDisplay': {},
387 'playProgressBar': {}
402 entries: settingEntries
406 if (options.peertubeLink === true) {
407 Object.assign(children, {
408 'peerTubeLinkButton': {}
412 if (options.theaterButton === true) {
413 Object.assign(children, {
418 Object.assign(children, {
419 'fullscreenToggle': {}
425 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
428 label: player.localize('Copy the video URL'),
429 listener: function () {
430 copyToClipboard(buildVideoLink())
434 label: player.localize('Copy the video URL at the current time'),
435 listener: function (this: videojs.Player) {
436 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
440 label: player.localize('Copy embed code'),
442 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
447 if (mode === 'webtorrent') {
449 label: player.localize('Copy magnet URI'),
450 listener: function (this: videojs.Player) {
451 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
456 player.contextmenuUI({ content })
459 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
460 Object.assign(plugins, {
462 skipInitialFocus: true,
463 enableInactiveFocus: false,
464 captureDocumentHotkeys: true,
465 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
466 const tagName = e.tagName.toLowerCase()
467 return e.id === 'content' || tagName === 'body' || tagName === 'video'
470 enableVolumeScroll: false,
471 enableModifiersForNumbers: false,
473 fullscreenKey: function (event: KeyboardEvent) {
474 // fullscreen with the f key or Ctrl+Enter
475 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
478 seekStep: function (event: KeyboardEvent) {
479 // mimic VLC seek behavior, and default to 5 (original value is 5).
480 if (event.ctrlKey && event.altKey) {
482 } else if (event.ctrlKey) {
484 } else if (event.altKey) {
492 increasePlaybackRateKey: {
493 key: function (event: KeyboardEvent) {
494 return event.key === '>'
496 handler: function (player: videojs.Player) {
497 const newValue = Math.min(player.playbackRate() + 0.1, 5)
498 player.playbackRate(parseFloat(newValue.toFixed(2)))
501 decreasePlaybackRateKey: {
502 key: function (event: KeyboardEvent) {
503 return event.key === '<'
505 handler: function (player: videojs.Player) {
506 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
507 player.playbackRate(parseFloat(newValue.toFixed(2)))
511 key: function (event: KeyboardEvent) {
512 return event.key === '.'
514 handler: function (player: videojs.Player) {
516 // Calculate movement distance (assuming 30 fps)
518 player.currentTime(player.currentTime() + dist)
526 private static getAutoPlayValue (autoplay: any) {
527 if (autoplay !== true) return autoplay
529 // Giving up with iOS
530 if (isIOS()) return false
532 // We have issues with autoplay and Safari.
533 // any that tries to play using auto mute seems to work
534 if (isSafari()) return 'any'
540 // ############################################################################