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