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