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/peertube-link-button'
12 import './videojs-components/resolution-menu-button'
13 import './videojs-components/settings-menu-button'
14 import './videojs-components/p2p-info-button'
15 import './videojs-components/peertube-load-progress-bar'
16 import './videojs-components/theater-button'
17 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings'
18 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils'
19 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
20 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
21 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
22 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
23 import { getStoredP2PEnabled } from './peertube-player-local-storage'
24 import { TranslationsManager } from './translations-manager'
26 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
27 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
28 // Change Captions to Subtitles/CC
29 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
30 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
31 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
33 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
35 export type WebtorrentOptions = {
36 videoFiles: VideoFile[]
39 export type P2PMediaLoaderOptions = {
41 segmentsSha256Url: string
42 trackerAnnounce: string[]
43 redundancyBaseUrls: string[]
44 videoFiles: VideoFile[]
47 export interface CustomizationOptions {
48 startTime: number | string
49 stopTime: number | string
60 export interface CommonOptions extends CustomizationOptions {
61 playerElement: HTMLVideoElement
62 onPlayerElementChange: (element: HTMLVideoElement) => void
66 enableHotkeys: boolean
67 inactivityTimeout: number
70 theaterButton: boolean
78 videoCaptions: VideoJSCaption[]
80 userWatching?: UserWatching
85 export type PeertubePlayerManagerOptions = {
86 common: CommonOptions,
87 webtorrent: WebtorrentOptions,
88 p2pMediaLoader?: P2PMediaLoaderOptions
91 export class PeertubePlayerManager {
92 private static playerElementClassName: string
93 private static onPlayerChange: (player: any) => void
95 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: any) => void) {
96 let p2pMediaLoader: any
98 this.onPlayerChange = onPlayerChange
99 this.playerElementClassName = options.common.playerElement.className
101 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
102 if (mode === 'p2p-media-loader') {
103 [ p2pMediaLoader ] = await Promise.all([
104 import('p2p-media-loader-hlsjs'),
105 import('./p2p-media-loader/p2p-media-loader-plugin')
109 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
111 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
114 return new Promise(res => {
115 videojs(options.common.playerElement, videojsOptions, function (this: any) {
118 let alreadyFallback = false
120 player.tech_.one('error', () => {
121 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
122 alreadyFallback = true
125 player.one('error', () => {
126 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
127 alreadyFallback = true
130 self.addContextMenu(mode, player, options.common.embedUrl)
137 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
138 if (currentMode === 'webtorrent') return
140 console.log('Fallback to webtorrent.')
142 const newVideoElement = document.createElement('video')
143 newVideoElement.className = this.playerElementClassName
145 // VideoJS wraps our video element inside a div
146 let currentParentPlayerElement = options.common.playerElement.parentNode
147 // Fix on IOS, don't ask me why
148 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
150 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
152 options.common.playerElement = newVideoElement
153 options.common.onPlayerElementChange(newVideoElement)
157 await import('./webtorrent/webtorrent-plugin')
159 const mode = 'webtorrent'
160 const videojsOptions = this.getVideojsOptions(mode, options)
163 videojs(newVideoElement, videojsOptions, function (this: any) {
166 self.addContextMenu(mode, player, options.common.embedUrl)
168 PeertubePlayerManager.onPlayerChange(player)
172 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
173 const commonOptions = options.common
175 let autoplay = commonOptions.autoplay
178 const plugins: VideoJSPluginOptions = {
181 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
182 videoViewUrl: commonOptions.videoViewUrl,
183 videoDuration: commonOptions.videoDuration,
184 userWatching: commonOptions.userWatching,
185 subtitle: commonOptions.subtitle,
186 videoCaptions: commonOptions.videoCaptions,
187 stopTime: commonOptions.stopTime
191 if (commonOptions.enableHotkeys === true) {
192 PeertubePlayerManager.addHotkeysOptions(plugins)
195 if (mode === 'p2p-media-loader') {
196 const { streamrootHls } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
198 html5 = streamrootHls.html5
201 if (mode === 'webtorrent') {
202 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
204 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
208 const videojsOptions = {
211 // We don't use text track settings for now
212 textTrackSettings: false,
213 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
214 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
216 muted: commonOptions.muted !== undefined
217 ? commonOptions.muted
218 : undefined, // Undefined so the player knows it has to check the local storage
220 autoplay: autoplay === true
221 ? 'any' // Use 'any' instead of true to get notifier by videojs if autoplay fails
224 poster: commonOptions.poster,
225 inactivityTimeout: commonOptions.inactivityTimeout,
226 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
231 children: this.getControlBarChildren(mode, {
232 captions: commonOptions.captions,
233 peertubeLink: commonOptions.peertubeLink,
234 theaterButton: commonOptions.theaterButton
239 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
240 Object.assign(videojsOptions, { language: commonOptions.language })
243 return videojsOptions
246 private static addP2PMediaLoaderOptions (
247 plugins: VideoJSPluginOptions,
248 options: PeertubePlayerManagerOptions,
249 p2pMediaLoaderModule: any
251 const p2pMediaLoaderOptions = options.p2pMediaLoader
252 const commonOptions = options.common
254 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
255 .filter(t => t.startsWith('ws'))
257 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
259 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
260 redundancyUrlManager,
261 type: 'application/x-mpegURL',
262 startTime: commonOptions.startTime,
263 src: p2pMediaLoaderOptions.playlistUrl
266 let consumeOnly = false
268 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
269 console.log('We are on a cellular connection: disabling seeding.')
273 const p2pMediaLoaderConfig = {
276 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
277 rtcConfig: getRtcConfig(),
278 requiredSegmentsPriority: 5,
279 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
280 useP2P: getStoredP2PEnabled(),
284 swarmId: p2pMediaLoaderOptions.playlistUrl
287 const streamrootHls = {
288 levelLabelHandler: (level: { height: number, width: number }) => {
289 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
291 let label = file.resolution.label
292 if (file.fps >= 50) label += file.fps
298 capLevelToPlayerSize: true,
299 autoStartLoad: false,
300 liveSyncDurationCount: 7,
301 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
306 const toAssign = { p2pMediaLoader, streamrootHls }
307 Object.assign(plugins, toAssign)
312 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
313 const commonOptions = options.common
314 const webtorrentOptions = options.webtorrent
317 autoplay: commonOptions.autoplay,
318 videoDuration: commonOptions.videoDuration,
319 playerElement: commonOptions.playerElement,
320 videoFiles: webtorrentOptions.videoFiles,
321 startTime: commonOptions.startTime
324 Object.assign(plugins, { webtorrent })
327 private static getControlBarChildren (mode: PlayerMode, options: {
328 peertubeLink: boolean
329 theaterButton: boolean,
332 const settingEntries = []
333 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
336 settingEntries.push('playbackRateMenuButton')
337 if (options.captions === true) settingEntries.push('captionsButton')
338 settingEntries.push('resolutionMenuButton')
342 'currentTimeDisplay': {},
344 'durationDisplay': {},
347 'flexibleWidthSpacer': {},
352 [loadProgressBar]: {},
353 'mouseTimeDisplay': {},
354 'playProgressBar': {}
369 entries: settingEntries
373 if (options.peertubeLink === true) {
374 Object.assign(children, {
375 'peerTubeLinkButton': {}
379 if (options.theaterButton === true) {
380 Object.assign(children, {
385 Object.assign(children, {
386 'fullscreenToggle': {}
392 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
395 label: player.localize('Copy the video URL'),
396 listener: function () {
397 copyToClipboard(buildVideoLink())
401 label: player.localize('Copy the video URL at the current time'),
402 listener: function () {
403 const player = this as videojs.Player
404 copyToClipboard(buildVideoLink({ startTime: player.currentTime() }))
408 label: player.localize('Copy embed code'),
410 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
415 if (mode === 'webtorrent') {
417 label: player.localize('Copy magnet URI'),
418 listener: function () {
419 const player = this as videojs.Player
420 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
425 player.contextmenuUI({ content })
428 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
429 Object.assign(plugins, {
431 enableVolumeScroll: false,
432 enableModifiersForNumbers: false,
434 fullscreenKey: function (event: KeyboardEvent) {
435 // fullscreen with the f key or Ctrl+Enter
436 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
439 seekStep: function (event: KeyboardEvent) {
440 // mimic VLC seek behavior, and default to 5 (original value is 5).
441 if (event.ctrlKey && event.altKey) {
443 } else if (event.ctrlKey) {
445 } else if (event.altKey) {
453 increasePlaybackRateKey: {
454 key: function (event: KeyboardEvent) {
455 return event.key === '>'
457 handler: function (player: videojs.Player) {
458 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
461 decreasePlaybackRateKey: {
462 key: function (event: KeyboardEvent) {
463 return event.key === '<'
465 handler: function (player: videojs.Player) {
466 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
470 key: function (event: KeyboardEvent) {
471 return event.key === '.'
473 handler: function (player: videojs.Player) {
475 // Calculate movement distance (assuming 30 fps)
477 player.currentTime(player.currentTime() + dist)
486 // ############################################################################