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