1 import { VideoFile } from '../../../../shared/models/videos'
3 import * as videojs from 'video.js'
4 import 'videojs-hotkeys'
6 import 'videojs-contextmenu-ui'
7 import 'videojs-contrib-quality-levels'
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/peertube-link-button'
13 import './videojs-components/resolution-menu-button'
14 import './videojs-components/settings-menu-button'
15 import './videojs-components/p2p-info-button'
16 import './videojs-components/peertube-load-progress-bar'
17 import './videojs-components/theater-button'
18 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings'
19 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils'
20 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
21 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
22 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
23 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
24 import { getStoredP2PEnabled } from './peertube-player-local-storage'
25 import { TranslationsManager } from './translations-manager'
27 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
28 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
29 // Change Captions to Subtitles/CC
30 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
31 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
32 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
34 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
36 export type WebtorrentOptions = {
37 videoFiles: VideoFile[]
40 export type P2PMediaLoaderOptions = {
42 segmentsSha256Url: string
43 trackerAnnounce: string[]
44 redundancyBaseUrls: string[]
45 videoFiles: VideoFile[]
48 export interface CustomizationOptions {
49 startTime: number | string
50 stopTime: number | string
61 export interface CommonOptions extends CustomizationOptions {
62 playerElement: HTMLVideoElement
63 onPlayerElementChange: (element: HTMLVideoElement) => void
68 enableHotkeys: boolean
69 inactivityTimeout: number
72 theaterButton: boolean
80 videoCaptions: VideoJSCaption[]
82 userWatching?: UserWatching
87 export type PeertubePlayerManagerOptions = {
88 common: CommonOptions,
89 webtorrent: WebtorrentOptions,
90 p2pMediaLoader?: P2PMediaLoaderOptions
93 export class PeertubePlayerManager {
94 private static playerElementClassName: string
95 private static onPlayerChange: (player: any) => void
97 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: any) => void) {
98 let p2pMediaLoader: any
100 this.onPlayerChange = onPlayerChange
101 this.playerElementClassName = options.common.playerElement.className
103 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
104 if (mode === 'p2p-media-loader') {
105 [ p2pMediaLoader ] = await Promise.all([
106 import('p2p-media-loader-hlsjs'),
107 import('./p2p-media-loader/p2p-media-loader-plugin')
111 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
113 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
116 return new Promise(res => {
117 videojs(options.common.playerElement, videojsOptions, function (this: any) {
120 let alreadyFallback = false
122 player.tech_.one('error', () => {
123 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
124 alreadyFallback = true
127 player.one('error', () => {
128 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
129 alreadyFallback = true
132 self.addContextMenu(mode, player, options.common.embedUrl)
141 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
142 if (currentMode === 'webtorrent') return
144 console.log('Fallback to webtorrent.')
146 const newVideoElement = document.createElement('video')
147 newVideoElement.className = this.playerElementClassName
149 // VideoJS wraps our video element inside a div
150 let currentParentPlayerElement = options.common.playerElement.parentNode
151 // Fix on IOS, don't ask me why
152 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
154 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
156 options.common.playerElement = newVideoElement
157 options.common.onPlayerElementChange(newVideoElement)
161 await import('./webtorrent/webtorrent-plugin')
163 const mode = 'webtorrent'
164 const videojsOptions = this.getVideojsOptions(mode, options)
167 videojs(newVideoElement, videojsOptions, function (this: any) {
170 self.addContextMenu(mode, player, options.common.embedUrl)
172 PeertubePlayerManager.onPlayerChange(player)
176 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
177 const commonOptions = options.common
179 let autoplay = commonOptions.autoplay
182 const plugins: VideoJSPluginOptions = {
185 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
186 videoViewUrl: commonOptions.videoViewUrl,
187 videoDuration: commonOptions.videoDuration,
188 userWatching: commonOptions.userWatching,
189 subtitle: commonOptions.subtitle,
190 videoCaptions: commonOptions.videoCaptions,
191 stopTime: commonOptions.stopTime
195 if (commonOptions.enableHotkeys === true) {
196 PeertubePlayerManager.addHotkeysOptions(plugins)
199 if (mode === 'p2p-media-loader') {
200 const { streamrootHls } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
202 html5 = streamrootHls.html5
205 if (mode === 'webtorrent') {
206 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
208 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
212 const videojsOptions = {
215 // We don't use text track settings for now
216 textTrackSettings: false,
217 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
218 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
220 muted: commonOptions.muted !== undefined
221 ? commonOptions.muted
222 : undefined, // Undefined so the player knows it has to check the local storage
224 autoplay: autoplay === true
225 ? 'any' // Use 'any' instead of true to get notifier by videojs if autoplay fails
228 poster: commonOptions.poster,
229 inactivityTimeout: commonOptions.inactivityTimeout,
230 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
235 children: this.getControlBarChildren(mode, {
236 captions: commonOptions.captions,
237 peertubeLink: commonOptions.peertubeLink,
238 theaterButton: commonOptions.theaterButton,
239 nextVideo: commonOptions.nextVideo
244 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
245 Object.assign(videojsOptions, { language: commonOptions.language })
248 return videojsOptions
251 private static addP2PMediaLoaderOptions (
252 plugins: VideoJSPluginOptions,
253 options: PeertubePlayerManagerOptions,
254 p2pMediaLoaderModule: any
256 const p2pMediaLoaderOptions = options.p2pMediaLoader
257 const commonOptions = options.common
259 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
260 .filter(t => t.startsWith('ws'))
262 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
264 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
265 redundancyUrlManager,
266 type: 'application/x-mpegURL',
267 startTime: commonOptions.startTime,
268 src: p2pMediaLoaderOptions.playlistUrl
271 let consumeOnly = false
273 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
274 console.log('We are on a cellular connection: disabling seeding.')
278 const p2pMediaLoaderConfig = {
281 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
282 rtcConfig: getRtcConfig(),
283 requiredSegmentsPriority: 5,
284 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
285 useP2P: getStoredP2PEnabled(),
289 swarmId: p2pMediaLoaderOptions.playlistUrl
292 const streamrootHls = {
293 levelLabelHandler: (level: { height: number, width: number }) => {
294 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
296 let label = file.resolution.label
297 if (file.fps >= 50) label += file.fps
303 capLevelToPlayerSize: true,
304 autoStartLoad: false,
305 liveSyncDurationCount: 7,
306 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
311 const toAssign = { p2pMediaLoader, streamrootHls }
312 Object.assign(plugins, toAssign)
317 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
318 const commonOptions = options.common
319 const webtorrentOptions = options.webtorrent
322 autoplay: commonOptions.autoplay,
323 videoDuration: commonOptions.videoDuration,
324 playerElement: commonOptions.playerElement,
325 videoFiles: webtorrentOptions.videoFiles,
326 startTime: commonOptions.startTime
329 Object.assign(plugins, { webtorrent })
332 private static getControlBarChildren (mode: PlayerMode, options: {
333 peertubeLink: boolean
334 theaterButton: boolean,
338 const settingEntries = []
339 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
342 settingEntries.push('playbackRateMenuButton')
343 if (options.captions === true) settingEntries.push('captionsButton')
344 settingEntries.push('resolutionMenuButton')
350 if (options.nextVideo) {
351 Object.assign(children, {
353 handler: options.nextVideo
358 Object.assign(children, {
359 'currentTimeDisplay': {},
361 'durationDisplay': {},
364 'flexibleWidthSpacer': {},
369 [loadProgressBar]: {},
370 'mouseTimeDisplay': {},
371 'playProgressBar': {}
386 entries: settingEntries
390 if (options.peertubeLink === true) {
391 Object.assign(children, {
392 'peerTubeLinkButton': {}
396 if (options.theaterButton === true) {
397 Object.assign(children, {
402 Object.assign(children, {
403 'fullscreenToggle': {}
409 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
412 label: player.localize('Copy the video URL'),
413 listener: function () {
414 copyToClipboard(buildVideoLink())
418 label: player.localize('Copy the video URL at the current time'),
419 listener: function () {
420 const player = this as videojs.Player
421 copyToClipboard(buildVideoLink({ startTime: player.currentTime() }))
425 label: player.localize('Copy embed code'),
427 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
432 if (mode === 'webtorrent') {
434 label: player.localize('Copy magnet URI'),
435 listener: function () {
436 const player = this as videojs.Player
437 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
442 player.contextmenuUI({ content })
445 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
446 Object.assign(plugins, {
448 enableVolumeScroll: false,
449 enableModifiersForNumbers: false,
451 fullscreenKey: function (event: KeyboardEvent) {
452 // fullscreen with the f key or Ctrl+Enter
453 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
456 seekStep: function (event: KeyboardEvent) {
457 // mimic VLC seek behavior, and default to 5 (original value is 5).
458 if (event.ctrlKey && event.altKey) {
460 } else if (event.ctrlKey) {
462 } else if (event.altKey) {
470 increasePlaybackRateKey: {
471 key: function (event: KeyboardEvent) {
472 return event.key === '>'
474 handler: function (player: videojs.Player) {
475 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
478 decreasePlaybackRateKey: {
479 key: function (event: KeyboardEvent) {
480 return event.key === '<'
482 handler: function (player: videojs.Player) {
483 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
487 key: function (event: KeyboardEvent) {
488 return event.key === '.'
490 handler: function (player: videojs.Player) {
492 // Calculate movement distance (assuming 30 fps)
494 player.currentTime(player.currentTime() + dist)
503 // ############################################################################