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