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 './peertube-plugin'
9 import './videojs-components/peertube-link-button'
10 import './videojs-components/resolution-menu-button'
11 import './videojs-components/settings-menu-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-load-progress-bar'
14 import './videojs-components/theater-button'
15 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings'
16 import { buildVideoEmbed, buildVideoLink, copyToClipboard } from './utils'
17 import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n'
18 import { Engine } from 'p2p-media-loader-hlsjs'
20 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
21 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
22 // Change Captions to Subtitles/CC
23 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
24 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
25 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
27 type PlayerMode = 'webtorrent' | 'p2p-media-loader'
29 type WebtorrentOptions = {
30 videoFiles: VideoFile[]
33 type P2PMediaLoaderOptions = {
37 type CommonOptions = {
38 playerElement: HTMLVideoElement
42 enableHotkeys: boolean
43 inactivityTimeout: number
45 startTime: number | string
60 videoCaptions: VideoJSCaption[]
62 userWatching?: UserWatching
67 export type PeertubePlayerManagerOptions = {
68 common: CommonOptions,
69 webtorrent?: WebtorrentOptions,
70 p2pMediaLoader?: P2PMediaLoaderOptions
73 export class PeertubePlayerManager {
75 private static videojsLocaleCache: { [ path: string ]: any } = {}
77 static getServerTranslations (serverUrl: string, locale: string) {
78 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
79 // It is the default locale, nothing to translate
80 if (!path) return Promise.resolve(undefined)
82 return fetch(path + '/server.json')
83 .then(res => res.json())
85 console.error('Cannot get server translations', err)
90 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
91 if (mode === 'webtorrent') await import('./webtorrent-plugin')
92 if (mode === 'p2p-media-loader') await import('./p2p-media-loader-plugin')
94 const videojsOptions = this.getVideojsOptions(mode, options)
96 await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language)
99 return new Promise(res => {
100 videojs(options.common.playerElement, videojsOptions, function (this: any) {
103 self.addContextMenu(mode, player, options.common.embedUrl)
110 private static loadLocaleInVideoJS (serverUrl: string, locale: string) {
111 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
112 // It is the default locale, nothing to translate
113 if (!path) return Promise.resolve(undefined)
117 if (PeertubePlayerManager.videojsLocaleCache[path]) {
118 p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path])
120 p = fetch(path + '/player.json')
121 .then(res => res.json())
123 PeertubePlayerManager.videojsLocaleCache[path] = json
127 console.error('Cannot get player translations', err)
132 const completeLocale = getCompleteLocale(locale)
133 return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
136 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
137 const commonOptions = options.common
138 const webtorrentOptions = options.webtorrent
139 const p2pMediaLoaderOptions = options.p2pMediaLoader
141 const plugins: VideoJSPluginOptions = {
143 autoplay: commonOptions.autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
144 videoViewUrl: commonOptions.videoViewUrl,
145 videoDuration: commonOptions.videoDuration,
146 startTime: commonOptions.startTime,
147 userWatching: commonOptions.userWatching,
148 subtitle: commonOptions.subtitle,
149 videoCaptions: commonOptions.videoCaptions
153 if (p2pMediaLoaderOptions) {
154 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
155 type: 'application/x-mpegURL',
156 src: p2pMediaLoaderOptions.playlistUrl
161 swarmId: 'swarm' // TODO: choose swarm id
164 const streamrootHls = {
167 liveSyncDurationCount: 7,
168 loader: new Engine(config).createLoaderClass()
173 Object.assign(plugins, { p2pMediaLoader, streamrootHls })
176 if (webtorrentOptions) {
178 autoplay: commonOptions.autoplay,
179 videoDuration: commonOptions.videoDuration,
180 playerElement: commonOptions.playerElement,
181 videoFiles: webtorrentOptions.videoFiles
183 Object.assign(plugins, { webtorrent })
186 const videojsOptions = {
187 // We don't use text track settings for now
188 textTrackSettings: false,
189 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
190 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
192 muted: commonOptions.muted !== undefined
193 ? commonOptions.muted
194 : undefined, // Undefined so the player knows it has to check the local storage
196 poster: commonOptions.poster,
198 inactivityTimeout: commonOptions.inactivityTimeout,
199 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
202 children: this.getControlBarChildren(mode, {
203 captions: commonOptions.captions,
204 peertubeLink: commonOptions.peertubeLink,
205 theaterMode: commonOptions.theaterMode
210 if (commonOptions.enableHotkeys === true) {
211 Object.assign(videojsOptions.plugins, {
213 enableVolumeScroll: false,
214 enableModifiersForNumbers: false,
216 fullscreenKey: function (event: KeyboardEvent) {
217 // fullscreen with the f key or Ctrl+Enter
218 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
221 seekStep: function (event: KeyboardEvent) {
222 // mimic VLC seek behavior, and default to 5 (original value is 5).
223 if (event.ctrlKey && event.altKey) {
225 } else if (event.ctrlKey) {
227 } else if (event.altKey) {
235 increasePlaybackRateKey: {
236 key: function (event: KeyboardEvent) {
237 return event.key === '>'
239 handler: function (player: videojs.Player) {
240 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
243 decreasePlaybackRateKey: {
244 key: function (event: KeyboardEvent) {
245 return event.key === '<'
247 handler: function (player: videojs.Player) {
248 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
252 key: function (event: KeyboardEvent) {
253 return event.key === '.'
255 handler: function (player: videojs.Player) {
257 // Calculate movement distance (assuming 30 fps)
259 player.currentTime(player.currentTime() + dist)
267 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
268 Object.assign(videojsOptions, { language: commonOptions.language })
271 return videojsOptions
274 private static getControlBarChildren (mode: PlayerMode, options: {
275 peertubeLink: boolean
276 theaterMode: boolean,
279 const settingEntries = []
280 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
283 settingEntries.push('playbackRateMenuButton')
284 if (options.captions === true) settingEntries.push('captionsButton')
285 settingEntries.push('resolutionMenuButton')
289 'currentTimeDisplay': {},
291 'durationDisplay': {},
294 'flexibleWidthSpacer': {},
299 [loadProgressBar]: {},
300 'mouseTimeDisplay': {},
301 'playProgressBar': {}
316 entries: settingEntries
320 if (options.peertubeLink === true) {
321 Object.assign(children, {
322 'peerTubeLinkButton': {}
326 if (options.theaterMode === true) {
327 Object.assign(children, {
332 Object.assign(children, {
333 'fullscreenToggle': {}
339 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
342 label: player.localize('Copy the video URL'),
343 listener: function () {
344 copyToClipboard(buildVideoLink())
348 label: player.localize('Copy the video URL at the current time'),
349 listener: function () {
350 const player = this as videojs.Player
351 copyToClipboard(buildVideoLink(player.currentTime()))
355 label: player.localize('Copy embed code'),
357 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
362 if (mode === 'webtorrent') {
364 label: player.localize('Copy magnet URI'),
365 listener: function () {
366 const player = this as videojs.Player
367 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
372 player.contextmenuUI({ content })
375 private static getLocalePath (serverUrl: string, locale: string) {
376 const completeLocale = getCompleteLocale(locale)
378 if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
380 return serverUrl + '/client/locales/' + completeLocale
384 // ############################################################################