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