]>
Commit | Line | Data |
---|---|---|
1 | import { VideoFile } from '../../../../shared/models/videos' | |
2 | // @ts-ignore | |
3 | import * as videojs from 'video.js' | |
4 | import 'videojs-hotkeys' | |
5 | import 'videojs-dock' | |
6 | import 'videojs-contextmenu-ui' | |
7 | import 'videojs-contrib-quality-levels' | |
8 | import './peertube-plugin' | |
9 | import './videojs-components/peertube-link-button' | |
10 | import './videojs-components/resolution-menu-button' | |
11 | import './videojs-components/settings-menu-button' | |
12 | import './videojs-components/p2p-info-button' | |
13 | import './videojs-components/peertube-load-progress-bar' | |
14 | import './videojs-components/theater-button' | |
15 | import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings' | |
16 | import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils' | |
17 | import { getCompleteLocale, getShortLocale, is18nLocale, isDefaultLocale } from '../../../../shared/models/i18n/i18n' | |
18 | import { segmentValidatorFactory } from './p2p-media-loader/segment-validator' | |
19 | import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder' | |
20 | ||
21 | // Change 'Playback Rate' to 'Speed' (smaller for our settings menu) | |
22 | videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed' | |
23 | // Change Captions to Subtitles/CC | |
24 | videojsUntyped.getComponent('CaptionsButton').prototype.controlText_ = 'Subtitles/CC' | |
25 | // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know) | |
26 | videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' ' | |
27 | ||
28 | export type PlayerMode = 'webtorrent' | 'p2p-media-loader' | |
29 | ||
30 | export type WebtorrentOptions = { | |
31 | videoFiles: VideoFile[] | |
32 | } | |
33 | ||
34 | export type P2PMediaLoaderOptions = { | |
35 | playlistUrl: string | |
36 | segmentsSha256Url: string | |
37 | trackerAnnounce: string[] | |
38 | redundancyBaseUrls: string[] | |
39 | videoFiles: VideoFile[] | |
40 | } | |
41 | ||
42 | export type CommonOptions = { | |
43 | playerElement: HTMLVideoElement | |
44 | onPlayerElementChange: (element: HTMLVideoElement) => void | |
45 | ||
46 | autoplay: boolean | |
47 | videoDuration: number | |
48 | enableHotkeys: boolean | |
49 | inactivityTimeout: number | |
50 | poster: string | |
51 | startTime: number | string | |
52 | ||
53 | theaterMode: boolean | |
54 | captions: boolean | |
55 | peertubeLink: boolean | |
56 | ||
57 | videoViewUrl: string | |
58 | embedUrl: string | |
59 | ||
60 | language?: string | |
61 | controls?: boolean | |
62 | muted?: boolean | |
63 | loop?: boolean | |
64 | subtitle?: string | |
65 | ||
66 | videoCaptions: VideoJSCaption[] | |
67 | ||
68 | userWatching?: UserWatching | |
69 | ||
70 | serverUrl: string | |
71 | } | |
72 | ||
73 | export type PeertubePlayerManagerOptions = { | |
74 | common: CommonOptions, | |
75 | webtorrent: WebtorrentOptions, | |
76 | p2pMediaLoader?: P2PMediaLoaderOptions | |
77 | } | |
78 | ||
79 | export class PeertubePlayerManager { | |
80 | ||
81 | private static videojsLocaleCache: { [ path: string ]: any } = {} | |
82 | private static playerElementClassName: string | |
83 | ||
84 | static getServerTranslations (serverUrl: string, locale: string) { | |
85 | const path = PeertubePlayerManager.getLocalePath(serverUrl, locale) | |
86 | // It is the default locale, nothing to translate | |
87 | if (!path) return Promise.resolve(undefined) | |
88 | ||
89 | return fetch(path + '/server.json') | |
90 | .then(res => res.json()) | |
91 | .catch(err => { | |
92 | console.error('Cannot get server translations', err) | |
93 | return undefined | |
94 | }) | |
95 | } | |
96 | ||
97 | static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) { | |
98 | let p2pMediaLoader: any | |
99 | ||
100 | this.playerElementClassName = options.common.playerElement.className | |
101 | ||
102 | if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin') | |
103 | if (mode === 'p2p-media-loader') { | |
104 | [ p2pMediaLoader ] = await Promise.all([ | |
105 | import('p2p-media-loader-hlsjs'), | |
106 | import('./p2p-media-loader/p2p-media-loader-plugin') | |
107 | ]) | |
108 | } | |
109 | ||
110 | const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader) | |
111 | ||
112 | await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language) | |
113 | ||
114 | const self = this | |
115 | return new Promise(res => { | |
116 | videojs(options.common.playerElement, videojsOptions, function (this: any) { | |
117 | const player = this | |
118 | ||
119 | player.tech_.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options)) | |
120 | player.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options)) | |
121 | ||
122 | self.addContextMenu(mode, player, options.common.embedUrl) | |
123 | ||
124 | return res(player) | |
125 | }) | |
126 | }) | |
127 | } | |
128 | ||
129 | private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) { | |
130 | if (currentMode === 'webtorrent') return | |
131 | ||
132 | console.log('Fallback to webtorrent.') | |
133 | ||
134 | const newVideoElement = document.createElement('video') | |
135 | newVideoElement.className = this.playerElementClassName | |
136 | ||
137 | // VideoJS wraps our video element inside a div | |
138 | let currentParentPlayerElement = options.common.playerElement.parentNode | |
139 | // Fix on IOS, don't ask me why | |
140 | if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode | |
141 | ||
142 | currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement) | |
143 | ||
144 | options.common.playerElement = newVideoElement | |
145 | options.common.onPlayerElementChange(newVideoElement) | |
146 | ||
147 | player.dispose() | |
148 | ||
149 | await import('./webtorrent/webtorrent-plugin') | |
150 | ||
151 | const mode = 'webtorrent' | |
152 | const videojsOptions = this.getVideojsOptions(mode, options) | |
153 | ||
154 | const self = this | |
155 | videojs(newVideoElement, videojsOptions, function (this: any) { | |
156 | const player = this | |
157 | ||
158 | self.addContextMenu(mode, player, options.common.embedUrl) | |
159 | }) | |
160 | } | |
161 | ||
162 | private static loadLocaleInVideoJS (serverUrl: string, locale: string) { | |
163 | const path = PeertubePlayerManager.getLocalePath(serverUrl, locale) | |
164 | // It is the default locale, nothing to translate | |
165 | if (!path) return Promise.resolve(undefined) | |
166 | ||
167 | let p: Promise<any> | |
168 | ||
169 | if (PeertubePlayerManager.videojsLocaleCache[path]) { | |
170 | p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path]) | |
171 | } else { | |
172 | p = fetch(path + '/player.json') | |
173 | .then(res => res.json()) | |
174 | .then(json => { | |
175 | PeertubePlayerManager.videojsLocaleCache[path] = json | |
176 | return json | |
177 | }) | |
178 | .catch(err => { | |
179 | console.error('Cannot get player translations', err) | |
180 | return undefined | |
181 | }) | |
182 | } | |
183 | ||
184 | const completeLocale = getCompleteLocale(locale) | |
185 | return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json)) | |
186 | } | |
187 | ||
188 | private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) { | |
189 | const commonOptions = options.common | |
190 | const webtorrentOptions = options.webtorrent | |
191 | const p2pMediaLoaderOptions = options.p2pMediaLoader | |
192 | ||
193 | let autoplay = options.common.autoplay | |
194 | let html5 = {} | |
195 | ||
196 | const plugins: VideoJSPluginOptions = { | |
197 | peertube: { | |
198 | mode, | |
199 | autoplay, // Use peertube plugin autoplay because we get the file by webtorrent | |
200 | videoViewUrl: commonOptions.videoViewUrl, | |
201 | videoDuration: commonOptions.videoDuration, | |
202 | startTime: commonOptions.startTime, | |
203 | userWatching: commonOptions.userWatching, | |
204 | subtitle: commonOptions.subtitle, | |
205 | videoCaptions: commonOptions.videoCaptions | |
206 | } | |
207 | } | |
208 | ||
209 | if (mode === 'p2p-media-loader') { | |
210 | const p2pMediaLoader: P2PMediaLoaderPluginOptions = { | |
211 | redundancyBaseUrls: options.p2pMediaLoader.redundancyBaseUrls, | |
212 | type: 'application/x-mpegURL', | |
213 | src: p2pMediaLoaderOptions.playlistUrl | |
214 | } | |
215 | ||
216 | const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce | |
217 | .filter(t => t.startsWith('ws')) | |
218 | ||
219 | const p2pMediaLoaderConfig = { | |
220 | loader: { | |
221 | trackerAnnounce, | |
222 | segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url), | |
223 | rtcConfig: getRtcConfig(), | |
224 | requiredSegmentsPriority: 5, | |
225 | segmentUrlBuilder: segmentUrlBuilderFactory(options.p2pMediaLoader.redundancyBaseUrls) | |
226 | }, | |
227 | segments: { | |
228 | swarmId: p2pMediaLoaderOptions.playlistUrl | |
229 | } | |
230 | } | |
231 | const streamrootHls = { | |
232 | levelLabelHandler: (level: { height: number, width: number }) => { | |
233 | const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height) | |
234 | ||
235 | let label = file.resolution.label | |
236 | if (file.fps >= 50) label += file.fps | |
237 | ||
238 | return label | |
239 | }, | |
240 | html5: { | |
241 | hlsjsConfig: { | |
242 | liveSyncDurationCount: 7, | |
243 | loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass() | |
244 | } | |
245 | } | |
246 | } | |
247 | ||
248 | Object.assign(plugins, { p2pMediaLoader, streamrootHls }) | |
249 | html5 = streamrootHls.html5 | |
250 | } | |
251 | ||
252 | if (mode === 'webtorrent') { | |
253 | const webtorrent = { | |
254 | autoplay, | |
255 | videoDuration: commonOptions.videoDuration, | |
256 | playerElement: commonOptions.playerElement, | |
257 | videoFiles: webtorrentOptions.videoFiles | |
258 | } | |
259 | Object.assign(plugins, { webtorrent }) | |
260 | ||
261 | // WebTorrent plugin handles autoplay, because we do some hackish stuff in there | |
262 | autoplay = false | |
263 | } | |
264 | ||
265 | const videojsOptions = { | |
266 | html5, | |
267 | ||
268 | // We don't use text track settings for now | |
269 | textTrackSettings: false, | |
270 | controls: commonOptions.controls !== undefined ? commonOptions.controls : true, | |
271 | loop: commonOptions.loop !== undefined ? commonOptions.loop : false, | |
272 | ||
273 | muted: commonOptions.muted !== undefined | |
274 | ? commonOptions.muted | |
275 | : undefined, // Undefined so the player knows it has to check the local storage | |
276 | ||
277 | poster: commonOptions.poster, | |
278 | autoplay: autoplay === true ? 'any' : autoplay, // Use 'any' instead of true to get notifier by videojs if autoplay fails | |
279 | inactivityTimeout: commonOptions.inactivityTimeout, | |
280 | playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ], | |
281 | plugins, | |
282 | controlBar: { | |
283 | children: this.getControlBarChildren(mode, { | |
284 | captions: commonOptions.captions, | |
285 | peertubeLink: commonOptions.peertubeLink, | |
286 | theaterMode: commonOptions.theaterMode | |
287 | }) | |
288 | } | |
289 | } | |
290 | ||
291 | if (commonOptions.enableHotkeys === true) { | |
292 | Object.assign(videojsOptions.plugins, { | |
293 | hotkeys: { | |
294 | enableVolumeScroll: false, | |
295 | enableModifiersForNumbers: false, | |
296 | ||
297 | fullscreenKey: function (event: KeyboardEvent) { | |
298 | // fullscreen with the f key or Ctrl+Enter | |
299 | return event.key === 'f' || (event.ctrlKey && event.key === 'Enter') | |
300 | }, | |
301 | ||
302 | seekStep: function (event: KeyboardEvent) { | |
303 | // mimic VLC seek behavior, and default to 5 (original value is 5). | |
304 | if (event.ctrlKey && event.altKey) { | |
305 | return 5 * 60 | |
306 | } else if (event.ctrlKey) { | |
307 | return 60 | |
308 | } else if (event.altKey) { | |
309 | return 10 | |
310 | } else { | |
311 | return 5 | |
312 | } | |
313 | }, | |
314 | ||
315 | customKeys: { | |
316 | increasePlaybackRateKey: { | |
317 | key: function (event: KeyboardEvent) { | |
318 | return event.key === '>' | |
319 | }, | |
320 | handler: function (player: videojs.Player) { | |
321 | player.playbackRate((player.playbackRate() + 0.1).toFixed(2)) | |
322 | } | |
323 | }, | |
324 | decreasePlaybackRateKey: { | |
325 | key: function (event: KeyboardEvent) { | |
326 | return event.key === '<' | |
327 | }, | |
328 | handler: function (player: videojs.Player) { | |
329 | player.playbackRate((player.playbackRate() - 0.1).toFixed(2)) | |
330 | } | |
331 | }, | |
332 | frameByFrame: { | |
333 | key: function (event: KeyboardEvent) { | |
334 | return event.key === '.' | |
335 | }, | |
336 | handler: function (player: videojs.Player) { | |
337 | player.pause() | |
338 | // Calculate movement distance (assuming 30 fps) | |
339 | const dist = 1 / 30 | |
340 | player.currentTime(player.currentTime() + dist) | |
341 | } | |
342 | } | |
343 | } | |
344 | } | |
345 | }) | |
346 | } | |
347 | ||
348 | if (commonOptions.language && !isDefaultLocale(commonOptions.language)) { | |
349 | Object.assign(videojsOptions, { language: commonOptions.language }) | |
350 | } | |
351 | ||
352 | return videojsOptions | |
353 | } | |
354 | ||
355 | private static getControlBarChildren (mode: PlayerMode, options: { | |
356 | peertubeLink: boolean | |
357 | theaterMode: boolean, | |
358 | captions: boolean | |
359 | }) { | |
360 | const settingEntries = [] | |
361 | const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar' | |
362 | ||
363 | // Keep an order | |
364 | settingEntries.push('playbackRateMenuButton') | |
365 | if (options.captions === true) settingEntries.push('captionsButton') | |
366 | settingEntries.push('resolutionMenuButton') | |
367 | ||
368 | const children = { | |
369 | 'playToggle': {}, | |
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.theaterMode === 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: any, 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 () { | |
431 | const player = this as videojs.Player | |
432 | copyToClipboard(buildVideoLink(player.currentTime())) | |
433 | } | |
434 | }, | |
435 | { | |
436 | label: player.localize('Copy embed code'), | |
437 | listener: () => { | |
438 | copyToClipboard(buildVideoEmbed(videoEmbedUrl)) | |
439 | } | |
440 | } | |
441 | ] | |
442 | ||
443 | if (mode === 'webtorrent') { | |
444 | content.push({ | |
445 | label: player.localize('Copy magnet URI'), | |
446 | listener: function () { | |
447 | const player = this as videojs.Player | |
448 | copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri) | |
449 | } | |
450 | }) | |
451 | } | |
452 | ||
453 | player.contextmenuUI({ content }) | |
454 | } | |
455 | ||
456 | private static getLocalePath (serverUrl: string, locale: string) { | |
457 | const completeLocale = getCompleteLocale(locale) | |
458 | ||
459 | if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined | |
460 | ||
461 | return serverUrl + '/client/locales/' + completeLocale | |
462 | } | |
463 | } | |
464 | ||
465 | // ############################################################################ | |
466 | ||
467 | export { | |
468 | videojs | |
469 | } |