]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-player-manager.ts
Add japanese support
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
CommitLineData
2adfc7ea
C
1import { VideoFile } from '../../../../shared/models/videos'
2// @ts-ignore
3import * as videojs from 'video.js'
4import 'videojs-hotkeys'
5import 'videojs-dock'
6import 'videojs-contextmenu-ui'
7import 'videojs-contrib-quality-levels'
8import './peertube-plugin'
9import './videojs-components/peertube-link-button'
10import './videojs-components/resolution-menu-button'
11import './videojs-components/settings-menu-button'
12import './videojs-components/p2p-info-button'
13import './videojs-components/peertube-load-progress-bar'
14import './videojs-components/theater-button'
15import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings'
09209296 16import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils'
2adfc7ea 17import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n'
09209296
C
18import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
19import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
2adfc7ea
C
20
21// Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
22videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
23// Change Captions to Subtitles/CC
24videojsUntyped.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)
26videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
27
3b6f205c 28export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
2adfc7ea 29
3b6f205c 30export type WebtorrentOptions = {
2adfc7ea
C
31 videoFiles: VideoFile[]
32}
33
3b6f205c 34export type P2PMediaLoaderOptions = {
2adfc7ea 35 playlistUrl: string
09209296 36 segmentsSha256Url: string
4348a27d 37 trackerAnnounce: string[]
09209296
C
38 redundancyBaseUrls: string[]
39 videoFiles: VideoFile[]
2adfc7ea
C
40}
41
3b6f205c 42export type CommonOptions = {
2adfc7ea 43 playerElement: HTMLVideoElement
6ec0b75b 44 onPlayerElementChange: (element: HTMLVideoElement) => void
2adfc7ea
C
45
46 autoplay: boolean
47 videoDuration: number
48 enableHotkeys: boolean
49 inactivityTimeout: number
50 poster: string
51 startTime: number | string
f0a39880 52 stopTime: number | string
2adfc7ea
C
53
54 theaterMode: boolean
55 captions: boolean
56 peertubeLink: boolean
57
58 videoViewUrl: string
59 embedUrl: string
60
61 language?: string
62 controls?: boolean
63 muted?: boolean
64 loop?: boolean
65 subtitle?: string
66
67 videoCaptions: VideoJSCaption[]
68
69 userWatching?: UserWatching
70
71 serverUrl: string
72}
73
74export type PeertubePlayerManagerOptions = {
75 common: CommonOptions,
6ec0b75b 76 webtorrent: WebtorrentOptions,
2adfc7ea
C
77 p2pMediaLoader?: P2PMediaLoaderOptions
78}
79
80export class PeertubePlayerManager {
81
82 private static videojsLocaleCache: { [ path: string ]: any } = {}
6ec0b75b 83 private static playerElementClassName: string
2adfc7ea
C
84
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)
89
90 return fetch(path + '/server.json')
91 .then(res => res.json())
92 .catch(err => {
93 console.error('Cannot get server translations', err)
94 return undefined
95 })
96 }
97
98 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) {
4348a27d
C
99 let p2pMediaLoader: any
100
6ec0b75b
C
101 this.playerElementClassName = options.common.playerElement.className
102
09209296 103 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
4348a27d
C
104 if (mode === 'p2p-media-loader') {
105 [ p2pMediaLoader ] = await Promise.all([
106 import('p2p-media-loader-hlsjs'),
09209296 107 import('./p2p-media-loader/p2p-media-loader-plugin')
4348a27d
C
108 ])
109 }
2adfc7ea 110
4348a27d 111 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
2adfc7ea
C
112
113 await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language)
114
115 const self = this
116 return new Promise(res => {
117 videojs(options.common.playerElement, videojsOptions, function (this: any) {
118 const player = this
119
96cb4527
C
120 player.tech_.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options))
121 player.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options))
6ec0b75b 122
2adfc7ea
C
123 self.addContextMenu(mode, player, options.common.embedUrl)
124
125 return res(player)
126 })
127 })
128 }
129
96cb4527
C
130 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
131 if (currentMode === 'webtorrent') return
132
133 console.log('Fallback to webtorrent.')
134
6ec0b75b
C
135 const newVideoElement = document.createElement('video')
136 newVideoElement.className = this.playerElementClassName
137
138 // VideoJS wraps our video element inside a div
96cb4527
C
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
142
6ec0b75b
C
143 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
144
145 options.common.playerElement = newVideoElement
146 options.common.onPlayerElementChange(newVideoElement)
147
148 player.dispose()
149
150 await import('./webtorrent/webtorrent-plugin')
151
152 const mode = 'webtorrent'
153 const videojsOptions = this.getVideojsOptions(mode, options)
154
155 const self = this
156 videojs(newVideoElement, videojsOptions, function (this: any) {
157 const player = this
158
159 self.addContextMenu(mode, player, options.common.embedUrl)
160 })
161 }
162
2adfc7ea
C
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)
167
168 let p: Promise<any>
169
170 if (PeertubePlayerManager.videojsLocaleCache[path]) {
171 p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path])
172 } else {
173 p = fetch(path + '/player.json')
174 .then(res => res.json())
175 .then(json => {
176 PeertubePlayerManager.videojsLocaleCache[path] = json
177 return json
178 })
179 .catch(err => {
180 console.error('Cannot get player translations', err)
181 return undefined
182 })
183 }
184
185 const completeLocale = getCompleteLocale(locale)
186 return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json))
187 }
188
4348a27d 189 private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
2adfc7ea
C
190 const commonOptions = options.common
191 const webtorrentOptions = options.webtorrent
192 const p2pMediaLoaderOptions = options.p2pMediaLoader
09209296
C
193
194 let autoplay = options.common.autoplay
3b6f205c 195 let html5 = {}
2adfc7ea
C
196
197 const plugins: VideoJSPluginOptions = {
198 peertube: {
09209296
C
199 mode,
200 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
2adfc7ea
C
201 videoViewUrl: commonOptions.videoViewUrl,
202 videoDuration: commonOptions.videoDuration,
2adfc7ea
C
203 userWatching: commonOptions.userWatching,
204 subtitle: commonOptions.subtitle,
f0a39880
C
205 videoCaptions: commonOptions.videoCaptions,
206 stopTime: commonOptions.stopTime
2adfc7ea
C
207 }
208 }
209
6ec0b75b 210 if (mode === 'p2p-media-loader') {
2adfc7ea 211 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
09209296 212 redundancyBaseUrls: options.p2pMediaLoader.redundancyBaseUrls,
2adfc7ea 213 type: 'application/x-mpegURL',
f0a39880 214 startTime: commonOptions.startTime,
2adfc7ea
C
215 src: p2pMediaLoaderOptions.playlistUrl
216 }
217
09209296
C
218 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
219 .filter(t => t.startsWith('ws'))
220
4348a27d 221 const p2pMediaLoaderConfig = {
09209296
C
222 loader: {
223 trackerAnnounce,
224 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
225 rtcConfig: getRtcConfig(),
226 requiredSegmentsPriority: 5,
227 segmentUrlBuilder: segmentUrlBuilderFactory(options.p2pMediaLoader.redundancyBaseUrls)
228 },
2adfc7ea 229 segments: {
4348a27d 230 swarmId: p2pMediaLoaderOptions.playlistUrl
2adfc7ea
C
231 }
232 }
233 const streamrootHls = {
09209296
C
234 levelLabelHandler: (level: { height: number, width: number }) => {
235 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
236
237 let label = file.resolution.label
238 if (file.fps >= 50) label += file.fps
239
240 return label
241 },
2adfc7ea
C
242 html5: {
243 hlsjsConfig: {
244 liveSyncDurationCount: 7,
4348a27d 245 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
2adfc7ea
C
246 }
247 }
248 }
249
250 Object.assign(plugins, { p2pMediaLoader, streamrootHls })
3b6f205c 251 html5 = streamrootHls.html5
2adfc7ea
C
252 }
253
6ec0b75b 254 if (mode === 'webtorrent') {
2adfc7ea 255 const webtorrent = {
09209296 256 autoplay,
2adfc7ea
C
257 videoDuration: commonOptions.videoDuration,
258 playerElement: commonOptions.playerElement,
f0a39880
C
259 videoFiles: webtorrentOptions.videoFiles,
260 startTime: commonOptions.startTime
2adfc7ea
C
261 }
262 Object.assign(plugins, { webtorrent })
09209296
C
263
264 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
265 autoplay = false
2adfc7ea
C
266 }
267
268 const videojsOptions = {
3b6f205c
C
269 html5,
270
2adfc7ea
C
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,
275
276 muted: commonOptions.muted !== undefined
277 ? commonOptions.muted
278 : undefined, // Undefined so the player knows it has to check the local storage
279
280 poster: commonOptions.poster,
6ec0b75b 281 autoplay: autoplay === true ? 'any' : autoplay, // Use 'any' instead of true to get notifier by videojs if autoplay fails
2adfc7ea
C
282 inactivityTimeout: commonOptions.inactivityTimeout,
283 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
284 plugins,
285 controlBar: {
286 children: this.getControlBarChildren(mode, {
287 captions: commonOptions.captions,
288 peertubeLink: commonOptions.peertubeLink,
289 theaterMode: commonOptions.theaterMode
290 })
291 }
292 }
293
294 if (commonOptions.enableHotkeys === true) {
295 Object.assign(videojsOptions.plugins, {
296 hotkeys: {
297 enableVolumeScroll: false,
298 enableModifiersForNumbers: false,
299
300 fullscreenKey: function (event: KeyboardEvent) {
301 // fullscreen with the f key or Ctrl+Enter
302 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
303 },
304
305 seekStep: function (event: KeyboardEvent) {
306 // mimic VLC seek behavior, and default to 5 (original value is 5).
307 if (event.ctrlKey && event.altKey) {
308 return 5 * 60
309 } else if (event.ctrlKey) {
310 return 60
311 } else if (event.altKey) {
312 return 10
313 } else {
314 return 5
315 }
316 },
317
318 customKeys: {
319 increasePlaybackRateKey: {
320 key: function (event: KeyboardEvent) {
321 return event.key === '>'
322 },
323 handler: function (player: videojs.Player) {
324 player.playbackRate((player.playbackRate() + 0.1).toFixed(2))
325 }
326 },
327 decreasePlaybackRateKey: {
328 key: function (event: KeyboardEvent) {
329 return event.key === '<'
330 },
331 handler: function (player: videojs.Player) {
332 player.playbackRate((player.playbackRate() - 0.1).toFixed(2))
333 }
334 },
335 frameByFrame: {
336 key: function (event: KeyboardEvent) {
337 return event.key === '.'
338 },
339 handler: function (player: videojs.Player) {
340 player.pause()
341 // Calculate movement distance (assuming 30 fps)
342 const dist = 1 / 30
343 player.currentTime(player.currentTime() + dist)
344 }
345 }
346 }
347 }
348 })
349 }
350
351 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
352 Object.assign(videojsOptions, { language: commonOptions.language })
353 }
354
355 return videojsOptions
356 }
357
358 private static getControlBarChildren (mode: PlayerMode, options: {
359 peertubeLink: boolean
360 theaterMode: boolean,
361 captions: boolean
362 }) {
363 const settingEntries = []
364 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
365
366 // Keep an order
367 settingEntries.push('playbackRateMenuButton')
368 if (options.captions === true) settingEntries.push('captionsButton')
369 settingEntries.push('resolutionMenuButton')
370
371 const children = {
372 'playToggle': {},
373 'currentTimeDisplay': {},
374 'timeDivider': {},
375 'durationDisplay': {},
376 'liveDisplay': {},
377
378 'flexibleWidthSpacer': {},
379 'progressControl': {
380 children: {
381 'seekBar': {
382 children: {
383 [loadProgressBar]: {},
384 'mouseTimeDisplay': {},
385 'playProgressBar': {}
386 }
387 }
388 }
389 },
390
391 'p2PInfoButton': {},
392
393 'muteToggle': {},
394 'volumeControl': {},
395
396 'settingsButton': {
397 setup: {
398 maxHeightOffset: 40
399 },
400 entries: settingEntries
401 }
402 }
403
404 if (options.peertubeLink === true) {
405 Object.assign(children, {
406 'peerTubeLinkButton': {}
407 })
408 }
409
410 if (options.theaterMode === true) {
411 Object.assign(children, {
412 'theaterButton': {}
413 })
414 }
415
416 Object.assign(children, {
417 'fullscreenToggle': {}
418 })
419
420 return children
421 }
422
423 private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) {
424 const content = [
425 {
426 label: player.localize('Copy the video URL'),
427 listener: function () {
428 copyToClipboard(buildVideoLink())
429 }
430 },
431 {
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()))
436 }
437 },
438 {
439 label: player.localize('Copy embed code'),
440 listener: () => {
441 copyToClipboard(buildVideoEmbed(videoEmbedUrl))
442 }
443 }
444 ]
445
446 if (mode === 'webtorrent') {
447 content.push({
448 label: player.localize('Copy magnet URI'),
449 listener: function () {
450 const player = this as videojs.Player
451 copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri)
452 }
453 })
454 }
455
456 player.contextmenuUI({ content })
457 }
458
459 private static getLocalePath (serverUrl: string, locale: string) {
460 const completeLocale = getCompleteLocale(locale)
461
462 if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined
463
464 return serverUrl + '/client/locales/' + completeLocale
465 }
466}
467
468// ############################################################################
469
470export {
471 videojs
472}