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