]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
CommitLineData
512decf3 1import 'videojs-hotkeys/videojs.hotkeys'
2adfc7ea
C
2import 'videojs-dock'
3import 'videojs-contextmenu-ui'
4import 'videojs-contrib-quality-levels'
f5fcd9f7 5import './upnext/end-card'
3bcb4fd7 6import './upnext/upnext-plugin'
62ab565d 7import './bezels/bezels-plugin'
2adfc7ea 8import './peertube-plugin'
a950e4c8 9import './videojs-components/next-previous-video-button'
f5fcd9f7 10import './videojs-components/p2p-info-button'
2adfc7ea 11import './videojs-components/peertube-link-button'
f5fcd9f7 12import './videojs-components/peertube-load-progress-bar'
2adfc7ea 13import './videojs-components/resolution-menu-button'
f5fcd9f7
C
14import './videojs-components/resolution-menu-item'
15import './videojs-components/settings-dialog'
2adfc7ea 16import './videojs-components/settings-menu-button'
f5fcd9f7
C
17import './videojs-components/settings-menu-item'
18import './videojs-components/settings-panel'
19import './videojs-components/settings-panel-child'
2adfc7ea 20import './videojs-components/theater-button'
4572c3d0 21import './playlist/playlist-plugin'
3e2bc4ea 22import videojs from 'video.js'
bd45d503 23import { isDefaultLocale } from '@shared/core-utils/i18n'
4572c3d0 24import { VideoFile } from '@shared/models'
da332417 25import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
3e2bc4ea
C
26import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
27import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
43c66a91 28import { getStoredP2PEnabled } from './peertube-player-local-storage'
4572c3d0 29import {
a950e4c8 30 NextPreviousVideoButtonOptions,
4572c3d0
C
31 P2PMediaLoaderPluginOptions,
32 PlaylistPluginOptions,
33 UserWatching,
34 VideoJSCaption,
35 VideoJSPluginOptions
36} from './peertube-videojs-typings'
3f9c4955 37import { TranslationsManager } from './translations-manager'
afff310e
RK
38import { buildVideoOrPlaylistEmbed, buildVideoLink, getRtcConfig, isSafari, isIOS } from './utils'
39import { copyToClipboard } from '../../root-helpers/utils'
2adfc7ea
C
40
41// Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
f5fcd9f7
C
42(videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
43
44const CaptionsButton = videojs.getComponent('CaptionsButton') as any
2adfc7ea 45// Change Captions to Subtitles/CC
f5fcd9f7 46CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
2adfc7ea 47// We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
f5fcd9f7 48CaptionsButton.prototype.label_ = ' '
2adfc7ea 49
3b6f205c 50export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
2adfc7ea 51
3b6f205c 52export type WebtorrentOptions = {
2adfc7ea
C
53 videoFiles: VideoFile[]
54}
55
3b6f205c 56export type P2PMediaLoaderOptions = {
2adfc7ea 57 playlistUrl: string
09209296 58 segmentsSha256Url: string
4348a27d 59 trackerAnnounce: string[]
09209296
C
60 redundancyBaseUrls: string[]
61 videoFiles: VideoFile[]
2adfc7ea
C
62}
63
5efab546
C
64export interface CustomizationOptions {
65 startTime: number | string
66 stopTime: number | string
67
68 controls?: boolean
69 muted?: boolean
70 loop?: boolean
71 subtitle?: string
96f6278f 72 resume?: string
5efab546
C
73
74 peertubeLink: boolean
75}
76
77export interface CommonOptions extends CustomizationOptions {
2adfc7ea 78 playerElement: HTMLVideoElement
6ec0b75b 79 onPlayerElementChange: (element: HTMLVideoElement) => void
2adfc7ea
C
80
81 autoplay: boolean
a950e4c8
C
82
83 nextVideo?: () => void
84 hasNextVideo?: () => boolean
85
86 previousVideo?: () => void
87 hasPreviousVideo?: () => boolean
4572c3d0
C
88
89 playlist?: PlaylistPluginOptions
90
2adfc7ea
C
91 videoDuration: number
92 enableHotkeys: boolean
93 inactivityTimeout: number
94 poster: string
2adfc7ea 95
3d9a63d3 96 theaterButton: boolean
2adfc7ea 97 captions: boolean
2adfc7ea
C
98
99 videoViewUrl: string
100 embedUrl: string
4097c6d6 101 embedTitle: string
2adfc7ea 102
25b7c847
C
103 isLive: boolean
104
2adfc7ea 105 language?: string
2adfc7ea
C
106
107 videoCaptions: VideoJSCaption[]
108
109 userWatching?: UserWatching
110
111 serverUrl: string
112}
113
114export type PeertubePlayerManagerOptions = {
115 common: CommonOptions,
6ec0b75b 116 webtorrent: WebtorrentOptions,
2adfc7ea
C
117 p2pMediaLoader?: P2PMediaLoaderOptions
118}
119
120export class PeertubePlayerManager {
6ec0b75b 121 private static playerElementClassName: string
7e37e111 122 private static onPlayerChange: (player: videojs.Player) => void
2adfc7ea 123
9eccae74
C
124 private static alreadyPlayed = false
125
1a568b6f
C
126 static initState () {
127 PeertubePlayerManager.alreadyPlayed = false
128 }
129
7e37e111 130 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
4348a27d
C
131 let p2pMediaLoader: any
132
bfbd9128 133 this.onPlayerChange = onPlayerChange
6ec0b75b
C
134 this.playerElementClassName = options.common.playerElement.className
135
09209296 136 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
4348a27d
C
137 if (mode === 'p2p-media-loader') {
138 [ p2pMediaLoader ] = await Promise.all([
139 import('p2p-media-loader-hlsjs'),
09209296 140 import('./p2p-media-loader/p2p-media-loader-plugin')
4348a27d
C
141 ])
142 }
2adfc7ea 143
4348a27d 144 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
2adfc7ea 145
3f9c4955 146 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
2adfc7ea
C
147
148 const self = this
149 return new Promise(res => {
7e37e111 150 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
2adfc7ea
C
151 const player = this
152
536598cf
C
153 let alreadyFallback = false
154
f5fcd9f7 155 player.tech(true).one('error', () => {
536598cf
C
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 })
6ec0b75b 164
9eccae74
C
165 player.one('play', () => {
166 PeertubePlayerManager.alreadyPlayed = true
167 })
168
4097c6d6 169 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
2adfc7ea 170
10475dea
RK
171 player.bezels()
172
2adfc7ea
C
173 return res(player)
174 })
175 })
176 }
177
96cb4527
C
178 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
179 if (currentMode === 'webtorrent') return
180
181 console.log('Fallback to webtorrent.')
182
6ec0b75b
C
183 const newVideoElement = document.createElement('video')
184 newVideoElement.className = this.playerElementClassName
185
186 // VideoJS wraps our video element inside a div
96cb4527
C
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
6ec0b75b
C
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
7e37e111 204 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
6ec0b75b
C
205 const player = this
206
4097c6d6 207 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
bfbd9128
C
208
209 PeertubePlayerManager.onPlayerChange(player)
6ec0b75b
C
210 })
211 }
212
f5fcd9f7
C
213 private static getVideojsOptions (
214 mode: PlayerMode,
215 options: PeertubePlayerManagerOptions,
216 p2pMediaLoaderModule?: any
7e37e111 217 ): videojs.PlayerOptions {
2adfc7ea 218 const commonOptions = options.common
9eccae74 219 const isHLS = mode === 'p2p-media-loader'
09209296 220
72efdda5 221 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
3b6f205c 222 let html5 = {}
2adfc7ea
C
223
224 const plugins: VideoJSPluginOptions = {
225 peertube: {
09209296 226 mode,
cb5c2abc 227 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
2adfc7ea
C
228 videoViewUrl: commonOptions.videoViewUrl,
229 videoDuration: commonOptions.videoDuration,
2adfc7ea
C
230 userWatching: commonOptions.userWatching,
231 subtitle: commonOptions.subtitle,
f0a39880 232 videoCaptions: commonOptions.videoCaptions,
10f26f42
C
233 stopTime: commonOptions.stopTime,
234 isLive: commonOptions.isLive
2adfc7ea
C
235 }
236 }
237
4572c3d0
C
238 if (commonOptions.playlist) {
239 plugins.playlist = commonOptions.playlist
240 }
241
39aad8cc
C
242 if (commonOptions.enableHotkeys === true) {
243 PeertubePlayerManager.addHotkeysOptions(plugins)
244 }
09209296 245
9eccae74 246 if (isHLS) {
83fcadac 247 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
2adfc7ea 248
83fcadac 249 html5 = hlsjs.html5
2adfc7ea
C
250 }
251
6ec0b75b 252 if (mode === 'webtorrent') {
39aad8cc 253 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
09209296
C
254
255 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
256 autoplay = false
2adfc7ea
C
257 }
258
259 const videojsOptions = {
3b6f205c
C
260 html5,
261
2adfc7ea 262 // We don't use text track settings for now
f5fcd9f7 263 textTrackSettings: false as any, // FIXME: typings
2adfc7ea
C
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
72efdda5 271 autoplay: this.getAutoPlayValue(autoplay),
39aad8cc 272
2adfc7ea 273 poster: commonOptions.poster,
2adfc7ea 274 inactivityTimeout: commonOptions.inactivityTimeout,
08844775 275 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
39aad8cc 276
2adfc7ea 277 plugins,
39aad8cc 278
2adfc7ea
C
279 controlBar: {
280 children: this.getControlBarChildren(mode, {
281 captions: commonOptions.captions,
282 peertubeLink: commonOptions.peertubeLink,
1dc240a9 283 theaterButton: commonOptions.theaterButton,
a950e4c8
C
284
285 nextVideo: commonOptions.nextVideo,
286 hasNextVideo: commonOptions.hasNextVideo,
287
288 previousVideo: commonOptions.previousVideo,
289 hasPreviousVideo: commonOptions.hasPreviousVideo
f5fcd9f7 290 }) as any // FIXME: typings
2adfc7ea
C
291 }
292 }
293
39aad8cc
C
294 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
295 Object.assign(videojsOptions, { language: commonOptions.language })
296 }
2adfc7ea 297
39aad8cc
C
298 return videojsOptions
299 }
2adfc7ea 300
39aad8cc
C
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
fe9d0531 323 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
39aad8cc
C
324 console.log('We are on a cellular connection: disabling seeding.')
325 consumeOnly = true
326 }
327
328 const p2pMediaLoaderConfig = {
329 loader: {
330 trackerAnnounce,
25b7c847 331 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
39aad8cc 332 rtcConfig: getRtcConfig(),
c6c0fa6c 333 requiredSegmentsPriority: 1,
39aad8cc
C
334 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
335 useP2P: getStoredP2PEnabled(),
336 consumeOnly
337 },
338 segments: {
339 swarmId: p2pMediaLoaderOptions.playlistUrl
340 }
341 }
83fcadac 342 const hlsjs = {
39aad8cc 343 levelLabelHandler: (level: { height: number, width: number }) => {
dca0fe12
C
344 const resolution = Math.min(level.height || 0, level.width || 0)
345
346 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
053aed43
C
347 // We don't have files for live videos
348 if (!file) return level.height
39aad8cc
C
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,
e14de000 359 liveSyncDurationCount: 5,
39aad8cc 360 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
2adfc7ea 361 }
39aad8cc 362 }
2adfc7ea
C
363 }
364
83fcadac 365 const toAssign = { p2pMediaLoader, hlsjs }
39aad8cc
C
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
ebc8dd52
C
375 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
376 ? true
377 : false
378
39aad8cc 379 const webtorrent = {
ebc8dd52 380 autoplay,
39aad8cc
C
381 videoDuration: commonOptions.videoDuration,
382 playerElement: commonOptions.playerElement,
383 videoFiles: webtorrentOptions.videoFiles,
384 startTime: commonOptions.startTime
2adfc7ea
C
385 }
386
39aad8cc 387 Object.assign(plugins, { webtorrent })
2adfc7ea
C
388 }
389
390 private static getControlBarChildren (mode: PlayerMode, options: {
391 peertubeLink: boolean
a950e4c8
C
392 theaterButton: boolean
393 captions: boolean
394
1dc240a9 395 nextVideo?: Function
a950e4c8
C
396 hasNextVideo?: () => boolean
397
398 previousVideo?: Function
399 hasPreviousVideo?: () => boolean
2adfc7ea
C
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
a950e4c8
C
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 })
1dc240a9
RK
425 }
426
a950e4c8
C
427 Object.assign(children, { playToggle: {} })
428
1dc240a9 429 if (options.nextVideo) {
a950e4c8
C
430 const buttonOptions: NextPreviousVideoButtonOptions = {
431 type: 'next',
432 handler: options.nextVideo,
433 isDisabled: () => {
434 if (!options.hasNextVideo) return false
435
436 return !options.hasNextVideo()
1dc240a9 437 }
a950e4c8
C
438 }
439
440 Object.assign(children, {
441 'nextVideoButton': buttonOptions
1dc240a9
RK
442 })
443 }
444
445 Object.assign(children, {
2adfc7ea
C
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 }
1dc240a9 475 })
2adfc7ea
C
476
477 if (options.peertubeLink === true) {
478 Object.assign(children, {
479 'peerTubeLinkButton': {}
480 })
481 }
482
3d9a63d3 483 if (options.theaterButton === true) {
2adfc7ea
C
484 Object.assign(children, {
485 'theaterButton': {}
486 })
487 }
488
489 Object.assign(children, {
490 'fullscreenToggle': {}
491 })
492
493 return children
494 }
495
4097c6d6 496 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
2adfc7ea
C
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'),
7e37e111 506 listener: function (this: videojs.Player) {
f5fcd9f7 507 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
2adfc7ea
C
508 }
509 },
510 {
511 label: player.localize('Copy embed code'),
512 listener: () => {
4097c6d6 513 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
2adfc7ea
C
514 }
515 }
516 ]
517
518 if (mode === 'webtorrent') {
519 content.push({
520 label: player.localize('Copy magnet URI'),
7e37e111 521 listener: function (this: videojs.Player) {
f5fcd9f7 522 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
2adfc7ea
C
523 }
524 })
525 }
526
527 player.contextmenuUI({ content })
528 }
529
39aad8cc 530 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
e0b59721 531 const isNaked = (event: KeyboardEvent, key: string) =>
532 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
533
39aad8cc
C
534 Object.assign(plugins, {
535 hotkeys: {
7ede74ad
C
536 skipInitialFocus: true,
537 enableInactiveFocus: false,
538 captureDocumentHotkeys: true,
539 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
e85bfe96
C
540 const tagName = e.tagName.toLowerCase()
541 return e.id === 'content' || tagName === 'body' || tagName === 'video'
7ede74ad
C
542 },
543
39aad8cc
C
544 enableVolumeScroll: false,
545 enableModifiersForNumbers: false,
546
684cdacb 547 rewindKey: function (event: KeyboardEvent) {
548 return isNaked(event, 'ArrowLeft')
549 },
550
551 forwardKey: function (event: KeyboardEvent) {
552 return isNaked(event, 'ArrowRight')
553 },
554
39aad8cc
C
555 fullscreenKey: function (event: KeyboardEvent) {
556 // fullscreen with the f key or Ctrl+Enter
e0b59721 557 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
39aad8cc
C
558 },
559
39aad8cc
C
560 customKeys: {
561 increasePlaybackRateKey: {
562 key: function (event: KeyboardEvent) {
e0b59721 563 return isNaked(event, '>')
39aad8cc
C
564 },
565 handler: function (player: videojs.Player) {
f5fcd9f7
C
566 const newValue = Math.min(player.playbackRate() + 0.1, 5)
567 player.playbackRate(parseFloat(newValue.toFixed(2)))
39aad8cc
C
568 }
569 },
570 decreasePlaybackRateKey: {
571 key: function (event: KeyboardEvent) {
e0b59721 572 return isNaked(event, '<')
39aad8cc
C
573 },
574 handler: function (player: videojs.Player) {
f5fcd9f7
C
575 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
576 player.playbackRate(parseFloat(newValue.toFixed(2)))
39aad8cc
C
577 }
578 },
579 frameByFrame: {
580 key: function (event: KeyboardEvent) {
e0b59721 581 return isNaked(event, '.')
39aad8cc
C
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 }
64228474 594
72efdda5
C
595 private static getAutoPlayValue (autoplay: any) {
596 if (autoplay !== true) return autoplay
597
ebc8dd52
C
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()) {
9eccae74
C
601 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
602 }
64228474
C
603
604 return 'play'
605 }
2adfc7ea
C
606}
607
608// ############################################################################
609
610export {
611 videojs
612}