1 import { VideoFile } from '../../../../shared/models/videos'
2 import videojs, { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js'
3 import 'videojs-hotkeys'
5 import 'videojs-contextmenu-ui'
6 import 'videojs-contrib-quality-levels'
7 import './upnext/end-card'
8 import './upnext/upnext-plugin'
9 import './bezels/bezels-plugin'
10 import './peertube-plugin'
11 import './videojs-components/next-video-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-link-button'
14 import './videojs-components/peertube-load-progress-bar'
15 import './videojs-components/resolution-menu-button'
16 import './videojs-components/resolution-menu-item'
17 import './videojs-components/settings-dialog'
18 import './videojs-components/settings-menu-button'
19 import './videojs-components/settings-menu-item'
20 import './videojs-components/settings-panel'
21 import './videojs-components/settings-panel-child'
22 import './videojs-components/theater-button'
23 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings'
24 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils'
25 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
26 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
27 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
28 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
29 import { getStoredP2PEnabled } from './peertube-player-local-storage'
30 import { TranslationsManager } from './translations-manager'
33 (window as any).WebVTT = require('vtt.js/lib/vtt.js').WebVTT;
35 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
36 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
38 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
39 // Change Captions to Subtitles/CC
40 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
41 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
42 CaptionsButton.prototype.label_ = ' '
44 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
46 export type WebtorrentOptions = {
47 videoFiles: VideoFile[]
50 export type P2PMediaLoaderOptions = {
52 segmentsSha256Url: string
53 trackerAnnounce: string[]
54 redundancyBaseUrls: string[]
55 videoFiles: VideoFile[]
58 export interface CustomizationOptions {
59 startTime: number | string
60 stopTime: number | string
71 export interface CommonOptions extends CustomizationOptions {
72 playerElement: HTMLVideoElement
73 onPlayerElementChange: (element: HTMLVideoElement) => void
78 enableHotkeys: boolean
79 inactivityTimeout: number
82 theaterButton: boolean
90 videoCaptions: VideoJSCaption[]
92 userWatching?: UserWatching
97 export type PeertubePlayerManagerOptions = {
98 common: CommonOptions,
99 webtorrent: WebtorrentOptions,
100 p2pMediaLoader?: P2PMediaLoaderOptions
103 export class PeertubePlayerManager {
104 private static playerElementClassName: string
105 private static onPlayerChange: (player: VideoJsPlayer) => void
107 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: VideoJsPlayer) => void) {
108 let p2pMediaLoader: any
110 this.onPlayerChange = onPlayerChange
111 this.playerElementClassName = options.common.playerElement.className
113 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
114 if (mode === 'p2p-media-loader') {
115 [ p2pMediaLoader ] = await Promise.all([
116 import('p2p-media-loader-hlsjs'),
117 import('./p2p-media-loader/p2p-media-loader-plugin')
121 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
123 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
126 return new Promise(res => {
127 videojs(options.common.playerElement, videojsOptions, function (this: VideoJsPlayer) {
130 let alreadyFallback = false
132 player.tech(true).one('error', () => {
133 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
134 alreadyFallback = true
137 player.one('error', () => {
138 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
139 alreadyFallback = true
142 self.addContextMenu(mode, player, options.common.embedUrl)
151 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
152 if (currentMode === 'webtorrent') return
154 console.log('Fallback to webtorrent.')
156 const newVideoElement = document.createElement('video')
157 newVideoElement.className = this.playerElementClassName
159 // VideoJS wraps our video element inside a div
160 let currentParentPlayerElement = options.common.playerElement.parentNode
161 // Fix on IOS, don't ask me why
162 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
164 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
166 options.common.playerElement = newVideoElement
167 options.common.onPlayerElementChange(newVideoElement)
171 await import('./webtorrent/webtorrent-plugin')
173 const mode = 'webtorrent'
174 const videojsOptions = this.getVideojsOptions(mode, options)
177 videojs(newVideoElement, videojsOptions, function (this: VideoJsPlayer) {
180 self.addContextMenu(mode, player, options.common.embedUrl)
182 PeertubePlayerManager.onPlayerChange(player)
186 private static getVideojsOptions (
188 options: PeertubePlayerManagerOptions,
189 p2pMediaLoaderModule?: any
190 ): VideoJsPlayerOptions {
191 const commonOptions = options.common
193 let autoplay = commonOptions.autoplay
196 const plugins: VideoJSPluginOptions = {
199 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
200 videoViewUrl: commonOptions.videoViewUrl,
201 videoDuration: commonOptions.videoDuration,
202 userWatching: commonOptions.userWatching,
203 subtitle: commonOptions.subtitle,
204 videoCaptions: commonOptions.videoCaptions,
205 stopTime: commonOptions.stopTime
209 if (commonOptions.enableHotkeys === true) {
210 PeertubePlayerManager.addHotkeysOptions(plugins)
213 if (mode === 'p2p-media-loader') {
214 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
219 if (mode === 'webtorrent') {
220 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
222 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
226 const videojsOptions = {
229 // We don't use text track settings for now
230 textTrackSettings: false as any, // FIXME: typings
231 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
232 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
234 muted: commonOptions.muted !== undefined
235 ? commonOptions.muted
236 : undefined, // Undefined so the player knows it has to check the local storage
238 autoplay: autoplay === true
239 ? 'any' // Use 'any' instead of true to get notifier by videojs if autoplay fails
242 poster: commonOptions.poster,
243 inactivityTimeout: commonOptions.inactivityTimeout,
244 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
249 children: this.getControlBarChildren(mode, {
250 captions: commonOptions.captions,
251 peertubeLink: commonOptions.peertubeLink,
252 theaterButton: commonOptions.theaterButton,
253 nextVideo: commonOptions.nextVideo
254 }) as any // FIXME: typings
258 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
259 Object.assign(videojsOptions, { language: commonOptions.language })
262 return videojsOptions
265 private static addP2PMediaLoaderOptions (
266 plugins: VideoJSPluginOptions,
267 options: PeertubePlayerManagerOptions,
268 p2pMediaLoaderModule: any
270 const p2pMediaLoaderOptions = options.p2pMediaLoader
271 const commonOptions = options.common
273 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
274 .filter(t => t.startsWith('ws'))
276 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
278 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
279 redundancyUrlManager,
280 type: 'application/x-mpegURL',
281 startTime: commonOptions.startTime,
282 src: p2pMediaLoaderOptions.playlistUrl
285 let consumeOnly = false
287 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
288 console.log('We are on a cellular connection: disabling seeding.')
292 const p2pMediaLoaderConfig = {
295 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
296 rtcConfig: getRtcConfig(),
297 requiredSegmentsPriority: 5,
298 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
299 useP2P: getStoredP2PEnabled(),
303 swarmId: p2pMediaLoaderOptions.playlistUrl
307 levelLabelHandler: (level: { height: number, width: number }) => {
308 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === 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: VideoJsPlayer, 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: VideoJsPlayer) {
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: VideoJsPlayer) {
449 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
454 player.contextmenuUI({ content })
457 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
458 Object.assign(plugins, {
460 enableVolumeScroll: false,
461 enableModifiersForNumbers: false,
463 fullscreenKey: function (event: KeyboardEvent) {
464 // fullscreen with the f key or Ctrl+Enter
465 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
468 seekStep: function (event: KeyboardEvent) {
469 // mimic VLC seek behavior, and default to 5 (original value is 5).
470 if (event.ctrlKey && event.altKey) {
472 } else if (event.ctrlKey) {
474 } else if (event.altKey) {
482 increasePlaybackRateKey: {
483 key: function (event: KeyboardEvent) {
484 return event.key === '>'
486 handler: function (player: videojs.Player) {
487 const newValue = Math.min(player.playbackRate() + 0.1, 5)
488 player.playbackRate(parseFloat(newValue.toFixed(2)))
491 decreasePlaybackRateKey: {
492 key: function (event: KeyboardEvent) {
493 return event.key === '<'
495 handler: function (player: videojs.Player) {
496 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
497 player.playbackRate(parseFloat(newValue.toFixed(2)))
501 key: function (event: KeyboardEvent) {
502 return event.key === '.'
504 handler: function (player: videojs.Player) {
506 // Calculate movement distance (assuming 30 fps)
508 player.currentTime(player.currentTime() + dist)
517 // ############################################################################