]>
Commit | Line | Data |
---|---|---|
1 | import { VideoFile } from '../../../../shared/models/videos' | |
2 | import videojs from 'video.js' | |
3 | import 'videojs-hotkeys/videojs.hotkeys' | |
4 | import 'videojs-dock' | |
5 | import 'videojs-contextmenu-ui' | |
6 | import 'videojs-contrib-quality-levels' | |
7 | import './upnext/end-card' | |
8 | import './upnext/upnext-plugin' | |
9 | import './bezels/bezels-plugin' | |
10 | import './peertube-plugin' | |
11 | import './videojs-components/next-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 { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings' | |
24 | import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils' | |
25 | import { isDefaultLocale } from '../../../../shared/models/i18n/i18n' | |
26 | import { segmentValidatorFactory } from './p2p-media-loader/segment-validator' | |
27 | import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder' | |
28 | import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager' | |
29 | import { getStoredP2PEnabled } from './peertube-player-local-storage' | |
30 | import { TranslationsManager } from './translations-manager' | |
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 = 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: autoplay === true | |
236 | ? 'play' // Use 'any' instead of true to get notifier by videojs if autoplay fails | |
237 | : autoplay, | |
238 | ||
239 | poster: commonOptions.poster, | |
240 | inactivityTimeout: commonOptions.inactivityTimeout, | |
241 | playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ], | |
242 | ||
243 | plugins, | |
244 | ||
245 | controlBar: { | |
246 | children: this.getControlBarChildren(mode, { | |
247 | captions: commonOptions.captions, | |
248 | peertubeLink: commonOptions.peertubeLink, | |
249 | theaterButton: commonOptions.theaterButton, | |
250 | nextVideo: commonOptions.nextVideo | |
251 | }) as any // FIXME: typings | |
252 | } | |
253 | } | |
254 | ||
255 | if (commonOptions.language && !isDefaultLocale(commonOptions.language)) { | |
256 | Object.assign(videojsOptions, { language: commonOptions.language }) | |
257 | } | |
258 | ||
259 | return videojsOptions | |
260 | } | |
261 | ||
262 | private static addP2PMediaLoaderOptions ( | |
263 | plugins: VideoJSPluginOptions, | |
264 | options: PeertubePlayerManagerOptions, | |
265 | p2pMediaLoaderModule: any | |
266 | ) { | |
267 | const p2pMediaLoaderOptions = options.p2pMediaLoader | |
268 | const commonOptions = options.common | |
269 | ||
270 | const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce | |
271 | .filter(t => t.startsWith('ws')) | |
272 | ||
273 | const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls) | |
274 | ||
275 | const p2pMediaLoader: P2PMediaLoaderPluginOptions = { | |
276 | redundancyUrlManager, | |
277 | type: 'application/x-mpegURL', | |
278 | startTime: commonOptions.startTime, | |
279 | src: p2pMediaLoaderOptions.playlistUrl | |
280 | } | |
281 | ||
282 | let consumeOnly = false | |
283 | // FIXME: typings | |
284 | if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') { | |
285 | console.log('We are on a cellular connection: disabling seeding.') | |
286 | consumeOnly = true | |
287 | } | |
288 | ||
289 | const p2pMediaLoaderConfig = { | |
290 | loader: { | |
291 | trackerAnnounce, | |
292 | segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url), | |
293 | rtcConfig: getRtcConfig(), | |
294 | requiredSegmentsPriority: 5, | |
295 | segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager), | |
296 | useP2P: getStoredP2PEnabled(), | |
297 | consumeOnly | |
298 | }, | |
299 | segments: { | |
300 | swarmId: p2pMediaLoaderOptions.playlistUrl | |
301 | } | |
302 | } | |
303 | const hlsjs = { | |
304 | levelLabelHandler: (level: { height: number, width: number }) => { | |
305 | const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height) | |
306 | ||
307 | let label = file.resolution.label | |
308 | if (file.fps >= 50) label += file.fps | |
309 | ||
310 | return label | |
311 | }, | |
312 | html5: { | |
313 | hlsjsConfig: { | |
314 | capLevelToPlayerSize: true, | |
315 | autoStartLoad: false, | |
316 | liveSyncDurationCount: 7, | |
317 | loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass() | |
318 | } | |
319 | } | |
320 | } | |
321 | ||
322 | const toAssign = { p2pMediaLoader, hlsjs } | |
323 | Object.assign(plugins, toAssign) | |
324 | ||
325 | return toAssign | |
326 | } | |
327 | ||
328 | private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) { | |
329 | const commonOptions = options.common | |
330 | const webtorrentOptions = options.webtorrent | |
331 | ||
332 | const webtorrent = { | |
333 | autoplay: commonOptions.autoplay, | |
334 | videoDuration: commonOptions.videoDuration, | |
335 | playerElement: commonOptions.playerElement, | |
336 | videoFiles: webtorrentOptions.videoFiles, | |
337 | startTime: commonOptions.startTime | |
338 | } | |
339 | ||
340 | Object.assign(plugins, { webtorrent }) | |
341 | } | |
342 | ||
343 | private static getControlBarChildren (mode: PlayerMode, options: { | |
344 | peertubeLink: boolean | |
345 | theaterButton: boolean, | |
346 | captions: boolean, | |
347 | nextVideo?: Function | |
348 | }) { | |
349 | const settingEntries = [] | |
350 | const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar' | |
351 | ||
352 | // Keep an order | |
353 | settingEntries.push('playbackRateMenuButton') | |
354 | if (options.captions === true) settingEntries.push('captionsButton') | |
355 | settingEntries.push('resolutionMenuButton') | |
356 | ||
357 | const children = { | |
358 | 'playToggle': {} | |
359 | } | |
360 | ||
361 | if (options.nextVideo) { | |
362 | Object.assign(children, { | |
363 | 'nextVideoButton': { | |
364 | handler: options.nextVideo | |
365 | } | |
366 | }) | |
367 | } | |
368 | ||
369 | Object.assign(children, { | |
370 | 'currentTimeDisplay': {}, | |
371 | 'timeDivider': {}, | |
372 | 'durationDisplay': {}, | |
373 | 'liveDisplay': {}, | |
374 | ||
375 | 'flexibleWidthSpacer': {}, | |
376 | 'progressControl': { | |
377 | children: { | |
378 | 'seekBar': { | |
379 | children: { | |
380 | [loadProgressBar]: {}, | |
381 | 'mouseTimeDisplay': {}, | |
382 | 'playProgressBar': {} | |
383 | } | |
384 | } | |
385 | } | |
386 | }, | |
387 | ||
388 | 'p2PInfoButton': {}, | |
389 | ||
390 | 'muteToggle': {}, | |
391 | 'volumeControl': {}, | |
392 | ||
393 | 'settingsButton': { | |
394 | setup: { | |
395 | maxHeightOffset: 40 | |
396 | }, | |
397 | entries: settingEntries | |
398 | } | |
399 | }) | |
400 | ||
401 | if (options.peertubeLink === true) { | |
402 | Object.assign(children, { | |
403 | 'peerTubeLinkButton': {} | |
404 | }) | |
405 | } | |
406 | ||
407 | if (options.theaterButton === true) { | |
408 | Object.assign(children, { | |
409 | 'theaterButton': {} | |
410 | }) | |
411 | } | |
412 | ||
413 | Object.assign(children, { | |
414 | 'fullscreenToggle': {} | |
415 | }) | |
416 | ||
417 | return children | |
418 | } | |
419 | ||
420 | private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) { | |
421 | const content = [ | |
422 | { | |
423 | label: player.localize('Copy the video URL'), | |
424 | listener: function () { | |
425 | copyToClipboard(buildVideoLink()) | |
426 | } | |
427 | }, | |
428 | { | |
429 | label: player.localize('Copy the video URL at the current time'), | |
430 | listener: function (this: videojs.Player) { | |
431 | copyToClipboard(buildVideoLink({ startTime: this.currentTime() })) | |
432 | } | |
433 | }, | |
434 | { | |
435 | label: player.localize('Copy embed code'), | |
436 | listener: () => { | |
437 | copyToClipboard(buildVideoEmbed(videoEmbedUrl)) | |
438 | } | |
439 | } | |
440 | ] | |
441 | ||
442 | if (mode === 'webtorrent') { | |
443 | content.push({ | |
444 | label: player.localize('Copy magnet URI'), | |
445 | listener: function (this: videojs.Player) { | |
446 | copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri) | |
447 | } | |
448 | }) | |
449 | } | |
450 | ||
451 | player.contextmenuUI({ content }) | |
452 | } | |
453 | ||
454 | private static addHotkeysOptions (plugins: VideoJSPluginOptions) { | |
455 | Object.assign(plugins, { | |
456 | hotkeys: { | |
457 | enableVolumeScroll: false, | |
458 | enableModifiersForNumbers: false, | |
459 | ||
460 | fullscreenKey: function (event: KeyboardEvent) { | |
461 | // fullscreen with the f key or Ctrl+Enter | |
462 | return event.key === 'f' || (event.ctrlKey && event.key === 'Enter') | |
463 | }, | |
464 | ||
465 | seekStep: function (event: KeyboardEvent) { | |
466 | // mimic VLC seek behavior, and default to 5 (original value is 5). | |
467 | if (event.ctrlKey && event.altKey) { | |
468 | return 5 * 60 | |
469 | } else if (event.ctrlKey) { | |
470 | return 60 | |
471 | } else if (event.altKey) { | |
472 | return 10 | |
473 | } else { | |
474 | return 5 | |
475 | } | |
476 | }, | |
477 | ||
478 | customKeys: { | |
479 | increasePlaybackRateKey: { | |
480 | key: function (event: KeyboardEvent) { | |
481 | return event.key === '>' | |
482 | }, | |
483 | handler: function (player: videojs.Player) { | |
484 | const newValue = Math.min(player.playbackRate() + 0.1, 5) | |
485 | player.playbackRate(parseFloat(newValue.toFixed(2))) | |
486 | } | |
487 | }, | |
488 | decreasePlaybackRateKey: { | |
489 | key: function (event: KeyboardEvent) { | |
490 | return event.key === '<' | |
491 | }, | |
492 | handler: function (player: videojs.Player) { | |
493 | const newValue = Math.max(player.playbackRate() - 0.1, 0.10) | |
494 | player.playbackRate(parseFloat(newValue.toFixed(2))) | |
495 | } | |
496 | }, | |
497 | frameByFrame: { | |
498 | key: function (event: KeyboardEvent) { | |
499 | return event.key === '.' | |
500 | }, | |
501 | handler: function (player: videojs.Player) { | |
502 | player.pause() | |
503 | // Calculate movement distance (assuming 30 fps) | |
504 | const dist = 1 / 30 | |
505 | player.currentTime(player.currentTime() + dist) | |
506 | } | |
507 | } | |
508 | } | |
509 | } | |
510 | }) | |
511 | } | |
512 | } | |
513 | ||
514 | // ############################################################################ | |
515 | ||
516 | export { | |
517 | videojs | |
518 | } |