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