]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
fix missing title attribute on <iframe> tag suggested for embedding (#3901)
[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 embedTitle: string
102
103 isLive: boolean
104
105 language?: string
106
107 videoCaptions: VideoJSCaption[]
108
109 userWatching?: UserWatching
110
111 serverUrl: string
112 }
113
114 export type PeertubePlayerManagerOptions = {
115 common: CommonOptions,
116 webtorrent: WebtorrentOptions,
117 p2pMediaLoader?: P2PMediaLoaderOptions
118 }
119
120 export class PeertubePlayerManager {
121 private static playerElementClassName: string
122 private static onPlayerChange: (player: videojs.Player) => void
123
124 private static alreadyPlayed = false
125
126 static initState () {
127 PeertubePlayerManager.alreadyPlayed = false
128 }
129
130 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
131 let p2pMediaLoader: any
132
133 this.onPlayerChange = onPlayerChange
134 this.playerElementClassName = options.common.playerElement.className
135
136 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
137 if (mode === 'p2p-media-loader') {
138 [ p2pMediaLoader ] = await Promise.all([
139 import('p2p-media-loader-hlsjs'),
140 import('./p2p-media-loader/p2p-media-loader-plugin')
141 ])
142 }
143
144 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
145
146 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
147
148 const self = this
149 return new Promise(res => {
150 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
151 const player = this
152
153 let alreadyFallback = false
154
155 player.tech(true).one('error', () => {
156 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
157 alreadyFallback = true
158 })
159
160 player.one('error', () => {
161 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
162 alreadyFallback = true
163 })
164
165 player.one('play', () => {
166 PeertubePlayerManager.alreadyPlayed = true
167 })
168
169 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
170
171 player.bezels()
172
173 return res(player)
174 })
175 })
176 }
177
178 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
179 if (currentMode === 'webtorrent') return
180
181 console.log('Fallback to webtorrent.')
182
183 const newVideoElement = document.createElement('video')
184 newVideoElement.className = this.playerElementClassName
185
186 // VideoJS wraps our video element inside a div
187 let currentParentPlayerElement = options.common.playerElement.parentNode
188 // Fix on IOS, don't ask me why
189 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
190
191 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
192
193 options.common.playerElement = newVideoElement
194 options.common.onPlayerElementChange(newVideoElement)
195
196 player.dispose()
197
198 await import('./webtorrent/webtorrent-plugin')
199
200 const mode = 'webtorrent'
201 const videojsOptions = this.getVideojsOptions(mode, options)
202
203 const self = this
204 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
205 const player = this
206
207 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
208
209 PeertubePlayerManager.onPlayerChange(player)
210 })
211 }
212
213 private static getVideojsOptions (
214 mode: PlayerMode,
215 options: PeertubePlayerManagerOptions,
216 p2pMediaLoaderModule?: any
217 ): videojs.PlayerOptions {
218 const commonOptions = options.common
219 const isHLS = mode === 'p2p-media-loader'
220
221 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
222 let html5 = {}
223
224 const plugins: VideoJSPluginOptions = {
225 peertube: {
226 mode,
227 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
228 videoViewUrl: commonOptions.videoViewUrl,
229 videoDuration: commonOptions.videoDuration,
230 userWatching: commonOptions.userWatching,
231 subtitle: commonOptions.subtitle,
232 videoCaptions: commonOptions.videoCaptions,
233 stopTime: commonOptions.stopTime,
234 isLive: commonOptions.isLive
235 }
236 }
237
238 if (commonOptions.playlist) {
239 plugins.playlist = commonOptions.playlist
240 }
241
242 if (commonOptions.enableHotkeys === true) {
243 PeertubePlayerManager.addHotkeysOptions(plugins)
244 }
245
246 if (isHLS) {
247 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
248
249 html5 = hlsjs.html5
250 }
251
252 if (mode === 'webtorrent') {
253 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
254
255 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
256 autoplay = false
257 }
258
259 const videojsOptions = {
260 html5,
261
262 // We don't use text track settings for now
263 textTrackSettings: false as any, // FIXME: typings
264 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
265 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
266
267 muted: commonOptions.muted !== undefined
268 ? commonOptions.muted
269 : undefined, // Undefined so the player knows it has to check the local storage
270
271 autoplay: this.getAutoPlayValue(autoplay),
272
273 poster: commonOptions.poster,
274 inactivityTimeout: commonOptions.inactivityTimeout,
275 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
276
277 plugins,
278
279 controlBar: {
280 children: this.getControlBarChildren(mode, {
281 captions: commonOptions.captions,
282 peertubeLink: commonOptions.peertubeLink,
283 theaterButton: commonOptions.theaterButton,
284
285 nextVideo: commonOptions.nextVideo,
286 hasNextVideo: commonOptions.hasNextVideo,
287
288 previousVideo: commonOptions.previousVideo,
289 hasPreviousVideo: commonOptions.hasPreviousVideo
290 }) as any // FIXME: typings
291 }
292 }
293
294 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
295 Object.assign(videojsOptions, { language: commonOptions.language })
296 }
297
298 return videojsOptions
299 }
300
301 private static addP2PMediaLoaderOptions (
302 plugins: VideoJSPluginOptions,
303 options: PeertubePlayerManagerOptions,
304 p2pMediaLoaderModule: any
305 ) {
306 const p2pMediaLoaderOptions = options.p2pMediaLoader
307 const commonOptions = options.common
308
309 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
310 .filter(t => t.startsWith('ws'))
311
312 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
313
314 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
315 redundancyUrlManager,
316 type: 'application/x-mpegURL',
317 startTime: commonOptions.startTime,
318 src: p2pMediaLoaderOptions.playlistUrl
319 }
320
321 let consumeOnly = false
322 // FIXME: typings
323 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
324 console.log('We are on a cellular connection: disabling seeding.')
325 consumeOnly = true
326 }
327
328 const p2pMediaLoaderConfig = {
329 loader: {
330 trackerAnnounce,
331 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
332 rtcConfig: getRtcConfig(),
333 requiredSegmentsPriority: 1,
334 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
335 useP2P: getStoredP2PEnabled(),
336 consumeOnly
337 },
338 segments: {
339 swarmId: p2pMediaLoaderOptions.playlistUrl
340 }
341 }
342 const hlsjs = {
343 levelLabelHandler: (level: { height: number, width: number }) => {
344 const resolution = Math.min(level.height || 0, level.width || 0)
345
346 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
347 // We don't have files for live videos
348 if (!file) return level.height
349
350 let label = file.resolution.label
351 if (file.fps >= 50) label += file.fps
352
353 return label
354 },
355 html5: {
356 hlsjsConfig: {
357 capLevelToPlayerSize: true,
358 autoStartLoad: false,
359 liveSyncDurationCount: 5,
360 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
361 }
362 }
363 }
364
365 const toAssign = { p2pMediaLoader, hlsjs }
366 Object.assign(plugins, toAssign)
367
368 return toAssign
369 }
370
371 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
372 const commonOptions = options.common
373 const webtorrentOptions = options.webtorrent
374
375 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
376 ? true
377 : false
378
379 const webtorrent = {
380 autoplay,
381 videoDuration: commonOptions.videoDuration,
382 playerElement: commonOptions.playerElement,
383 videoFiles: webtorrentOptions.videoFiles,
384 startTime: commonOptions.startTime
385 }
386
387 Object.assign(plugins, { webtorrent })
388 }
389
390 private static getControlBarChildren (mode: PlayerMode, options: {
391 peertubeLink: boolean
392 theaterButton: boolean
393 captions: boolean
394
395 nextVideo?: Function
396 hasNextVideo?: () => boolean
397
398 previousVideo?: Function
399 hasPreviousVideo?: () => boolean
400 }) {
401 const settingEntries = []
402 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
403
404 // Keep an order
405 settingEntries.push('playbackRateMenuButton')
406 if (options.captions === true) settingEntries.push('captionsButton')
407 settingEntries.push('resolutionMenuButton')
408
409 const children = {}
410
411 if (options.previousVideo) {
412 const buttonOptions: NextPreviousVideoButtonOptions = {
413 type: 'previous',
414 handler: options.previousVideo,
415 isDisabled: () => {
416 if (!options.hasPreviousVideo) return false
417
418 return !options.hasPreviousVideo()
419 }
420 }
421
422 Object.assign(children, {
423 'previousVideoButton': buttonOptions
424 })
425 }
426
427 Object.assign(children, { playToggle: {} })
428
429 if (options.nextVideo) {
430 const buttonOptions: NextPreviousVideoButtonOptions = {
431 type: 'next',
432 handler: options.nextVideo,
433 isDisabled: () => {
434 if (!options.hasNextVideo) return false
435
436 return !options.hasNextVideo()
437 }
438 }
439
440 Object.assign(children, {
441 'nextVideoButton': buttonOptions
442 })
443 }
444
445 Object.assign(children, {
446 'currentTimeDisplay': {},
447 'timeDivider': {},
448 'durationDisplay': {},
449 'liveDisplay': {},
450
451 'flexibleWidthSpacer': {},
452 'progressControl': {
453 children: {
454 'seekBar': {
455 children: {
456 [loadProgressBar]: {},
457 'mouseTimeDisplay': {},
458 'playProgressBar': {}
459 }
460 }
461 }
462 },
463
464 'p2PInfoButton': {},
465
466 'muteToggle': {},
467 'volumeControl': {},
468
469 'settingsButton': {
470 setup: {
471 maxHeightOffset: 40
472 },
473 entries: settingEntries
474 }
475 })
476
477 if (options.peertubeLink === true) {
478 Object.assign(children, {
479 'peerTubeLinkButton': {}
480 })
481 }
482
483 if (options.theaterButton === true) {
484 Object.assign(children, {
485 'theaterButton': {}
486 })
487 }
488
489 Object.assign(children, {
490 'fullscreenToggle': {}
491 })
492
493 return children
494 }
495
496 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
497 const content = [
498 {
499 label: player.localize('Copy the video URL'),
500 listener: function () {
501 copyToClipboard(buildVideoLink())
502 }
503 },
504 {
505 label: player.localize('Copy the video URL at the current time'),
506 listener: function (this: videojs.Player) {
507 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
508 }
509 },
510 {
511 label: player.localize('Copy embed code'),
512 listener: () => {
513 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
514 }
515 }
516 ]
517
518 if (mode === 'webtorrent') {
519 content.push({
520 label: player.localize('Copy magnet URI'),
521 listener: function (this: videojs.Player) {
522 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
523 }
524 })
525 }
526
527 player.contextmenuUI({ content })
528 }
529
530 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
531 const isNaked = (event: KeyboardEvent, key: string) =>
532 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
533
534 Object.assign(plugins, {
535 hotkeys: {
536 skipInitialFocus: true,
537 enableInactiveFocus: false,
538 captureDocumentHotkeys: true,
539 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
540 const tagName = e.tagName.toLowerCase()
541 return e.id === 'content' || tagName === 'body' || tagName === 'video'
542 },
543
544 enableVolumeScroll: false,
545 enableModifiersForNumbers: false,
546
547 rewindKey: function (event: KeyboardEvent) {
548 return isNaked(event, 'ArrowLeft')
549 },
550
551 forwardKey: function (event: KeyboardEvent) {
552 return isNaked(event, 'ArrowRight')
553 },
554
555 fullscreenKey: function (event: KeyboardEvent) {
556 // fullscreen with the f key or Ctrl+Enter
557 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
558 },
559
560 customKeys: {
561 increasePlaybackRateKey: {
562 key: function (event: KeyboardEvent) {
563 return isNaked(event, '>')
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 isNaked(event, '<')
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 isNaked(event, '.')
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 }