]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
Add lazy loading in player
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
1 import { VideoFile } from '../../../../shared/models/videos'
2 // @ts-ignore
3 import * as videojs from 'video.js'
4 import 'videojs-hotkeys'
5 import 'videojs-dock'
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
19 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
20 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
21 // Change Captions to Subtitles/CC
22 videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC'
23 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
24 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
25
26 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
27
28 export type WebtorrentOptions = {
29 videoFiles: VideoFile[]
30 }
31
32 export type P2PMediaLoaderOptions = {
33 playlistUrl: string
34 trackerAnnounce: string[]
35 }
36
37 export type CommonOptions = {
38 playerElement: HTMLVideoElement
39
40 autoplay: boolean
41 videoDuration: number
42 enableHotkeys: boolean
43 inactivityTimeout: number
44 poster: string
45 startTime: number | string
46
47 theaterMode: boolean
48 captions: boolean
49 peertubeLink: boolean
50
51 videoViewUrl: string
52 embedUrl: string
53
54 language?: string
55 controls?: boolean
56 muted?: boolean
57 loop?: boolean
58 subtitle?: string
59
60 videoCaptions: VideoJSCaption[]
61
62 userWatching?: UserWatching
63
64 serverUrl: string
65 }
66
67 export type PeertubePlayerManagerOptions = {
68 common: CommonOptions,
69 webtorrent?: WebtorrentOptions,
70 p2pMediaLoader?: P2PMediaLoaderOptions
71 }
72
73 export class PeertubePlayerManager {
74
75 private static videojsLocaleCache: { [ path: string ]: any } = {}
76
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)
81
82 return fetch(path + '/server.json')
83 .then(res => res.json())
84 .catch(err => {
85 console.error('Cannot get server translations', err)
86 return undefined
87 })
88 }
89
90 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
91 let p2pMediaLoader: any
92
93 if (mode === 'webtorrent') await import('./webtorrent-plugin')
94 if (mode === 'p2p-media-loader') {
95 [ p2pMediaLoader ] = await Promise.all([
96 import('p2p-media-loader-hlsjs'),
97 import('./p2p-media-loader-plugin')
98 ])
99 }
100
101 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
102
103 await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language)
104
105 const self = this
106 return new Promise(res => {
107 videojs(options.common.playerElement, videojsOptions, function (this: any) {
108 const player = this
109
110 self.addContextMenu(mode, player, options.common.embedUrl)
111
112 return res(player)
113 })
114 })
115 }
116
117 private static loadLocaleInVideoJS (serverUrl: string, locale: string) {
118 const path = PeertubePlayerManager.getLocalePath(serverUrl, locale)
119 // It is the default locale, nothing to translate
120 if (!path) return Promise.resolve(undefined)
121
122 let p: Promise<any>
123
124 if (PeertubePlayerManager.videojsLocaleCache[path]) {
125 p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path])
126 } else {
127 p = fetch(path + '/player.json')
128 .then(res => res.json())
129 .then(json => {
130 PeertubePlayerManager.videojsLocaleCache[path] = json
131 return json
132 })
133 .catch(err => {
134 console.error('Cannot get player translations', err)
135 return undefined
136 })
137 }
138
139 const completeLocale = getCompleteLocale(locale)
140 return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
141 }
142
143 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
144 const commonOptions = options.common
145 const webtorrentOptions = options.webtorrent
146 const p2pMediaLoaderOptions = options.p2pMediaLoader
147 let html5 = {}
148
149 const plugins: VideoJSPluginOptions = {
150 peertube: {
151 autoplay: commonOptions.autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
152 videoViewUrl: commonOptions.videoViewUrl,
153 videoDuration: commonOptions.videoDuration,
154 startTime: commonOptions.startTime,
155 userWatching: commonOptions.userWatching,
156 subtitle: commonOptions.subtitle,
157 videoCaptions: commonOptions.videoCaptions
158 }
159 }
160
161 if (p2pMediaLoaderOptions) {
162 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
163 type: 'application/x-mpegURL',
164 src: p2pMediaLoaderOptions.playlistUrl
165 }
166
167 const p2pMediaLoaderConfig = {
168 // loader: {
169 // trackerAnnounce: p2pMediaLoaderOptions.trackerAnnounce
170 // },
171 segments: {
172 swarmId: p2pMediaLoaderOptions.playlistUrl
173 }
174 }
175 const streamrootHls = {
176 html5: {
177 hlsjsConfig: {
178 liveSyncDurationCount: 7,
179 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
180 }
181 }
182 }
183
184 Object.assign(plugins, { p2pMediaLoader, streamrootHls })
185 html5 = streamrootHls.html5
186 }
187
188 if (webtorrentOptions) {
189 const webtorrent = {
190 autoplay: commonOptions.autoplay,
191 videoDuration: commonOptions.videoDuration,
192 playerElement: commonOptions.playerElement,
193 videoFiles: webtorrentOptions.videoFiles
194 }
195 Object.assign(plugins, { webtorrent })
196 }
197
198 const videojsOptions = {
199 html5,
200
201 // We don't use text track settings for now
202 textTrackSettings: false,
203 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
204 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
205
206 muted: commonOptions.muted !== undefined
207 ? commonOptions.muted
208 : undefined, // Undefined so the player knows it has to check the local storage
209
210 poster: commonOptions.poster,
211 autoplay: false,
212 inactivityTimeout: commonOptions.inactivityTimeout,
213 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
214 plugins,
215 controlBar: {
216 children: this.getControlBarChildren(mode, {
217 captions: commonOptions.captions,
218 peertubeLink: commonOptions.peertubeLink,
219 theaterMode: commonOptions.theaterMode
220 })
221 }
222 }
223
224 if (commonOptions.enableHotkeys === true) {
225 Object.assign(videojsOptions.plugins, {
226 hotkeys: {
227 enableVolumeScroll: false,
228 enableModifiersForNumbers: false,
229
230 fullscreenKey: function (event: KeyboardEvent) {
231 // fullscreen with the f key or Ctrl+Enter
232 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
233 },
234
235 seekStep: function (event: KeyboardEvent) {
236 // mimic VLC seek behavior, and default to 5 (original value is 5).
237 if (event.ctrlKey && event.altKey) {
238 return 5 * 60
239 } else if (event.ctrlKey) {
240 return 60
241 } else if (event.altKey) {
242 return 10
243 } else {
244 return 5
245 }
246 },
247
248 customKeys: {
249 increasePlaybackRateKey: {
250 key: function (event: KeyboardEvent) {
251 return event.key === '>'
252 },
253 handler: function (player: videojs.Player) {
254 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
255 }
256 },
257 decreasePlaybackRateKey: {
258 key: function (event: KeyboardEvent) {
259 return event.key === '<'
260 },
261 handler: function (player: videojs.Player) {
262 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
263 }
264 },
265 frameByFrame: {
266 key: function (event: KeyboardEvent) {
267 return event.key === '.'
268 },
269 handler: function (player: videojs.Player) {
270 player.pause()
271 // Calculate movement distance (assuming 30 fps)
272 const dist = 1 / 30
273 player.currentTime(player.currentTime() + dist)
274 }
275 }
276 }
277 }
278 })
279 }
280
281 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
282 Object.assign(videojsOptions, { language: commonOptions.language })
283 }
284
285 return videojsOptions
286 }
287
288 private static getControlBarChildren (mode: PlayerMode, options: {
289 peertubeLink: boolean
290 theaterMode: boolean,
291 captions: boolean
292 }) {
293 const settingEntries = []
294 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
295
296 // Keep an order
297 settingEntries.push('playbackRateMenuButton')
298 if (options.captions === true) settingEntries.push('captionsButton')
299 settingEntries.push('resolutionMenuButton')
300
301 const children = {
302 'playToggle': {},
303 'currentTimeDisplay': {},
304 'timeDivider': {},
305 'durationDisplay': {},
306 'liveDisplay': {},
307
308 'flexibleWidthSpacer': {},
309 'progressControl': {
310 children: {
311 'seekBar': {
312 children: {
313 [loadProgressBar]: {},
314 'mouseTimeDisplay': {},
315 'playProgressBar': {}
316 }
317 }
318 }
319 },
320
321 'p2PInfoButton': {},
322
323 'muteToggle': {},
324 'volumeControl': {},
325
326 'settingsButton': {
327 setup: {
328 maxHeightOffset: 40
329 },
330 entries: settingEntries
331 }
332 }
333
334 if (options.peertubeLink === true) {
335 Object.assign(children, {
336 'peerTubeLinkButton': {}
337 })
338 }
339
340 if (options.theaterMode === true) {
341 Object.assign(children, {
342 'theaterButton': {}
343 })
344 }
345
346 Object.assign(children, {
347 'fullscreenToggle': {}
348 })
349
350 return children
351 }
352
353 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
354 const content = [
355 {
356 label: player.localize('Copy the video URL'),
357 listener: function () {
358 copyToClipboard(buildVideoLink())
359 }
360 },
361 {
362 label: player.localize('Copy the video URL at the current time'),
363 listener: function () {
364 const player = this as videojs.Player
365 copyToClipboard(buildVideoLink(player.currentTime()))
366 }
367 },
368 {
369 label: player.localize('Copy embed code'),
370 listener: () => {
371 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
372 }
373 }
374 ]
375
376 if (mode === 'webtorrent') {
377 content.push({
378 label: player.localize('Copy magnet URI'),
379 listener: function () {
380 const player = this as videojs.Player
381 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
382 }
383 })
384 }
385
386 player.contextmenuUI({ content })
387 }
388
389 private static getLocalePath (serverUrl: string, locale: string) {
390 const completeLocale = getCompleteLocale(locale)
391
392 if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
393
394 return serverUrl + '/client/locales/' + completeLocale
395 }
396 }
397
398 // ############################################################################
399
400 export {
401 videojs
402 }