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