adding shortcuts to videojs, adding frame-by-frame support
[oweals/peertube.git] / client / src / assets / player / peertube-player.ts
1 import { VideoFile } from '../../../../shared/models/videos'
2
3 import 'videojs-hotkeys'
4 import 'videojs-dock'
5 import 'videojs-contextmenu-ui'
6 import './peertube-link-button'
7 import './resolution-menu-button'
8 import './settings-menu-button'
9 import './webtorrent-info-button'
10 import './peertube-videojs-plugin'
11 import './peertube-load-progress-bar'
12 import './theater-button'
13 import { VideoJSCaption, videojsUntyped } from './peertube-videojs-typings'
14 import { buildVideoEmbed, buildVideoLink, copyToClipboard } from './utils'
15 import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n'
16
17 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
18 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
19 // Change Captions to Subtitles/CC
20 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
21 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
22 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
23
24 function getVideojsOptions (options: {
25   autoplay: boolean,
26   playerElement: HTMLVideoElement,
27   videoViewUrl: string,
28   videoDuration: number,
29   videoFiles: VideoFile[],
30   enableHotkeys: boolean,
31   inactivityTimeout: number,
32   peertubeLink: boolean,
33   poster: string,
34   startTime: number | string
35   theaterMode: boolean,
36   videoCaptions: VideoJSCaption[],
37   language?: string,
38   controls?: boolean,
39   muted?: boolean,
40   loop?: boolean
41 }) {
42   const videojsOptions = {
43     // We don't use text track settings for now
44     textTrackSettings: false,
45     controls: options.controls !== undefined ? options.controls : true,
46     muted: options.controls !== undefined ? options.muted : false,
47     loop: options.loop !== undefined ? options.loop : false,
48     poster: options.poster,
49     autoplay: false,
50     inactivityTimeout: options.inactivityTimeout,
51     playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
52     plugins: {
53       peertube: {
54         autoplay: options.autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
55         videoCaptions: options.videoCaptions,
56         videoFiles: options.videoFiles,
57         playerElement: options.playerElement,
58         videoViewUrl: options.videoViewUrl,
59         videoDuration: options.videoDuration,
60         startTime: options.startTime
61       }
62     },
63     controlBar: {
64       children: getControlBarChildren(options)
65     }
66   }
67
68   if (options.enableHotkeys === true) {
69     Object.assign(videojsOptions.plugins, {
70       hotkeys: {
71         enableVolumeScroll: false,
72         enableModifiersForNumbers: false,
73
74         fullscreenKey: function (event) {
75           // fullscreen with the f key or Ctrl+Enter
76           return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
77         },
78
79         seekStep: function (event) {
80           // mimic VLC seek behavior, and default to 5 (original value is 5).
81           if (event.ctrlKey && event.altKey) {
82             return 5 * 60
83           } else if (event.ctrlKey) {
84             return 60
85           } else if (event.altKey) {
86             return 10
87           } else {
88             return 5
89           }
90         },
91
92         customKeys: {
93           increasePlaybackRateKey: {
94             key: function (event) {
95               return event.key === '>'
96             },
97             handler: function (player) {
98               player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
99             }
100           },
101           decreasePlaybackRateKey: {
102             key: function (event) {
103               return event.key === '<'
104             },
105             handler: function (player) {
106               player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
107             }
108           },
109           frameByFrame: {
110             key: function (event) {
111               return event.key === '.'
112             },
113             handler: function (player, options, event) {
114               player.pause()
115               // Calculate movement distance (assuming 30 fps)
116               const dist = 1 / 30
117               player.currentTime(player.currentTime() + dist)
118             }
119           }
120         }
121       }
122     })
123   }
124
125   if (options.language && !isDefaultLocale(options.language)) {
126     Object.assign(videojsOptions, { language: options.language })
127   }
128
129   return videojsOptions
130 }
131
132 function getControlBarChildren (options: {
133   peertubeLink: boolean
134   theaterMode: boolean,
135   videoCaptions: VideoJSCaption[]
136 }) {
137   const settingEntries = []
138
139   // Keep an order
140   settingEntries.push('playbackRateMenuButton')
141   if (options.videoCaptions.length !== 0) settingEntries.push('captionsButton')
142   settingEntries.push('resolutionMenuButton')
143
144   const children = {
145     'playToggle': {},
146     'currentTimeDisplay': {},
147     'timeDivider': {},
148     'durationDisplay': {},
149     'liveDisplay': {},
150
151     'flexibleWidthSpacer': {},
152     'progressControl': {
153       children: {
154         'seekBar': {
155           children: {
156             'peerTubeLoadProgressBar': {},
157             'mouseTimeDisplay': {},
158             'playProgressBar': {}
159           }
160         }
161       }
162     },
163
164     'webTorrentButton': {},
165
166     'muteToggle': {},
167     'volumeControl': {},
168
169     'settingsButton': {
170       setup: {
171         maxHeightOffset: 40
172       },
173       entries: settingEntries
174     }
175   }
176
177   if (options.peertubeLink === true) {
178     Object.assign(children, {
179       'peerTubeLinkButton': {}
180     })
181   }
182
183   if (options.theaterMode === true) {
184     Object.assign(children, {
185       'theaterButton': {}
186     })
187   }
188
189   Object.assign(children, {
190     'fullscreenToggle': {}
191   })
192
193   return children
194 }
195
196 function addContextMenu (player: any, videoEmbedUrl: string) {
197   player.contextmenuUI({
198     content: [
199       {
200         label: player.localize('Copy the video URL'),
201         listener: function () {
202           copyToClipboard(buildVideoLink())
203         }
204       },
205       {
206         label: player.localize('Copy the video URL at the current time'),
207         listener: function () {
208           const player = this
209           copyToClipboard(buildVideoLink(player.currentTime()))
210         }
211       },
212       {
213         label: player.localize('Copy embed code'),
214         listener: () => {
215           copyToClipboard(buildVideoEmbed(videoEmbedUrl))
216         }
217       },
218       {
219         label: player.localize('Copy magnet URI'),
220         listener: function () {
221           const player = this
222           copyToClipboard(player.peertube().getCurrentVideoFile().magnetUri)
223         }
224       }
225     ]
226   })
227 }
228
229 function loadLocaleInVideoJS (serverUrl: string, videojs: any, locale: string) {
230   const path = getLocalePath(serverUrl, locale)
231   // It is the default locale, nothing to translate
232   if (!path) return Promise.resolve(undefined)
233
234   let p: Promise<any>
235
236   if (loadLocaleInVideoJS.cache[path]) {
237     p = Promise.resolve(loadLocaleInVideoJS.cache[path])
238   } else {
239     p = fetch(path + '/player.json')
240       .then(res => res.json())
241       .then(json => {
242         loadLocaleInVideoJS.cache[path] = json
243         return json
244       })
245   }
246
247   const completeLocale = getCompleteLocale(locale)
248   return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
249 }
250 namespace loadLocaleInVideoJS {
251   export const cache: { [ path: string ]: any } = {}
252 }
253
254 function getServerTranslations (serverUrl: string, locale: string) {
255   const path = getLocalePath(serverUrl, locale)
256   // It is the default locale, nothing to translate
257   if (!path) return Promise.resolve(undefined)
258
259   return fetch(path + '/server.json')
260     .then(res => res.json())
261 }
262
263 // ############################################################################
264
265 export {
266   getServerTranslations,
267   loadLocaleInVideoJS,
268   getVideojsOptions,
269   addContextMenu
270 }
271
272 // ############################################################################
273
274 function getLocalePath (serverUrl: string, locale: string) {
275   const completeLocale = getCompleteLocale(locale)
276
277   if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
278
279   return serverUrl + '/client/locales/' + completeLocale
280 }