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