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