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