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