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