]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - 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
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-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 videojs from 'video.js'
22
23 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
24 import { VideoFile } from '../../../../shared/models/videos'
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 { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings'
30 import { TranslationsManager } from './translations-manager'
31 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig, isIOS, isSafari } from './utils'
32
33 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
34 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
35
36 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
37 // Change Captions to Subtitles/CC
38 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
39 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
40 CaptionsButton.prototype.label_ = ' '
41
42 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
43
44 export type WebtorrentOptions = {
45 videoFiles: VideoFile[]
46 }
47
48 export type P2PMediaLoaderOptions = {
49 playlistUrl: string
50 segmentsSha256Url: string
51 trackerAnnounce: string[]
52 redundancyBaseUrls: string[]
53 videoFiles: VideoFile[]
54 }
55
56 export interface CustomizationOptions {
57 startTime: number | string
58 stopTime: number | string
59
60 controls?: boolean
61 muted?: boolean
62 loop?: boolean
63 subtitle?: string
64 resume?: string
65
66 peertubeLink: boolean
67 }
68
69 export interface CommonOptions extends CustomizationOptions {
70 playerElement: HTMLVideoElement
71 onPlayerElementChange: (element: HTMLVideoElement) => void
72
73 autoplay: boolean
74 nextVideo?: Function
75 videoDuration: number
76 enableHotkeys: boolean
77 inactivityTimeout: number
78 poster: string
79
80 theaterButton: boolean
81 captions: boolean
82
83 videoViewUrl: string
84 embedUrl: string
85
86 language?: string
87
88 videoCaptions: VideoJSCaption[]
89
90 userWatching?: UserWatching
91
92 serverUrl: string
93 }
94
95 export type PeertubePlayerManagerOptions = {
96 common: CommonOptions,
97 webtorrent: WebtorrentOptions,
98 p2pMediaLoader?: P2PMediaLoaderOptions
99 }
100
101 export class PeertubePlayerManager {
102 private static playerElementClassName: string
103 private static onPlayerChange: (player: videojs.Player) => void
104
105 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
106 let p2pMediaLoader: any
107
108 this.onPlayerChange = onPlayerChange
109 this.playerElementClassName = options.common.playerElement.className
110
111 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
112 if (mode === 'p2p-media-loader') {
113 [ p2pMediaLoader ] = await Promise.all([
114 import('p2p-media-loader-hlsjs'),
115 import('./p2p-media-loader/p2p-media-loader-plugin')
116 ])
117 }
118
119 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
120
121 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
122
123 const self = this
124 return new Promise(res => {
125 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
126 const player = this
127
128 let alreadyFallback = false
129
130 player.tech(true).one('error', () => {
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 })
139
140 self.addContextMenu(mode, player, options.common.embedUrl)
141
142 player.bezels()
143
144 return res(player)
145 })
146 })
147 }
148
149 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
150 if (currentMode === 'webtorrent') return
151
152 console.log('Fallback to webtorrent.')
153
154 const newVideoElement = document.createElement('video')
155 newVideoElement.className = this.playerElementClassName
156
157 // VideoJS wraps our video element inside a div
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
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
175 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
176 const player = this
177
178 self.addContextMenu(mode, player, options.common.embedUrl)
179
180 PeertubePlayerManager.onPlayerChange(player)
181 })
182 }
183
184 private static getVideojsOptions (
185 mode: PlayerMode,
186 options: PeertubePlayerManagerOptions,
187 p2pMediaLoaderModule?: any
188 ): videojs.PlayerOptions {
189 const commonOptions = options.common
190
191 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
192 let html5 = {}
193
194 const plugins: VideoJSPluginOptions = {
195 peertube: {
196 mode,
197 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
198 videoViewUrl: commonOptions.videoViewUrl,
199 videoDuration: commonOptions.videoDuration,
200 userWatching: commonOptions.userWatching,
201 subtitle: commonOptions.subtitle,
202 videoCaptions: commonOptions.videoCaptions,
203 stopTime: commonOptions.stopTime
204 }
205 }
206
207 if (commonOptions.enableHotkeys === true) {
208 PeertubePlayerManager.addHotkeysOptions(plugins)
209 }
210
211 if (mode === 'p2p-media-loader') {
212 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
213
214 html5 = hlsjs.html5
215 }
216
217 if (mode === 'webtorrent') {
218 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
219
220 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
221 autoplay = false
222 }
223
224 const videojsOptions = {
225 html5,
226
227 // We don't use text track settings for now
228 textTrackSettings: false as any, // FIXME: typings
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
236 autoplay: this.getAutoPlayValue(autoplay),
237
238 poster: commonOptions.poster,
239 inactivityTimeout: commonOptions.inactivityTimeout,
240 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
241
242 plugins,
243
244 controlBar: {
245 children: this.getControlBarChildren(mode, {
246 captions: commonOptions.captions,
247 peertubeLink: commonOptions.peertubeLink,
248 theaterButton: commonOptions.theaterButton,
249 nextVideo: commonOptions.nextVideo
250 }) as any // FIXME: typings
251 }
252 }
253
254 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
255 Object.assign(videojsOptions, { language: commonOptions.language })
256 }
257
258 return videojsOptions
259 }
260
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
283 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
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 }
302 const hlsjs = {
303 levelLabelHandler: (level: { height: number, width: number }) => {
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 }
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()
323 }
324 }
325 }
326
327 const toAssign = { p2pMediaLoader, hlsjs }
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
343 }
344
345 Object.assign(plugins, { webtorrent })
346 }
347
348 private static getControlBarChildren (mode: PlayerMode, options: {
349 peertubeLink: boolean
350 theaterButton: boolean,
351 captions: boolean,
352 nextVideo?: Function
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 = {
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, {
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 }
404 })
405
406 if (options.peertubeLink === true) {
407 Object.assign(children, {
408 'peerTubeLinkButton': {}
409 })
410 }
411
412 if (options.theaterButton === true) {
413 Object.assign(children, {
414 'theaterButton': {}
415 })
416 }
417
418 Object.assign(children, {
419 'fullscreenToggle': {}
420 })
421
422 return children
423 }
424
425 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
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'),
435 listener: function (this: videojs.Player) {
436 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
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'),
450 listener: function (this: videojs.Player) {
451 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
452 }
453 })
454 }
455
456 player.contextmenuUI({ content })
457 }
458
459 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
460 Object.assign(plugins, {
461 hotkeys: {
462 skipInitialFocus: true,
463 enableInactiveFocus: false,
464 captureDocumentHotkeys: true,
465 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
466 const tagName = e.tagName.toLowerCase()
467 return e.id === 'content' || tagName === 'body' || tagName === 'video'
468 },
469
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) {
497 const newValue = Math.min(player.playbackRate() + 0.1, 5)
498 player.playbackRate(parseFloat(newValue.toFixed(2)))
499 }
500 },
501 decreasePlaybackRateKey: {
502 key: function (event: KeyboardEvent) {
503 return event.key === '<'
504 },
505 handler: function (player: videojs.Player) {
506 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
507 player.playbackRate(parseFloat(newValue.toFixed(2)))
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 }
525
526 private static getAutoPlayValue (autoplay: any) {
527 if (autoplay !== true) return autoplay
528
529 // Giving up with iOS
530 if (isIOS()) return false
531
532 // We have issues with autoplay and Safari.
533 // any that tries to play using auto mute seems to work
534 if (isSafari()) return 'any'
535
536 return 'play'
537 }
538 }
539
540 // ############################################################################
541
542 export {
543 videojs
544 }