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