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