]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
Refactor video links building
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
1 import 'videojs-hotkeys/videojs.hotkeys'
2 import 'videojs-dock'
3 import 'videojs-contextmenu-pt'
4 import 'videojs-contrib-quality-levels'
5 import './upnext/end-card'
6 import './upnext/upnext-plugin'
7 import './stats/stats-card'
8 import './stats/stats-plugin'
9 import './bezels/bezels-plugin'
10 import './peertube-plugin'
11 import './videojs-components/next-previous-video-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-link-button'
14 import './videojs-components/peertube-load-progress-bar'
15 import './videojs-components/resolution-menu-button'
16 import './videojs-components/resolution-menu-item'
17 import './videojs-components/settings-dialog'
18 import './videojs-components/settings-menu-button'
19 import './videojs-components/settings-menu-item'
20 import './videojs-components/settings-panel'
21 import './videojs-components/settings-panel-child'
22 import './videojs-components/theater-button'
23 import './playlist/playlist-plugin'
24 import videojs from 'video.js'
25 import { PluginsManager } from '@root-helpers/plugins-manager'
26 import { isDefaultLocale } from '@shared/core-utils/i18n'
27 import { VideoFile } from '@shared/models'
28 import { copyToClipboard } from '../../root-helpers/utils'
29 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
30 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
31 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
32 import { getStoredP2PEnabled } from './peertube-player-local-storage'
33 import {
34 NextPreviousVideoButtonOptions,
35 P2PMediaLoaderPluginOptions,
36 PeerTubeLinkButtonOptions,
37 PlaylistPluginOptions,
38 UserWatching,
39 VideoJSCaption,
40 VideoJSPluginOptions
41 } from './peertube-videojs-typings'
42 import { TranslationsManager } from './translations-manager'
43 import { buildVideoLink, buildVideoOrPlaylistEmbed, decorateVideoLink, getRtcConfig, isIOS, isSafari } from './utils'
44
45 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
46 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
47
48 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
49 // Change Captions to Subtitles/CC
50 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
51 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
52 CaptionsButton.prototype.label_ = ' '
53
54 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
55
56 export type WebtorrentOptions = {
57 videoFiles: VideoFile[]
58 }
59
60 export type P2PMediaLoaderOptions = {
61 playlistUrl: string
62 segmentsSha256Url: string
63 trackerAnnounce: string[]
64 redundancyBaseUrls: string[]
65 videoFiles: VideoFile[]
66 }
67
68 export interface CustomizationOptions {
69 startTime: number | string
70 stopTime: number | string
71
72 controls?: boolean
73 muted?: boolean
74 loop?: boolean
75 subtitle?: string
76 resume?: string
77
78 peertubeLink: boolean
79 }
80
81 export interface CommonOptions extends CustomizationOptions {
82 playerElement: HTMLVideoElement
83 onPlayerElementChange: (element: HTMLVideoElement) => void
84
85 autoplay: boolean
86
87 nextVideo?: () => void
88 hasNextVideo?: () => boolean
89
90 previousVideo?: () => void
91 hasPreviousVideo?: () => boolean
92
93 playlist?: PlaylistPluginOptions
94
95 videoDuration: number
96 enableHotkeys: boolean
97 inactivityTimeout: number
98 poster: string
99
100 theaterButton: boolean
101 captions: boolean
102
103 videoViewUrl: string
104 embedUrl: string
105 embedTitle: string
106
107 isLive: boolean
108
109 language?: string
110
111 videoCaptions: VideoJSCaption[]
112
113 videoUUID: string
114 videoShortUUID: string
115
116 userWatching?: UserWatching
117
118 serverUrl: string
119 }
120
121 export type PeertubePlayerManagerOptions = {
122 common: CommonOptions
123 webtorrent: WebtorrentOptions
124 p2pMediaLoader?: P2PMediaLoaderOptions
125
126 pluginsManager: PluginsManager
127 }
128
129 export class PeertubePlayerManager {
130 private static playerElementClassName: string
131 private static onPlayerChange: (player: videojs.Player) => void
132 private static alreadyPlayed = false
133 private static pluginsManager: PluginsManager
134
135 static initState () {
136 PeertubePlayerManager.alreadyPlayed = false
137 }
138
139 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
140 this.pluginsManager = options.pluginsManager
141
142 let p2pMediaLoader: any
143
144 this.onPlayerChange = onPlayerChange
145 this.playerElementClassName = options.common.playerElement.className
146
147 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
148 if (mode === 'p2p-media-loader') {
149 [ p2pMediaLoader ] = await Promise.all([
150 import('p2p-media-loader-hlsjs'),
151 import('./p2p-media-loader/p2p-media-loader-plugin')
152 ])
153 }
154
155 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
156
157 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
158
159 const self = this
160 return new Promise(res => {
161 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
162 const player = this
163
164 let alreadyFallback = false
165
166 player.tech(true).one('error', () => {
167 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
168 alreadyFallback = true
169 })
170
171 player.one('error', () => {
172 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
173 alreadyFallback = true
174 })
175
176 player.one('play', () => {
177 PeertubePlayerManager.alreadyPlayed = true
178 })
179
180 self.addContextMenu({
181 mode,
182 player,
183 videoShortUUID: options.common.videoShortUUID,
184 videoEmbedUrl: options.common.embedUrl,
185 videoEmbedTitle: options.common.embedTitle
186 })
187
188 player.bezels()
189 player.stats({
190 videoUUID: options.common.videoUUID,
191 videoIsLive: options.common.isLive,
192 mode
193 })
194
195 return res(player)
196 })
197 })
198 }
199
200 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
201 if (currentMode === 'webtorrent') return
202
203 console.log('Fallback to webtorrent.')
204
205 const newVideoElement = document.createElement('video')
206 newVideoElement.className = this.playerElementClassName
207
208 // VideoJS wraps our video element inside a div
209 let currentParentPlayerElement = options.common.playerElement.parentNode
210 // Fix on IOS, don't ask me why
211 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
212
213 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
214
215 options.common.playerElement = newVideoElement
216 options.common.onPlayerElementChange(newVideoElement)
217
218 player.dispose()
219
220 await import('./webtorrent/webtorrent-plugin')
221
222 const mode = 'webtorrent'
223 const videojsOptions = await this.getVideojsOptions(mode, options)
224
225 const self = this
226 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
227 const player = this
228
229 self.addContextMenu({
230 mode,
231 player,
232 videoShortUUID: options.common.videoShortUUID,
233 videoEmbedUrl: options.common.embedUrl,
234 videoEmbedTitle: options.common.embedTitle
235 })
236
237 PeertubePlayerManager.onPlayerChange(player)
238 })
239 }
240
241 private static async getVideojsOptions (
242 mode: PlayerMode,
243 options: PeertubePlayerManagerOptions,
244 p2pMediaLoaderModule?: any
245 ): Promise<videojs.PlayerOptions> {
246 const commonOptions = options.common
247 const isHLS = mode === 'p2p-media-loader'
248
249 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
250 const html5 = {
251 preloadTextTracks: false
252 }
253
254 const plugins: VideoJSPluginOptions = {
255 peertube: {
256 mode,
257 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
258 videoViewUrl: commonOptions.videoViewUrl,
259 videoDuration: commonOptions.videoDuration,
260 userWatching: commonOptions.userWatching,
261 subtitle: commonOptions.subtitle,
262 videoCaptions: commonOptions.videoCaptions,
263 stopTime: commonOptions.stopTime,
264 isLive: commonOptions.isLive,
265 videoUUID: commonOptions.videoUUID
266 }
267 }
268
269 if (commonOptions.playlist) {
270 plugins.playlist = commonOptions.playlist
271 }
272
273 if (commonOptions.enableHotkeys === true) {
274 PeertubePlayerManager.addHotkeysOptions(plugins)
275 }
276
277 if (isHLS) {
278 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
279
280 Object.assign(html5, hlsjs.html5)
281 }
282
283 if (mode === 'webtorrent') {
284 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
285
286 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
287 autoplay = false
288 }
289
290 const videojsOptions = {
291 html5,
292
293 // We don't use text track settings for now
294 textTrackSettings: false as any, // FIXME: typings
295 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
296 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
297
298 muted: commonOptions.muted !== undefined
299 ? commonOptions.muted
300 : undefined, // Undefined so the player knows it has to check the local storage
301
302 autoplay: this.getAutoPlayValue(autoplay),
303
304 poster: commonOptions.poster,
305 inactivityTimeout: commonOptions.inactivityTimeout,
306 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
307
308 plugins,
309
310 controlBar: {
311 children: this.getControlBarChildren(mode, {
312 videoShortUUID: commonOptions.videoShortUUID,
313
314 captions: commonOptions.captions,
315 peertubeLink: commonOptions.peertubeLink,
316 theaterButton: commonOptions.theaterButton,
317
318 nextVideo: commonOptions.nextVideo,
319 hasNextVideo: commonOptions.hasNextVideo,
320
321 previousVideo: commonOptions.previousVideo,
322 hasPreviousVideo: commonOptions.hasPreviousVideo
323 }) as any // FIXME: typings
324 }
325 }
326
327 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
328 Object.assign(videojsOptions, { language: commonOptions.language })
329 }
330
331 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
332 }
333
334 private static addP2PMediaLoaderOptions (
335 plugins: VideoJSPluginOptions,
336 options: PeertubePlayerManagerOptions,
337 p2pMediaLoaderModule: any
338 ) {
339 const p2pMediaLoaderOptions = options.p2pMediaLoader
340 const commonOptions = options.common
341
342 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
343 .filter(t => t.startsWith('ws'))
344
345 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
346
347 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
348 redundancyUrlManager,
349 type: 'application/x-mpegURL',
350 startTime: commonOptions.startTime,
351 src: p2pMediaLoaderOptions.playlistUrl
352 }
353
354 let consumeOnly = false
355 // FIXME: typings
356 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
357 console.log('We are on a cellular connection: disabling seeding.')
358 consumeOnly = true
359 }
360
361 const p2pMediaLoaderConfig = {
362 loader: {
363 trackerAnnounce,
364 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
365 rtcConfig: getRtcConfig(),
366 requiredSegmentsPriority: 1,
367 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
368 useP2P: getStoredP2PEnabled(),
369 consumeOnly
370 },
371 segments: {
372 swarmId: p2pMediaLoaderOptions.playlistUrl
373 }
374 }
375 const hlsjs = {
376 levelLabelHandler: (level: { height: number, width: number }) => {
377 const resolution = Math.min(level.height || 0, level.width || 0)
378
379 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
380 // We don't have files for live videos
381 if (!file) return level.height
382
383 let label = file.resolution.label
384 if (file.fps >= 50) label += file.fps
385
386 return label
387 },
388 html5: {
389 hlsjsConfig: {
390 capLevelToPlayerSize: true,
391 autoStartLoad: false,
392 liveSyncDurationCount: 5,
393 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
394 }
395 }
396 }
397
398 const toAssign = { p2pMediaLoader, hlsjs }
399 Object.assign(plugins, toAssign)
400
401 return toAssign
402 }
403
404 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
405 const commonOptions = options.common
406 const webtorrentOptions = options.webtorrent
407 const p2pMediaLoaderOptions = options.p2pMediaLoader
408
409 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
410 ? true
411 : false
412
413 const webtorrent = {
414 autoplay,
415 videoDuration: commonOptions.videoDuration,
416 playerElement: commonOptions.playerElement,
417 videoFiles: webtorrentOptions.videoFiles.length !== 0
418 ? webtorrentOptions.videoFiles
419 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
420 : p2pMediaLoaderOptions?.videoFiles || [],
421 startTime: commonOptions.startTime
422 }
423
424 Object.assign(plugins, { webtorrent })
425 }
426
427 private static getControlBarChildren (mode: PlayerMode, options: {
428 videoShortUUID: string
429
430 peertubeLink: boolean
431 theaterButton: boolean
432 captions: boolean
433
434 nextVideo?: Function
435 hasNextVideo?: () => boolean
436
437 previousVideo?: Function
438 hasPreviousVideo?: () => boolean
439 }) {
440 const settingEntries = []
441 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
442
443 // Keep an order
444 settingEntries.push('playbackRateMenuButton')
445 if (options.captions === true) settingEntries.push('captionsButton')
446 settingEntries.push('resolutionMenuButton')
447
448 const children = {}
449
450 if (options.previousVideo) {
451 const buttonOptions: NextPreviousVideoButtonOptions = {
452 type: 'previous',
453 handler: options.previousVideo,
454 isDisabled: () => {
455 if (!options.hasPreviousVideo) return false
456
457 return !options.hasPreviousVideo()
458 }
459 }
460
461 Object.assign(children, {
462 'previousVideoButton': buttonOptions
463 })
464 }
465
466 Object.assign(children, { playToggle: {} })
467
468 if (options.nextVideo) {
469 const buttonOptions: NextPreviousVideoButtonOptions = {
470 type: 'next',
471 handler: options.nextVideo,
472 isDisabled: () => {
473 if (!options.hasNextVideo) return false
474
475 return !options.hasNextVideo()
476 }
477 }
478
479 Object.assign(children, {
480 'nextVideoButton': buttonOptions
481 })
482 }
483
484 Object.assign(children, {
485 'currentTimeDisplay': {},
486 'timeDivider': {},
487 'durationDisplay': {},
488 'liveDisplay': {},
489
490 'flexibleWidthSpacer': {},
491 'progressControl': {
492 children: {
493 'seekBar': {
494 children: {
495 [loadProgressBar]: {},
496 'mouseTimeDisplay': {},
497 'playProgressBar': {}
498 }
499 }
500 }
501 },
502
503 'p2PInfoButton': {},
504
505 'muteToggle': {},
506 'volumeControl': {},
507
508 'settingsButton': {
509 setup: {
510 maxHeightOffset: 40
511 },
512 entries: settingEntries
513 }
514 })
515
516 if (options.peertubeLink === true) {
517 Object.assign(children, {
518 'peerTubeLinkButton': { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
519 })
520 }
521
522 if (options.theaterButton === true) {
523 Object.assign(children, {
524 'theaterButton': {}
525 })
526 }
527
528 Object.assign(children, {
529 'fullscreenToggle': {}
530 })
531
532 return children
533 }
534
535 private static addContextMenu (options: {
536 mode: PlayerMode
537 player: videojs.Player
538 videoShortUUID: string
539 videoEmbedUrl: string
540 videoEmbedTitle: string
541 }) {
542 const { mode, player, videoEmbedTitle, videoEmbedUrl, videoShortUUID } = options
543
544 const content = () => {
545 const isLoopEnabled = player.options_['loop']
546 const items = [
547 {
548 icon: 'repeat',
549 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
550 listener: function () {
551 player.options_['loop'] = !isLoopEnabled
552 }
553 },
554 {
555 label: player.localize('Copy the video URL'),
556 listener: function () {
557 copyToClipboard(buildVideoLink({ shortUUID: videoShortUUID }))
558 }
559 },
560 {
561 label: player.localize('Copy the video URL at the current time'),
562 listener: function (this: videojs.Player) {
563 const url = buildVideoLink({ shortUUID: videoShortUUID })
564
565 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
566 }
567 },
568 {
569 icon: 'code',
570 label: player.localize('Copy embed code'),
571 listener: () => {
572 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
573 }
574 }
575 ]
576
577 if (mode === 'webtorrent') {
578 items.push({
579 label: player.localize('Copy magnet URI'),
580 listener: function (this: videojs.Player) {
581 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
582 }
583 })
584 }
585
586 items.push({
587 icon: 'info',
588 label: player.localize('Stats for nerds'),
589 listener: () => {
590 player.stats().show()
591 }
592 })
593
594 return items.map(i => ({
595 ...i,
596 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
597 }))
598 }
599
600 // adding the menu
601 player.contextmenuUI({ content })
602 }
603
604 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
605 const isNaked = (event: KeyboardEvent, key: string) =>
606 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
607
608 Object.assign(plugins, {
609 hotkeys: {
610 skipInitialFocus: true,
611 enableInactiveFocus: false,
612 captureDocumentHotkeys: true,
613 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
614 const tagName = e.tagName.toLowerCase()
615 return e.id === 'content' || tagName === 'body' || tagName === 'video'
616 },
617
618 enableVolumeScroll: false,
619 enableModifiersForNumbers: false,
620
621 rewindKey: function (event: KeyboardEvent) {
622 return isNaked(event, 'ArrowLeft')
623 },
624
625 forwardKey: function (event: KeyboardEvent) {
626 return isNaked(event, 'ArrowRight')
627 },
628
629 fullscreenKey: function (event: KeyboardEvent) {
630 // fullscreen with the f key or Ctrl+Enter
631 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
632 },
633
634 customKeys: {
635 increasePlaybackRateKey: {
636 key: function (event: KeyboardEvent) {
637 return isNaked(event, '>')
638 },
639 handler: function (player: videojs.Player) {
640 const newValue = Math.min(player.playbackRate() + 0.1, 5)
641 player.playbackRate(parseFloat(newValue.toFixed(2)))
642 }
643 },
644 decreasePlaybackRateKey: {
645 key: function (event: KeyboardEvent) {
646 return isNaked(event, '<')
647 },
648 handler: function (player: videojs.Player) {
649 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
650 player.playbackRate(parseFloat(newValue.toFixed(2)))
651 }
652 },
653 frameByFrame: {
654 key: function (event: KeyboardEvent) {
655 return isNaked(event, '.')
656 },
657 handler: function (player: videojs.Player) {
658 player.pause()
659 // Calculate movement distance (assuming 30 fps)
660 const dist = 1 / 30
661 player.currentTime(player.currentTime() + dist)
662 }
663 }
664 }
665 }
666 })
667 }
668
669 private static getAutoPlayValue (autoplay: any) {
670 if (autoplay !== true) return autoplay
671
672 // On first play, disable autoplay to avoid issues
673 // But if the player already played videos, we can safely autoplay next ones
674 if (isIOS() || isSafari()) {
675 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
676 }
677
678 return 'play'
679 }
680 }
681
682 // ############################################################################
683
684 export {
685 videojs
686 }