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