2 import '@peertube/videojs-contextmenu'
3 import './upnext/end-card'
4 import './upnext/upnext-plugin'
5 import './stats/stats-card'
6 import './stats/stats-plugin'
7 import './bezels/bezels-plugin'
8 import './peertube-plugin'
9 import './peertube-resolutions-plugin'
10 import './videojs-components/next-previous-video-button'
11 import './videojs-components/p2p-info-button'
12 import './videojs-components/peertube-link-button'
13 import './videojs-components/peertube-load-progress-bar'
14 import './videojs-components/resolution-menu-button'
15 import './videojs-components/resolution-menu-item'
16 import './videojs-components/settings-dialog'
17 import './videojs-components/settings-menu-button'
18 import './videojs-components/settings-menu-item'
19 import './videojs-components/settings-panel'
20 import './videojs-components/settings-panel-child'
21 import './videojs-components/theater-button'
22 import './playlist/playlist-plugin'
23 import './mobile/peertube-mobile-plugin'
24 import './mobile/peertube-mobile-buttons'
25 import './hotkeys/peertube-hotkeys-plugin'
26 import videojs from 'video.js'
27 import { HlsJsEngineSettings } from '@peertube/p2p-media-loader-hlsjs'
28 import { PluginsManager } from '@root-helpers/plugins-manager'
29 import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
30 import { isDefaultLocale } from '@shared/core-utils/i18n'
31 import { VideoFile } from '@shared/models'
32 import { copyToClipboard } from '../../root-helpers/utils'
33 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
34 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
35 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
36 import { getAverageBandwidthInStore, saveAverageBandwidth } from './peertube-player-local-storage'
38 NextPreviousVideoButtonOptions,
39 P2PMediaLoaderPluginOptions,
40 PeerTubeLinkButtonOptions,
42 PlaylistPluginOptions,
46 } from './peertube-videojs-typings'
47 import { TranslationsManager } from './translations-manager'
48 import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isMobile, isSafari } from './utils'
50 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
51 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
53 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
54 // Change Captions to Subtitles/CC
55 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
56 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
57 CaptionsButton.prototype.label_ = ' '
59 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
61 export type WebtorrentOptions = {
62 videoFiles: VideoFile[]
65 export type P2PMediaLoaderOptions = {
67 segmentsSha256Url: string
68 trackerAnnounce: string[]
69 redundancyBaseUrls: string[]
70 videoFiles: VideoFile[]
73 export interface CustomizationOptions {
74 startTime: number | string
75 stopTime: number | string
86 export interface CommonOptions extends CustomizationOptions {
87 playerElement: HTMLVideoElement
88 onPlayerElementChange: (element: HTMLVideoElement) => void
93 nextVideo?: () => void
94 hasNextVideo?: () => boolean
96 previousVideo?: () => void
97 hasPreviousVideo?: () => boolean
99 playlist?: PlaylistPluginOptions
101 videoDuration: number
102 enableHotkeys: boolean
103 inactivityTimeout: number
106 theaterButton: boolean
117 videoCaptions: VideoJSCaption[]
120 videoShortUUID: string
122 userWatching?: UserWatching
127 export type PeertubePlayerManagerOptions = {
128 common: CommonOptions
129 webtorrent: WebtorrentOptions
130 p2pMediaLoader?: P2PMediaLoaderOptions
132 pluginsManager: PluginsManager
135 export class PeertubePlayerManager {
136 private static playerElementClassName: string
137 private static onPlayerChange: (player: videojs.Player) => void
138 private static alreadyPlayed = false
139 private static pluginsManager: PluginsManager
141 static initState () {
142 PeertubePlayerManager.alreadyPlayed = false
145 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
146 this.pluginsManager = options.pluginsManager
148 let p2pMediaLoader: any
150 this.onPlayerChange = onPlayerChange
151 this.playerElementClassName = options.common.playerElement.className
153 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
154 if (mode === 'p2p-media-loader') {
155 [ p2pMediaLoader ] = await Promise.all([
156 import('@peertube/p2p-media-loader-hlsjs'),
157 import('./p2p-media-loader/p2p-media-loader-plugin')
161 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
163 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
166 return new Promise(res => {
167 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
170 let alreadyFallback = false
172 player.tech(true).one('error', () => {
173 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
174 alreadyFallback = true
177 player.one('error', () => {
178 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
179 alreadyFallback = true
182 player.one('play', () => {
183 PeertubePlayerManager.alreadyPlayed = true
186 self.addContextMenu({
189 videoShortUUID: options.common.videoShortUUID,
190 videoEmbedUrl: options.common.embedUrl,
191 videoEmbedTitle: options.common.embedTitle
194 if (isMobile()) player.peertubeMobile()
195 if (options.common.enableHotkeys === true) player.peerTubeHotkeysPlugin()
200 videoUUID: options.common.videoUUID,
201 videoIsLive: options.common.isLive,
203 p2pEnabled: options.common.p2pEnabled
206 player.on('p2pInfo', (_, data: PlayerNetworkInfo) => {
207 if (data.source !== 'p2p-media-loader' || isNaN(data.bandwidthEstimate)) return
209 saveAverageBandwidth(data.bandwidthEstimate)
217 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
218 if (currentMode === 'webtorrent') return
220 console.log('Fallback to webtorrent.')
222 const newVideoElement = document.createElement('video')
223 newVideoElement.className = this.playerElementClassName
225 // VideoJS wraps our video element inside a div
226 let currentParentPlayerElement = options.common.playerElement.parentNode
227 // Fix on IOS, don't ask me why
228 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
230 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
232 options.common.playerElement = newVideoElement
233 options.common.onPlayerElementChange(newVideoElement)
237 await import('./webtorrent/webtorrent-plugin')
239 const mode = 'webtorrent'
240 const videojsOptions = await this.getVideojsOptions(mode, options)
243 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
246 self.addContextMenu({
249 videoShortUUID: options.common.videoShortUUID,
250 videoEmbedUrl: options.common.embedUrl,
251 videoEmbedTitle: options.common.embedTitle
254 PeertubePlayerManager.onPlayerChange(player)
258 private static async getVideojsOptions (
260 options: PeertubePlayerManagerOptions,
261 p2pMediaLoaderModule?: any
262 ): Promise<videojs.PlayerOptions> {
263 const commonOptions = options.common
264 const isHLS = mode === 'p2p-media-loader'
266 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
268 preloadTextTracks: false
271 const plugins: VideoJSPluginOptions = {
274 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
275 videoViewUrl: commonOptions.videoViewUrl,
276 videoDuration: commonOptions.videoDuration,
277 userWatching: commonOptions.userWatching,
278 subtitle: commonOptions.subtitle,
279 videoCaptions: commonOptions.videoCaptions,
280 stopTime: commonOptions.stopTime,
281 isLive: commonOptions.isLive,
282 videoUUID: commonOptions.videoUUID
286 if (commonOptions.playlist) {
287 plugins.playlist = commonOptions.playlist
291 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
293 Object.assign(html5, hlsjs.html5)
296 if (mode === 'webtorrent') {
297 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
299 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
303 const videojsOptions = {
306 // We don't use text track settings for now
307 textTrackSettings: false as any, // FIXME: typings
308 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
309 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
311 muted: commonOptions.muted !== undefined
312 ? commonOptions.muted
313 : undefined, // Undefined so the player knows it has to check the local storage
315 autoplay: this.getAutoPlayValue(autoplay),
317 poster: commonOptions.poster,
318 inactivityTimeout: commonOptions.inactivityTimeout,
319 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
324 children: this.getControlBarChildren(mode, {
325 videoShortUUID: commonOptions.videoShortUUID,
326 p2pEnabled: commonOptions.p2pEnabled,
328 captions: commonOptions.captions,
329 peertubeLink: commonOptions.peertubeLink,
330 theaterButton: commonOptions.theaterButton,
332 nextVideo: commonOptions.nextVideo,
333 hasNextVideo: commonOptions.hasNextVideo,
335 previousVideo: commonOptions.previousVideo,
336 hasPreviousVideo: commonOptions.hasPreviousVideo
337 }) as any // FIXME: typings
341 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
342 Object.assign(videojsOptions, { language: commonOptions.language })
345 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
348 private static addP2PMediaLoaderOptions (
349 plugins: VideoJSPluginOptions,
350 options: PeertubePlayerManagerOptions,
351 p2pMediaLoaderModule: any
353 const p2pMediaLoaderOptions = options.p2pMediaLoader
354 const commonOptions = options.common
356 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
357 .filter(t => t.startsWith('ws'))
359 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
361 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
362 redundancyUrlManager,
363 type: 'application/x-mpegURL',
364 startTime: commonOptions.startTime,
365 src: p2pMediaLoaderOptions.playlistUrl
368 let consumeOnly = false
369 if ((navigator as any)?.connection?.type === 'cellular') {
370 console.log('We are on a cellular connection: disabling seeding.')
374 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
377 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
378 rtcConfig: getRtcConfig(),
379 requiredSegmentsPriority: 1,
380 simultaneousHttpDownloads: 1,
381 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager, 1),
382 useP2P: commonOptions.p2pEnabled,
386 swarmId: p2pMediaLoaderOptions.playlistUrl
391 levelLabelHandler: (level: { height: number, width: number }) => {
392 const resolution = Math.min(level.height || 0, level.width || 0)
394 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
395 // We don't have files for live videos
396 if (!file) return level.height
398 let label = file.resolution.label
399 if (file.fps >= 50) label += file.fps
404 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderModule, p2pMediaLoaderConfig)
408 const toAssign = { p2pMediaLoader, hlsjs }
409 Object.assign(plugins, toAssign)
414 private static getHLSOptions (p2pMediaLoaderModule: any, p2pMediaLoaderConfig: HlsJsEngineSettings) {
416 capLevelToPlayerSize: true,
417 autoStartLoad: false,
418 liveSyncDurationCount: 5,
420 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
423 const averageBandwidth = getAverageBandwidthInStore()
424 if (!averageBandwidth) return base
429 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
431 testBandwidth: false,
436 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
437 const commonOptions = options.common
438 const webtorrentOptions = options.webtorrent
439 const p2pMediaLoaderOptions = options.p2pMediaLoader
441 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
445 playerRefusedP2P: commonOptions.p2pEnabled === false,
446 videoDuration: commonOptions.videoDuration,
447 playerElement: commonOptions.playerElement,
448 videoFiles: webtorrentOptions.videoFiles.length !== 0
449 ? webtorrentOptions.videoFiles
450 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
451 : p2pMediaLoaderOptions?.videoFiles || [],
452 startTime: commonOptions.startTime
455 Object.assign(plugins, { webtorrent })
458 private static getControlBarChildren (mode: PlayerMode, options: {
460 videoShortUUID: string
462 peertubeLink: boolean
463 theaterButton: boolean
466 nextVideo?: () => void
467 hasNextVideo?: () => boolean
469 previousVideo?: () => void
470 hasPreviousVideo?: () => boolean
472 const settingEntries = []
473 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
476 settingEntries.push('playbackRateMenuButton')
477 if (options.captions === true) settingEntries.push('captionsButton')
478 settingEntries.push('resolutionMenuButton')
482 if (options.previousVideo) {
483 const buttonOptions: NextPreviousVideoButtonOptions = {
485 handler: options.previousVideo,
487 if (!options.hasPreviousVideo) return false
489 return !options.hasPreviousVideo()
493 Object.assign(children, {
494 previousVideoButton: buttonOptions
498 Object.assign(children, { playToggle: {} })
500 if (options.nextVideo) {
501 const buttonOptions: NextPreviousVideoButtonOptions = {
503 handler: options.nextVideo,
505 if (!options.hasNextVideo) return false
507 return !options.hasNextVideo()
511 Object.assign(children, {
512 nextVideoButton: buttonOptions
516 Object.assign(children, {
517 currentTimeDisplay: {},
522 flexibleWidthSpacer: {},
527 [loadProgressBar]: {},
528 mouseTimeDisplay: {},
536 p2pEnabled: options.p2pEnabled
546 entries: settingEntries
550 if (options.peertubeLink === true) {
551 Object.assign(children, {
552 peerTubeLinkButton: { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
556 if (options.theaterButton === true) {
557 Object.assign(children, {
562 Object.assign(children, {
569 private static addContextMenu (options: {
571 player: videojs.Player
572 videoShortUUID: string
573 videoEmbedUrl: string
574 videoEmbedTitle: string
576 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
578 const content = () => {
579 const isLoopEnabled = player.options_['loop']
583 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
584 listener: function () {
585 player.options_['loop'] = !isLoopEnabled
589 label: player.localize('Copy the video URL'),
590 listener: function () {
591 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
595 label: player.localize('Copy the video URL at the current time'),
596 listener: function (this: videojs.Player) {
597 const url = buildVideoLink({ shortUUID: videoShortUUID })
599 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
604 label: player.localize('Copy embed code'),
606 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
611 if (mode === 'webtorrent') {
613 label: player.localize('Copy magnet URI'),
614 listener: function (this: videojs.Player) {
615 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
622 label: player.localize('Stats for nerds'),
624 player.stats().show()
628 return items.map(i => ({
630 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
635 player.contextmenuUI({ content })
638 private static getAutoPlayValue (autoplay: any) {
639 if (autoplay !== true) return autoplay
641 // On first play, disable autoplay to avoid issues
642 // But if the player already played videos, we can safely autoplay next ones
643 if (isIOS() || isSafari()) {
644 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
651 // ############################################################################