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, getRtcConfig } from './utils'
17 import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n'
18 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
19 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
21 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
22 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
23 // Change Captions to Subtitles/CC
24 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
25 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
26 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
28 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
30 export type WebtorrentOptions = {
31 videoFiles: VideoFile[]
34 export type P2PMediaLoaderOptions = {
36 segmentsSha256Url: string
37 trackerAnnounce: string[]
38 redundancyBaseUrls: string[]
39 videoFiles: VideoFile[]
42 export type CommonOptions = {
43 playerElement: HTMLVideoElement
47 enableHotkeys: boolean
48 inactivityTimeout: number
50 startTime: number | string
65 videoCaptions: VideoJSCaption[]
67 userWatching?: UserWatching
72 export type PeertubePlayerManagerOptions = {
73 common: CommonOptions,
74 webtorrent?: WebtorrentOptions,
75 p2pMediaLoader?: P2PMediaLoaderOptions
78 export class PeertubePlayerManager {
80 private static videojsLocaleCache: { [ path: string ]: any } = {}
82 static getServerTranslations (serverUrl: string, locale: string) {
83 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
84 // It is the default locale, nothing to translate
85 if (!path) return Promise.resolve(undefined)
87 return fetch(path + '/server.json')
88 .then(res => res.json())
90 console.error('Cannot get server translations', err)
95 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
96 let p2pMediaLoader: any
98 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
99 if (mode === 'p2p-media-loader') {
100 [ p2pMediaLoader ] = await Promise.all([
101 import('p2p-media-loader-hlsjs'),
102 import('./p2p-media-loader/p2p-media-loader-plugin')
106 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
108 await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language)
111 return new Promise(res => {
112 videojs(options.common.playerElement, videojsOptions, function (this: any) {
115 self.addContextMenu(mode, player, options.common.embedUrl)
122 private static loadLocaleInVideoJS (serverUrl: string, locale: string) {
123 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
124 // It is the default locale, nothing to translate
125 if (!path) return Promise.resolve(undefined)
129 if (PeertubePlayerManager.videojsLocaleCache[path]) {
130 p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path])
132 p = fetch(path + '/player.json')
133 .then(res => res.json())
135 PeertubePlayerManager.videojsLocaleCache[path] = json
139 console.error('Cannot get player translations', err)
144 const completeLocale = getCompleteLocale(locale)
145 return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
148 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
149 const commonOptions = options.common
150 const webtorrentOptions = options.webtorrent
151 const p2pMediaLoaderOptions = options.p2pMediaLoader
153 let autoplay = options.common.autoplay
156 const plugins: VideoJSPluginOptions = {
159 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
160 videoViewUrl: commonOptions.videoViewUrl,
161 videoDuration: commonOptions.videoDuration,
162 startTime: commonOptions.startTime,
163 userWatching: commonOptions.userWatching,
164 subtitle: commonOptions.subtitle,
165 videoCaptions: commonOptions.videoCaptions
169 if (p2pMediaLoaderOptions) {
170 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
171 redundancyBaseUrls: options.p2pMediaLoader.redundancyBaseUrls,
172 type: 'application/x-mpegURL',
173 src: p2pMediaLoaderOptions.playlistUrl
176 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
177 .filter(t => t.startsWith('ws'))
179 const p2pMediaLoaderConfig = {
182 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
183 rtcConfig: getRtcConfig(),
184 requiredSegmentsPriority: 5,
185 segmentUrlBuilder: segmentUrlBuilderFactory(options.p2pMediaLoader.redundancyBaseUrls)
188 swarmId: p2pMediaLoaderOptions.playlistUrl
191 const streamrootHls = {
192 levelLabelHandler: (level: { height: number, width: number }) => {
193 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
195 let label = file.resolution.label
196 if (file.fps >= 50) label += file.fps
202 liveSyncDurationCount: 7,
203 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
208 Object.assign(plugins, { p2pMediaLoader, streamrootHls })
209 html5 = streamrootHls.html5
212 if (webtorrentOptions) {
215 videoDuration: commonOptions.videoDuration,
216 playerElement: commonOptions.playerElement,
217 videoFiles: webtorrentOptions.videoFiles
219 Object.assign(plugins, { webtorrent })
221 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
225 const videojsOptions = {
228 // We don't use text track settings for now
229 textTrackSettings: false,
230 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
231 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
233 muted: commonOptions.muted !== undefined
234 ? commonOptions.muted
235 : undefined, // Undefined so the player knows it has to check the local storage
237 poster: commonOptions.poster,
239 inactivityTimeout: commonOptions.inactivityTimeout,
240 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
243 children: this.getControlBarChildren(mode, {
244 captions: commonOptions.captions,
245 peertubeLink: commonOptions.peertubeLink,
246 theaterMode: commonOptions.theaterMode
251 if (commonOptions.enableHotkeys === true) {
252 Object.assign(videojsOptions.plugins, {
254 enableVolumeScroll: false,
255 enableModifiersForNumbers: false,
257 fullscreenKey: function (event: KeyboardEvent) {
258 // fullscreen with the f key or Ctrl+Enter
259 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
262 seekStep: function (event: KeyboardEvent) {
263 // mimic VLC seek behavior, and default to 5 (original value is 5).
264 if (event.ctrlKey && event.altKey) {
266 } else if (event.ctrlKey) {
268 } else if (event.altKey) {
276 increasePlaybackRateKey: {
277 key: function (event: KeyboardEvent) {
278 return event.key === '>'
280 handler: function (player: videojs.Player) {
281 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
284 decreasePlaybackRateKey: {
285 key: function (event: KeyboardEvent) {
286 return event.key === '<'
288 handler: function (player: videojs.Player) {
289 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
293 key: function (event: KeyboardEvent) {
294 return event.key === '.'
296 handler: function (player: videojs.Player) {
298 // Calculate movement distance (assuming 30 fps)
300 player.currentTime(player.currentTime() + dist)
308 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
309 Object.assign(videojsOptions, { language: commonOptions.language })
312 return videojsOptions
315 private static getControlBarChildren (mode: PlayerMode, options: {
316 peertubeLink: boolean
317 theaterMode: boolean,
320 const settingEntries = []
321 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
324 settingEntries.push('playbackRateMenuButton')
325 if (options.captions === true) settingEntries.push('captionsButton')
326 settingEntries.push('resolutionMenuButton')
330 'currentTimeDisplay': {},
332 'durationDisplay': {},
335 'flexibleWidthSpacer': {},
340 [loadProgressBar]: {},
341 'mouseTimeDisplay': {},
342 'playProgressBar': {}
357 entries: settingEntries
361 if (options.peertubeLink === true) {
362 Object.assign(children, {
363 'peerTubeLinkButton': {}
367 if (options.theaterMode === true) {
368 Object.assign(children, {
373 Object.assign(children, {
374 'fullscreenToggle': {}
380 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
383 label: player.localize('Copy the video URL'),
384 listener: function () {
385 copyToClipboard(buildVideoLink())
389 label: player.localize('Copy the video URL at the current time'),
390 listener: function () {
391 const player = this as videojs.Player
392 copyToClipboard(buildVideoLink(player.currentTime()))
396 label: player.localize('Copy embed code'),
398 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
403 if (mode === 'webtorrent') {
405 label: player.localize('Copy magnet URI'),
406 listener: function () {
407 const player = this as videojs.Player
408 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
413 player.contextmenuUI({ content })
416 private static getLocalePath (serverUrl: string, locale: string) {
417 const completeLocale = getCompleteLocale(locale)
419 if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
421 return serverUrl + '/client/locales/' + completeLocale
425 // ############################################################################