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