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)
139 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
140 if (currentMode === 'webtorrent') return
142 console.log('Fallback to webtorrent.')
144 const newVideoElement = document.createElement('video')
145 newVideoElement.className = this.playerElementClassName
147 // VideoJS wraps our video element inside a div
148 let currentParentPlayerElement = options.common.playerElement.parentNode
149 // Fix on IOS, don't ask me why
150 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
152 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
154 options.common.playerElement = newVideoElement
155 options.common.onPlayerElementChange(newVideoElement)
159 await import('./webtorrent/webtorrent-plugin')
161 const mode = 'webtorrent'
162 const videojsOptions = this.getVideojsOptions(mode, options)
165 videojs(newVideoElement, videojsOptions, function (this: any) {
168 self.addContextMenu(mode, player, options.common.embedUrl)
170 PeertubePlayerManager.onPlayerChange(player)
174 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
175 const commonOptions = options.common
177 let autoplay = commonOptions.autoplay
180 const plugins: VideoJSPluginOptions = {
183 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
184 videoViewUrl: commonOptions.videoViewUrl,
185 videoDuration: commonOptions.videoDuration,
186 userWatching: commonOptions.userWatching,
187 subtitle: commonOptions.subtitle,
188 videoCaptions: commonOptions.videoCaptions,
189 stopTime: commonOptions.stopTime
193 if (commonOptions.enableHotkeys === true) {
194 PeertubePlayerManager.addHotkeysOptions(plugins)
197 if (mode === 'p2p-media-loader') {
198 const { streamrootHls } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
200 html5 = streamrootHls.html5
203 if (mode === 'webtorrent') {
204 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
206 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
210 const videojsOptions = {
213 // We don't use text track settings for now
214 textTrackSettings: false,
215 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
216 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
218 muted: commonOptions.muted !== undefined
219 ? commonOptions.muted
220 : undefined, // Undefined so the player knows it has to check the local storage
222 autoplay: autoplay === true
223 ? 'any' // Use 'any' instead of true to get notifier by videojs if autoplay fails
226 poster: commonOptions.poster,
227 inactivityTimeout: commonOptions.inactivityTimeout,
228 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
233 children: this.getControlBarChildren(mode, {
234 captions: commonOptions.captions,
235 peertubeLink: commonOptions.peertubeLink,
236 theaterButton: commonOptions.theaterButton
241 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
242 Object.assign(videojsOptions, { language: commonOptions.language })
245 return videojsOptions
248 private static addP2PMediaLoaderOptions (
249 plugins: VideoJSPluginOptions,
250 options: PeertubePlayerManagerOptions,
251 p2pMediaLoaderModule: any
253 const p2pMediaLoaderOptions = options.p2pMediaLoader
254 const commonOptions = options.common
256 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
257 .filter(t => t.startsWith('ws'))
259 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
261 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
262 redundancyUrlManager,
263 type: 'application/x-mpegURL',
264 startTime: commonOptions.startTime,
265 src: p2pMediaLoaderOptions.playlistUrl
268 let consumeOnly = false
270 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
271 console.log('We are on a cellular connection: disabling seeding.')
275 const p2pMediaLoaderConfig = {
278 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
279 rtcConfig: getRtcConfig(),
280 requiredSegmentsPriority: 5,
281 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
282 useP2P: getStoredP2PEnabled(),
286 swarmId: p2pMediaLoaderOptions.playlistUrl
289 const streamrootHls = {
290 levelLabelHandler: (level: { height: number, width: number }) => {
291 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
293 let label = file.resolution.label
294 if (file.fps >= 50) label += file.fps
300 capLevelToPlayerSize: true,
301 autoStartLoad: false,
302 liveSyncDurationCount: 7,
303 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
308 const toAssign = { p2pMediaLoader, streamrootHls }
309 Object.assign(plugins, toAssign)
314 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
315 const commonOptions = options.common
316 const webtorrentOptions = options.webtorrent
319 autoplay: commonOptions.autoplay,
320 videoDuration: commonOptions.videoDuration,
321 playerElement: commonOptions.playerElement,
322 videoFiles: webtorrentOptions.videoFiles,
323 startTime: commonOptions.startTime
326 Object.assign(plugins, { webtorrent })
329 private static getControlBarChildren (mode: PlayerMode, options: {
330 peertubeLink: boolean
331 theaterButton: boolean,
334 const settingEntries = []
335 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
338 settingEntries.push('playbackRateMenuButton')
339 if (options.captions === true) settingEntries.push('captionsButton')
340 settingEntries.push('resolutionMenuButton')
344 'currentTimeDisplay': {},
346 'durationDisplay': {},
349 'flexibleWidthSpacer': {},
354 [loadProgressBar]: {},
355 'mouseTimeDisplay': {},
356 'playProgressBar': {}
371 entries: settingEntries
375 if (options.peertubeLink === true) {
376 Object.assign(children, {
377 'peerTubeLinkButton': {}
381 if (options.theaterButton === true) {
382 Object.assign(children, {
387 Object.assign(children, {
388 'fullscreenToggle': {}
394 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
397 label: player.localize('Copy the video URL'),
398 listener: function () {
399 copyToClipboard(buildVideoLink())
403 label: player.localize('Copy the video URL at the current time'),
404 listener: function () {
405 const player = this as videojs.Player
406 copyToClipboard(buildVideoLink({ startTime: player.currentTime() }))
410 label: player.localize('Copy embed code'),
412 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
417 if (mode === 'webtorrent') {
419 label: player.localize('Copy magnet URI'),
420 listener: function () {
421 const player = this as videojs.Player
422 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
427 player.contextmenuUI({ content })
430 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
431 Object.assign(plugins, {
433 enableVolumeScroll: false,
434 enableModifiersForNumbers: false,
436 fullscreenKey: function (event: KeyboardEvent) {
437 // fullscreen with the f key or Ctrl+Enter
438 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
441 seekStep: function (event: KeyboardEvent) {
442 // mimic VLC seek behavior, and default to 5 (original value is 5).
443 if (event.ctrlKey && event.altKey) {
445 } else if (event.ctrlKey) {
447 } else if (event.altKey) {
455 increasePlaybackRateKey: {
456 key: function (event: KeyboardEvent) {
457 return event.key === '>'
459 handler: function (player: videojs.Player) {
460 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
463 decreasePlaybackRateKey: {
464 key: function (event: KeyboardEvent) {
465 return event.key === '<'
467 handler: function (player: videojs.Player) {
468 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
472 key: function (event: KeyboardEvent) {
473 return event.key === '.'
475 handler: function (player: videojs.Player) {
477 // Calculate movement distance (assuming 30 fps)
479 player.currentTime(player.currentTime() + dist)
488 // ############################################################################