]>
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 | stopTime: number | string | |
53 | ||
54 | theaterMode: boolean | |
55 | captions: boolean | |
56 | peertubeLink: boolean | |
57 | ||
58 | videoViewUrl: string | |
59 | embedUrl: string | |
60 | ||
61 | language?: string | |
62 | controls?: boolean | |
63 | muted?: boolean | |
64 | loop?: boolean | |
65 | subtitle?: string | |
66 | ||
67 | videoCaptions: VideoJSCaption[] | |
68 | ||
69 | userWatching?: UserWatching | |
70 | ||
71 | serverUrl: string | |
72 | } | |
73 | ||
74 | export type PeertubePlayerManagerOptions = { | |
75 | common: CommonOptions, | |
76 | webtorrent: WebtorrentOptions, | |
77 | p2pMediaLoader?: P2PMediaLoaderOptions | |
78 | } | |
79 | ||
80 | export class PeertubePlayerManager { | |
81 | ||
82 | private static videojsLocaleCache: { [ path: string ]: any } = {} | |
83 | private static playerElementClassName: string | |
84 | ||
85 | static getServerTranslations (serverUrl: string, locale: string) { | |
86 | const path = PeertubePlayerManager.getLocalePath(serverUrl, locale) | |
87 | // It is the default locale, nothing to translate | |
88 | if (!path) return Promise.resolve(undefined) | |
89 | ||
90 | return fetch(path + '/server.json') | |
91 | .then(res => res.json()) | |
92 | .catch(err => { | |
93 | console.error('Cannot get server translations', err) | |
94 | return undefined | |
95 | }) | |
96 | } | |
97 | ||
98 | static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions) { | |
99 | let p2pMediaLoader: any | |
100 | ||
101 | this.playerElementClassName = options.common.playerElement.className | |
102 | ||
103 | if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin') | |
104 | if (mode === 'p2p-media-loader') { | |
105 | [ p2pMediaLoader ] = await Promise.all([ | |
106 | import('p2p-media-loader-hlsjs'), | |
107 | import('./p2p-media-loader/p2p-media-loader-plugin') | |
108 | ]) | |
109 | } | |
110 | ||
111 | const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader) | |
112 | ||
113 | await this.loadLocaleInVideoJS(options.common.serverUrl, options.common.language) | |
114 | ||
115 | const self = this | |
116 | return new Promise(res => { | |
117 | videojs(options.common.playerElement, videojsOptions, function (this: any) { | |
118 | const player = this | |
119 | ||
120 | player.tech_.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options)) | |
121 | player.one('error', () => self.maybeFallbackToWebTorrent(mode, player, options)) | |
122 | ||
123 | self.addContextMenu(mode, player, options.common.embedUrl) | |
124 | ||
125 | return res(player) | |
126 | }) | |
127 | }) | |
128 | } | |
129 | ||
130 | private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) { | |
131 | if (currentMode === 'webtorrent') return | |
132 | ||
133 | console.log('Fallback to webtorrent.') | |
134 | ||
135 | const newVideoElement = document.createElement('video') | |
136 | newVideoElement.className = this.playerElementClassName | |
137 | ||
138 | // VideoJS wraps our video element inside a div | |
139 | let currentParentPlayerElement = options.common.playerElement.parentNode | |
140 | // Fix on IOS, don't ask me why | |
141 | if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode | |
142 | ||
143 | currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement) | |
144 | ||
145 | options.common.playerElement = newVideoElement | |
146 | options.common.onPlayerElementChange(newVideoElement) | |
147 | ||
148 | player.dispose() | |
149 | ||
150 | await import('./webtorrent/webtorrent-plugin') | |
151 | ||
152 | const mode = 'webtorrent' | |
153 | const videojsOptions = this.getVideojsOptions(mode, options) | |
154 | ||
155 | const self = this | |
156 | videojs(newVideoElement, videojsOptions, function (this: any) { | |
157 | const player = this | |
158 | ||
159 | self.addContextMenu(mode, player, options.common.embedUrl) | |
160 | }) | |
161 | } | |
162 | ||
163 | private static loadLocaleInVideoJS (serverUrl: string, locale: string) { | |
164 | const path = PeertubePlayerManager.getLocalePath(serverUrl, locale) | |
165 | // It is the default locale, nothing to translate | |
166 | if (!path) return Promise.resolve(undefined) | |
167 | ||
168 | let p: Promise<any> | |
169 | ||
170 | if (PeertubePlayerManager.videojsLocaleCache[path]) { | |
171 | p = Promise.resolve(PeertubePlayerManager.videojsLocaleCache[path]) | |
172 | } else { | |
173 | p = fetch(path + '/player.json') | |
174 | .then(res => res.json()) | |
175 | .then(json => { | |
176 | PeertubePlayerManager.videojsLocaleCache[path] = json | |
177 | return json | |
178 | }) | |
179 | .catch(err => { | |
180 | console.error('Cannot get player translations', err) | |
181 | return undefined | |
182 | }) | |
183 | } | |
184 | ||
185 | const completeLocale = getCompleteLocale(locale) | |
186 | return p.then(json => videojs.addLanguage(getShortLocale(completeLocale), json)) | |
187 | } | |
188 | ||
189 | private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) { | |
190 | const commonOptions = options.common | |
191 | const webtorrentOptions = options.webtorrent | |
192 | const p2pMediaLoaderOptions = options.p2pMediaLoader | |
193 | ||
194 | let autoplay = options.common.autoplay | |
195 | let html5 = {} | |
196 | ||
197 | const plugins: VideoJSPluginOptions = { | |
198 | peertube: { | |
199 | mode, | |
200 | autoplay, // Use peertube plugin autoplay because we get the file by webtorrent | |
201 | videoViewUrl: commonOptions.videoViewUrl, | |
202 | videoDuration: commonOptions.videoDuration, | |
203 | userWatching: commonOptions.userWatching, | |
204 | subtitle: commonOptions.subtitle, | |
205 | videoCaptions: commonOptions.videoCaptions, | |
206 | stopTime: commonOptions.stopTime | |
207 | } | |
208 | } | |
209 | ||
210 | if (mode === 'p2p-media-loader') { | |
211 | const p2pMediaLoader: P2PMediaLoaderPluginOptions = { | |
212 | redundancyBaseUrls: options.p2pMediaLoader.redundancyBaseUrls, | |
213 | type: 'application/x-mpegURL', | |
214 | startTime: commonOptions.startTime, | |
215 | src: p2pMediaLoaderOptions.playlistUrl | |
216 | } | |
217 | ||
218 | const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce | |
219 | .filter(t => t.startsWith('ws')) | |
220 | ||
221 | const p2pMediaLoaderConfig = { | |
222 | loader: { | |
223 | trackerAnnounce, | |
224 | segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url), | |
225 | rtcConfig: getRtcConfig(), | |
226 | requiredSegmentsPriority: 5, | |
227 | segmentUrlBuilder: segmentUrlBuilderFactory(options.p2pMediaLoader.redundancyBaseUrls) | |
228 | }, | |
229 | segments: { | |
230 | swarmId: p2pMediaLoaderOptions.playlistUrl | |
231 | } | |
232 | } | |
233 | const streamrootHls = { | |
234 | levelLabelHandler: (level: { height: number, width: number }) => { | |
235 | const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height) | |
236 | ||
237 | let label = file.resolution.label | |
238 | if (file.fps >= 50) label += file.fps | |
239 | ||
240 | return label | |
241 | }, | |
242 | html5: { | |
243 | hlsjsConfig: { | |
244 | liveSyncDurationCount: 7, | |
245 | loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass() | |
246 | } | |
247 | } | |
248 | } | |
249 | ||
250 | Object.assign(plugins, { p2pMediaLoader, streamrootHls }) | |
251 | html5 = streamrootHls.html5 | |
252 | } | |
253 | ||
254 | if (mode === 'webtorrent') { | |
255 | const webtorrent = { | |
256 | autoplay, | |
257 | videoDuration: commonOptions.videoDuration, | |
258 | playerElement: commonOptions.playerElement, | |
259 | videoFiles: webtorrentOptions.videoFiles, | |
260 | startTime: commonOptions.startTime | |
261 | } | |
262 | Object.assign(plugins, { webtorrent }) | |
263 | ||
264 | // WebTorrent plugin handles autoplay, because we do some hackish stuff in there | |
265 | autoplay = false | |
266 | } | |
267 | ||
268 | const videojsOptions = { | |
269 | html5, | |
270 | ||
271 | // We don't use text track settings for now | |
272 | textTrackSettings: false, | |
273 | controls: commonOptions.controls !== undefined ? commonOptions.controls : true, | |
274 | loop: commonOptions.loop !== undefined ? commonOptions.loop : false, | |
275 | ||
276 | muted: commonOptions.muted !== undefined | |
277 | ? commonOptions.muted | |
278 | : undefined, // Undefined so the player knows it has to check the local storage | |
279 | ||
280 | poster: commonOptions.poster, | |
281 | autoplay: autoplay === true ? 'any' : autoplay, // Use 'any' instead of true to get notifier by videojs if autoplay fails | |
282 | inactivityTimeout: commonOptions.inactivityTimeout, | |
283 | playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ], | |
284 | plugins, | |
285 | controlBar: { | |
286 | children: this.getControlBarChildren(mode, { | |
287 | captions: commonOptions.captions, | |
288 | peertubeLink: commonOptions.peertubeLink, | |
289 | theaterMode: commonOptions.theaterMode | |
290 | }) | |
291 | } | |
292 | } | |
293 | ||
294 | if (commonOptions.enableHotkeys === true) { | |
295 | Object.assign(videojsOptions.plugins, { | |
296 | hotkeys: { | |
297 | enableVolumeScroll: false, | |
298 | enableModifiersForNumbers: false, | |
299 | ||
300 | fullscreenKey: function (event: KeyboardEvent) { | |
301 | // fullscreen with the f key or Ctrl+Enter | |
302 | return event.key === 'f' || (event.ctrlKey && event.key === 'Enter') | |
303 | }, | |
304 | ||
305 | seekStep: function (event: KeyboardEvent) { | |
306 | // mimic VLC seek behavior, and default to 5 (original value is 5). | |
307 | if (event.ctrlKey && event.altKey) { | |
308 | return 5 * 60 | |
309 | } else if (event.ctrlKey) { | |
310 | return 60 | |
311 | } else if (event.altKey) { | |
312 | return 10 | |
313 | } else { | |
314 | return 5 | |
315 | } | |
316 | }, | |
317 | ||
318 | customKeys: { | |
319 | increasePlaybackRateKey: { | |
320 | key: function (event: KeyboardEvent) { | |
321 | return event.key === '>' | |
322 | }, | |
323 | handler: function (player: videojs.Player) { | |
324 | player.playbackRate((player.playbackRate() + 0.1).toFixed(2)) | |
325 | } | |
326 | }, | |
327 | decreasePlaybackRateKey: { | |
328 | key: function (event: KeyboardEvent) { | |
329 | return event.key === '<' | |
330 | }, | |
331 | handler: function (player: videojs.Player) { | |
332 | player.playbackRate((player.playbackRate() - 0.1).toFixed(2)) | |
333 | } | |
334 | }, | |
335 | frameByFrame: { | |
336 | key: function (event: KeyboardEvent) { | |
337 | return event.key === '.' | |
338 | }, | |
339 | handler: function (player: videojs.Player) { | |
340 | player.pause() | |
341 | // Calculate movement distance (assuming 30 fps) | |
342 | const dist = 1 / 30 | |
343 | player.currentTime(player.currentTime() + dist) | |
344 | } | |
345 | } | |
346 | } | |
347 | } | |
348 | }) | |
349 | } | |
350 | ||
351 | if (commonOptions.language && !isDefaultLocale(commonOptions.language)) { | |
352 | Object.assign(videojsOptions, { language: commonOptions.language }) | |
353 | } | |
354 | ||
355 | return videojsOptions | |
356 | } | |
357 | ||
358 | private static getControlBarChildren (mode: PlayerMode, options: { | |
359 | peertubeLink: boolean | |
360 | theaterMode: boolean, | |
361 | captions: boolean | |
362 | }) { | |
363 | const settingEntries = [] | |
364 | const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar' | |
365 | ||
366 | // Keep an order | |
367 | settingEntries.push('playbackRateMenuButton') | |
368 | if (options.captions === true) settingEntries.push('captionsButton') | |
369 | settingEntries.push('resolutionMenuButton') | |
370 | ||
371 | const children = { | |
372 | 'playToggle': {}, | |
373 | 'currentTimeDisplay': {}, | |
374 | 'timeDivider': {}, | |
375 | 'durationDisplay': {}, | |
376 | 'liveDisplay': {}, | |
377 | ||
378 | 'flexibleWidthSpacer': {}, | |
379 | 'progressControl': { | |
380 | children: { | |
381 | 'seekBar': { | |
382 | children: { | |
383 | [loadProgressBar]: {}, | |
384 | 'mouseTimeDisplay': {}, | |
385 | 'playProgressBar': {} | |
386 | } | |
387 | } | |
388 | } | |
389 | }, | |
390 | ||
391 | 'p2PInfoButton': {}, | |
392 | ||
393 | 'muteToggle': {}, | |
394 | 'volumeControl': {}, | |
395 | ||
396 | 'settingsButton': { | |
397 | setup: { | |
398 | maxHeightOffset: 40 | |
399 | }, | |
400 | entries: settingEntries | |
401 | } | |
402 | } | |
403 | ||
404 | if (options.peertubeLink === true) { | |
405 | Object.assign(children, { | |
406 | 'peerTubeLinkButton': {} | |
407 | }) | |
408 | } | |
409 | ||
410 | if (options.theaterMode === true) { | |
411 | Object.assign(children, { | |
412 | 'theaterButton': {} | |
413 | }) | |
414 | } | |
415 | ||
416 | Object.assign(children, { | |
417 | 'fullscreenToggle': {} | |
418 | }) | |
419 | ||
420 | return children | |
421 | } | |
422 | ||
423 | private static addContextMenu (mode: PlayerMode, player: any, videoEmbedUrl: string) { | |
424 | const content = [ | |
425 | { | |
426 | label: player.localize('Copy the video URL'), | |
427 | listener: function () { | |
428 | copyToClipboard(buildVideoLink()) | |
429 | } | |
430 | }, | |
431 | { | |
432 | label: player.localize('Copy the video URL at the current time'), | |
433 | listener: function () { | |
434 | const player = this as videojs.Player | |
435 | copyToClipboard(buildVideoLink(player.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 () { | |
450 | const player = this as videojs.Player | |
451 | copyToClipboard(player.webtorrent().getCurrentVideoFile().magnetUri) | |
452 | } | |
453 | }) | |
454 | } | |
455 | ||
456 | player.contextmenuUI({ content }) | |
457 | } | |
458 | ||
459 | private static getLocalePath (serverUrl: string, locale: string) { | |
460 | const completeLocale = getCompleteLocale(locale) | |
461 | ||
462 | if (!is18nLocale(completeLocale) || isDefaultLocale(completeLocale)) return undefined | |
463 | ||
464 | return serverUrl + '/client/locales/' + completeLocale | |
465 | } | |
466 | } | |
467 | ||
468 | // ############################################################################ | |
469 | ||
470 | export { | |
471 | videojs | |
472 | } |