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
44 onPlayerElementChange: (element: HTMLVideoElement) => void
48 enableHotkeys: boolean
49 inactivityTimeout: number
51 startTime: number | string
52 stopTime: number | string
67 videoCaptions: VideoJSCaption[]
69 userWatching?: UserWatching
74 export type PeertubePlayerManagerOptions = {
75 common: CommonOptions,
76 webtorrent: WebtorrentOptions,
77 p2pMediaLoader?: P2PMediaLoaderOptions
80 export class PeertubePlayerManager {
82 private static videojsLocaleCache: { [ path: string ]: any } = {}
83 private static playerElementClassName: string
85 static getServerTranslations (serverUrl: string, locale: string) {
86 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
87 // It is the default locale, nothing to translate
88 if (!path) return Promise.resolve(undefined)
90 return fetch(path + '/server.json')
91 .then(res => res.json())
93 console.error('Cannot get server translations', err)
98 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
99 let p2pMediaLoader: any
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 this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language)
116 return new Promise(res => {
117 videojs(options.common.playerElement, videojsOptions, function (this: any) {
120 player.tech_.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options))
121 player.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options))
123 self.addContextMenu(mode, player, options.common.embedUrl)
130 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
131 if (currentMode === 'webtorrent') return
133 console.log('Fallback to webtorrent.')
135 const newVideoElement = document.createElement('video')
136 newVideoElement.className = this.playerElementClassName
138 // VideoJS wraps our video element inside a div
139 let currentParentPlayerElement = options.common.playerElement.parentNode
140 // Fix on IOS, don't ask me why
141 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
143 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
145 options.common.playerElement = newVideoElement
146 options.common.onPlayerElementChange(newVideoElement)
150 await import('./webtorrent/webtorrent-plugin')
152 const mode = 'webtorrent'
153 const videojsOptions = this.getVideojsOptions(mode, options)
156 videojs(newVideoElement, videojsOptions, function (this: any) {
159 self.addContextMenu(mode, player, options.common.embedUrl)
163 private static loadLocaleInVideoJS (serverUrl: string, locale: string) {
164 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
165 // It is the default locale, nothing to translate
166 if (!path) return Promise.resolve(undefined)
170 if (PeertubePlayerManager.videojsLocaleCache[path]) {
171 p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path])
173 p = fetch(path + '/player.json')
174 .then(res => res.json())
176 PeertubePlayerManager.videojsLocaleCache[path] = json
180 console.error('Cannot get player translations', err)
185 const completeLocale = getCompleteLocale(locale)
186 return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
189 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
190 const commonOptions = options.common
191 const webtorrentOptions = options.webtorrent
192 const p2pMediaLoaderOptions = options.p2pMediaLoader
194 let autoplay = options.common.autoplay
197 const plugins: VideoJSPluginOptions = {
200 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
201 videoViewUrl: commonOptions.videoViewUrl,
202 videoDuration: commonOptions.videoDuration,
203 userWatching: commonOptions.userWatching,
204 subtitle: commonOptions.subtitle,
205 videoCaptions: commonOptions.videoCaptions,
206 stopTime: commonOptions.stopTime
210 if (mode === 'p2p-media-loader') {
211 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
212 redundancyBaseUrls: options.p2pMediaLoader.redundancyBaseUrls,
213 type: 'application/x-mpegURL',
214 startTime: commonOptions.startTime,
215 src: p2pMediaLoaderOptions.playlistUrl
218 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
219 .filter(t => t.startsWith('ws'))
221 const p2pMediaLoaderConfig = {
224 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
225 rtcConfig: getRtcConfig(),
226 requiredSegmentsPriority: 5,
227 segmentUrlBuilder: segmentUrlBuilderFactory(options.p2pMediaLoader.redundancyBaseUrls)
230 swarmId: p2pMediaLoaderOptions.playlistUrl
233 const streamrootHls = {
234 levelLabelHandler: (level: { height: number, width: number }) => {
235 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
237 let label = file.resolution.label
238 if (file.fps >= 50) label += file.fps
244 liveSyncDurationCount: 7,
245 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
250 Object.assign(plugins, { p2pMediaLoader, streamrootHls })
251 html5 = streamrootHls.html5
254 if (mode === 'webtorrent') {
257 videoDuration: commonOptions.videoDuration,
258 playerElement: commonOptions.playerElement,
259 videoFiles: webtorrentOptions.videoFiles,
260 startTime: commonOptions.startTime
262 Object.assign(plugins, { webtorrent })
264 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
268 const videojsOptions = {
271 // We don't use text track settings for now
272 textTrackSettings: false,
273 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
274 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
276 muted: commonOptions.muted !== undefined
277 ? commonOptions.muted
278 : undefined, // Undefined so the player knows it has to check the local storage
280 poster: commonOptions.poster,
281 autoplay: autoplay === true ? 'any' : autoplay, // Use 'any' instead of true to get notifier by videojs if autoplay fails
282 inactivityTimeout: commonOptions.inactivityTimeout,
283 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
286 children: this.getControlBarChildren(mode, {
287 captions: commonOptions.captions,
288 peertubeLink: commonOptions.peertubeLink,
289 theaterMode: commonOptions.theaterMode
294 if (commonOptions.enableHotkeys === true) {
295 Object.assign(videojsOptions.plugins, {
297 enableVolumeScroll: false,
298 enableModifiersForNumbers: false,
300 fullscreenKey: function (event: KeyboardEvent) {
301 // fullscreen with the f key or Ctrl+Enter
302 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
305 seekStep: function (event: KeyboardEvent) {
306 // mimic VLC seek behavior, and default to 5 (original value is 5).
307 if (event.ctrlKey && event.altKey) {
309 } else if (event.ctrlKey) {
311 } else if (event.altKey) {
319 increasePlaybackRateKey: {
320 key: function (event: KeyboardEvent) {
321 return event.key === '>'
323 handler: function (player: videojs.Player) {
324 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
327 decreasePlaybackRateKey: {
328 key: function (event: KeyboardEvent) {
329 return event.key === '<'
331 handler: function (player: videojs.Player) {
332 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
336 key: function (event: KeyboardEvent) {
337 return event.key === '.'
339 handler: function (player: videojs.Player) {
341 // Calculate movement distance (assuming 30 fps)
343 player.currentTime(player.currentTime() + dist)
351 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
352 Object.assign(videojsOptions, { language: commonOptions.language })
355 return videojsOptions
358 private static getControlBarChildren (mode: PlayerMode, options: {
359 peertubeLink: boolean
360 theaterMode: boolean,
363 const settingEntries = []
364 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
367 settingEntries.push('playbackRateMenuButton')
368 if (options.captions === true) settingEntries.push('captionsButton')
369 settingEntries.push('resolutionMenuButton')
373 'currentTimeDisplay': {},
375 'durationDisplay': {},
378 'flexibleWidthSpacer': {},
383 [loadProgressBar]: {},
384 'mouseTimeDisplay': {},
385 'playProgressBar': {}
400 entries: settingEntries
404 if (options.peertubeLink === true) {
405 Object.assign(children, {
406 'peerTubeLinkButton': {}
410 if (options.theaterMode === true) {
411 Object.assign(children, {
416 Object.assign(children, {
417 'fullscreenToggle': {}
423 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
426 label: player.localize('Copy the video URL'),
427 listener: function () {
428 copyToClipboard(buildVideoLink())
432 label: player.localize('Copy the video URL at the current time'),
433 listener: function () {
434 const player = this as videojs.Player
435 copyToClipboard(buildVideoLink(player.currentTime()))
439 label: player.localize('Copy embed code'),
441 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
446 if (mode === 'webtorrent') {
448 label: player.localize('Copy magnet URI'),
449 listener: function () {
450 const player = this as videojs.Player
451 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
456 player.contextmenuUI({ content })
459 private static getLocalePath (serverUrl: string, locale: string) {
460 const completeLocale = getCompleteLocale(locale)
462 if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
464 return serverUrl + '/client/locales/' + completeLocale
468 // ############################################################################