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