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)
225 const plugins: VideoJSPluginOptions = {
228 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
229 videoViewUrl: commonOptions.videoViewUrl,
230 videoDuration: commonOptions.videoDuration,
231 userWatching: commonOptions.userWatching,
232 subtitle: commonOptions.subtitle,
233 videoCaptions: commonOptions.videoCaptions,
234 stopTime: commonOptions.stopTime,
235 isLive: commonOptions.isLive,
236 videoUUID: commonOptions.videoUUID
240 if (commonOptions.playlist) {
241 plugins.playlist = commonOptions.playlist
244 if (commonOptions.enableHotkeys === true) {
245 PeertubePlayerManager.addHotkeysOptions(plugins)
249 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
254 if (mode === 'webtorrent') {
255 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
257 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
261 const videojsOptions = {
264 // We don't use text track settings for now
265 textTrackSettings: false as any, // FIXME: typings
266 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
267 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
269 muted: commonOptions.muted !== undefined
270 ? commonOptions.muted
271 : undefined, // Undefined so the player knows it has to check the local storage
273 autoplay: this.getAutoPlayValue(autoplay),
275 poster: commonOptions.poster,
276 inactivityTimeout: commonOptions.inactivityTimeout,
277 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
282 children: this.getControlBarChildren(mode, {
283 captions: commonOptions.captions,
284 peertubeLink: commonOptions.peertubeLink,
285 theaterButton: commonOptions.theaterButton,
287 nextVideo: commonOptions.nextVideo,
288 hasNextVideo: commonOptions.hasNextVideo,
290 previousVideo: commonOptions.previousVideo,
291 hasPreviousVideo: commonOptions.hasPreviousVideo
292 }) as any // FIXME: typings
296 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
297 Object.assign(videojsOptions, { language: commonOptions.language })
300 return videojsOptions
303 private static addP2PMediaLoaderOptions (
304 plugins: VideoJSPluginOptions,
305 options: PeertubePlayerManagerOptions,
306 p2pMediaLoaderModule: any
308 const p2pMediaLoaderOptions = options.p2pMediaLoader
309 const commonOptions = options.common
311 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
312 .filter(t => t.startsWith('ws'))
314 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
316 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
317 redundancyUrlManager,
318 type: 'application/x-mpegURL',
319 startTime: commonOptions.startTime,
320 src: p2pMediaLoaderOptions.playlistUrl
323 let consumeOnly = false
325 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
326 console.log('We are on a cellular connection: disabling seeding.')
330 const p2pMediaLoaderConfig = {
333 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
334 rtcConfig: getRtcConfig(),
335 requiredSegmentsPriority: 1,
336 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
337 useP2P: getStoredP2PEnabled(),
341 swarmId: p2pMediaLoaderOptions.playlistUrl
345 levelLabelHandler: (level: { height: number, width: number }) => {
346 const resolution = Math.min(level.height || 0, level.width || 0)
348 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
349 // We don't have files for live videos
350 if (!file) return level.height
352 let label = file.resolution.label
353 if (file.fps >= 50) label += file.fps
359 capLevelToPlayerSize: true,
360 autoStartLoad: false,
361 liveSyncDurationCount: 5,
362 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
367 const toAssign = { p2pMediaLoader, hlsjs }
368 Object.assign(plugins, toAssign)
373 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
374 const commonOptions = options.common
375 const webtorrentOptions = options.webtorrent
377 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
383 videoDuration: commonOptions.videoDuration,
384 playerElement: commonOptions.playerElement,
385 videoFiles: webtorrentOptions.videoFiles,
386 startTime: commonOptions.startTime
389 Object.assign(plugins, { webtorrent })
392 private static getControlBarChildren (mode: PlayerMode, options: {
393 peertubeLink: boolean
394 theaterButton: boolean
398 hasNextVideo?: () => boolean
400 previousVideo?: Function
401 hasPreviousVideo?: () => boolean
403 const settingEntries = []
404 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
407 settingEntries.push('playbackRateMenuButton')
408 if (options.captions === true) settingEntries.push('captionsButton')
409 settingEntries.push('resolutionMenuButton')
413 if (options.previousVideo) {
414 const buttonOptions: NextPreviousVideoButtonOptions = {
416 handler: options.previousVideo,
418 if (!options.hasPreviousVideo) return false
420 return !options.hasPreviousVideo()
424 Object.assign(children, {
425 'previousVideoButton': buttonOptions
429 Object.assign(children, { playToggle: {} })
431 if (options.nextVideo) {
432 const buttonOptions: NextPreviousVideoButtonOptions = {
434 handler: options.nextVideo,
436 if (!options.hasNextVideo) return false
438 return !options.hasNextVideo()
442 Object.assign(children, {
443 'nextVideoButton': buttonOptions
447 Object.assign(children, {
448 'currentTimeDisplay': {},
450 'durationDisplay': {},
453 'flexibleWidthSpacer': {},
458 [loadProgressBar]: {},
459 'mouseTimeDisplay': {},
460 'playProgressBar': {}
475 entries: settingEntries
479 if (options.peertubeLink === true) {
480 Object.assign(children, {
481 'peerTubeLinkButton': {}
485 if (options.theaterButton === true) {
486 Object.assign(children, {
491 Object.assign(children, {
492 'fullscreenToggle': {}
498 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
499 const content = () => {
500 const isLoopEnabled = player.options_['loop']
504 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
505 listener: function () {
506 player.options_['loop'] = !isLoopEnabled
510 label: player.localize('Copy the video URL'),
511 listener: function () {
512 copyToClipboard(buildVideoLink())
516 label: player.localize('Copy the video URL at the current time'),
517 listener: function (this: videojs.Player) {
518 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
523 label: player.localize('Copy embed code'),
525 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
530 if (mode === 'webtorrent') {
532 label: player.localize('Copy magnet URI'),
533 listener: function (this: videojs.Player) {
534 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
539 return items.map(i => ({
541 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
546 player.contextmenuUI({ content })
549 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
550 const isNaked = (event: KeyboardEvent, key: string) =>
551 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
553 Object.assign(plugins, {
555 skipInitialFocus: true,
556 enableInactiveFocus: false,
557 captureDocumentHotkeys: true,
558 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
559 const tagName = e.tagName.toLowerCase()
560 return e.id === 'content' || tagName === 'body' || tagName === 'video'
563 enableVolumeScroll: false,
564 enableModifiersForNumbers: false,
566 rewindKey: function (event: KeyboardEvent) {
567 return isNaked(event, 'ArrowLeft')
570 forwardKey: function (event: KeyboardEvent) {
571 return isNaked(event, 'ArrowRight')
574 fullscreenKey: function (event: KeyboardEvent) {
575 // fullscreen with the f key or Ctrl+Enter
576 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
580 increasePlaybackRateKey: {
581 key: function (event: KeyboardEvent) {
582 return isNaked(event, '>')
584 handler: function (player: videojs.Player) {
585 const newValue = Math.min(player.playbackRate() + 0.1, 5)
586 player.playbackRate(parseFloat(newValue.toFixed(2)))
589 decreasePlaybackRateKey: {
590 key: function (event: KeyboardEvent) {
591 return isNaked(event, '<')
593 handler: function (player: videojs.Player) {
594 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
595 player.playbackRate(parseFloat(newValue.toFixed(2)))
599 key: function (event: KeyboardEvent) {
600 return isNaked(event, '.')
602 handler: function (player: videojs.Player) {
604 // Calculate movement distance (assuming 30 fps)
606 player.currentTime(player.currentTime() + dist)
614 private static getAutoPlayValue (autoplay: any) {
615 if (autoplay !== true) return autoplay
617 // On first play, disable autoplay to avoid issues
618 // But if the player already played videos, we can safely autoplay next ones
619 if (isIOS() || isSafari()) {
620 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
627 // ############################################################################