]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
Fix console error when watching a video
[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-pt'
4 import 'videojs-contrib-quality-levels'
5 import './upnext/end-card'
6 import './upnext/upnext-plugin'
7 import './stats/stats-card'
8 import './stats/stats-plugin'
9 import './bezels/bezels-plugin'
10 import './peertube-plugin'
11 import './videojs-components/next-previous-video-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-link-button'
14 import './videojs-components/peertube-load-progress-bar'
15 import './videojs-components/resolution-menu-button'
16 import './videojs-components/resolution-menu-item'
17 import './videojs-components/settings-dialog'
18 import './videojs-components/settings-menu-button'
19 import './videojs-components/settings-menu-item'
20 import './videojs-components/settings-panel'
21 import './videojs-components/settings-panel-child'
22 import './videojs-components/theater-button'
23 import './playlist/playlist-plugin'
24 import videojs from 'video.js'
25 import { PluginsManager } from '@root-helpers/plugins-manager'
26 import { isDefaultLocale } from '@shared/core-utils/i18n'
27 import { VideoFile } from '@shared/models'
28 import { copyToClipboard } from '../../root-helpers/utils'
29 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
30 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
31 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
32 import { getStoredP2PEnabled } from './peertube-player-local-storage'
33 import {
34 NextPreviousVideoButtonOptions,
35 P2PMediaLoaderPluginOptions,
36 PlaylistPluginOptions,
37 UserWatching,
38 VideoJSCaption,
39 VideoJSPluginOptions
40 } from './peertube-videojs-typings'
41 import { TranslationsManager } from './translations-manager'
42 import { buildVideoLink, buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isSafari } from './utils'
43
44 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
45 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
46
47 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
48 // Change Captions to Subtitles/CC
49 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
50 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
51 CaptionsButton.prototype.label_ = ' '
52
53 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
54
55 export type WebtorrentOptions = {
56 videoFiles: VideoFile[]
57 }
58
59 export type P2PMediaLoaderOptions = {
60 playlistUrl: string
61 segmentsSha256Url: string
62 trackerAnnounce: string[]
63 redundancyBaseUrls: string[]
64 videoFiles: VideoFile[]
65 }
66
67 export interface CustomizationOptions {
68 startTime: number | string
69 stopTime: number | string
70
71 controls?: boolean
72 muted?: boolean
73 loop?: boolean
74 subtitle?: string
75 resume?: string
76
77 peertubeLink: boolean
78 }
79
80 export interface CommonOptions extends CustomizationOptions {
81 playerElement: HTMLVideoElement
82 onPlayerElementChange: (element: HTMLVideoElement) => void
83
84 autoplay: boolean
85
86 nextVideo?: () => void
87 hasNextVideo?: () => boolean
88
89 previousVideo?: () => void
90 hasPreviousVideo?: () => boolean
91
92 playlist?: PlaylistPluginOptions
93
94 videoDuration: number
95 enableHotkeys: boolean
96 inactivityTimeout: number
97 poster: string
98
99 theaterButton: boolean
100 captions: boolean
101
102 videoViewUrl: string
103 embedUrl: string
104 embedTitle: string
105
106 isLive: boolean
107
108 language?: string
109
110 videoCaptions: VideoJSCaption[]
111
112 videoUUID: string
113
114 userWatching?: UserWatching
115
116 serverUrl: string
117 }
118
119 export type PeertubePlayerManagerOptions = {
120 common: CommonOptions
121 webtorrent: WebtorrentOptions
122 p2pMediaLoader?: P2PMediaLoaderOptions
123
124 pluginsManager: PluginsManager
125 }
126
127 export class PeertubePlayerManager {
128 private static playerElementClassName: string
129 private static onPlayerChange: (player: videojs.Player) => void
130 private static alreadyPlayed = false
131 private static pluginsManager: PluginsManager
132
133 static initState () {
134 PeertubePlayerManager.alreadyPlayed = false
135 }
136
137 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
138 this.pluginsManager = options.pluginsManager
139
140 let p2pMediaLoader: any
141
142 this.onPlayerChange = onPlayerChange
143 this.playerElementClassName = options.common.playerElement.className
144
145 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
146 if (mode === 'p2p-media-loader') {
147 [ p2pMediaLoader ] = await Promise.all([
148 import('p2p-media-loader-hlsjs'),
149 import('./p2p-media-loader/p2p-media-loader-plugin')
150 ])
151 }
152
153 const videojsOptions = await this.getVideojsOptions(mode, options, p2pMediaLoader)
154
155 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
156
157 const self = this
158 return new Promise(res => {
159 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
160 const player = this
161
162 let alreadyFallback = false
163
164 player.tech(true).one('error', () => {
165 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
166 alreadyFallback = true
167 })
168
169 player.one('error', () => {
170 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
171 alreadyFallback = true
172 })
173
174 player.one('play', () => {
175 PeertubePlayerManager.alreadyPlayed = true
176 })
177
178 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
179
180 player.bezels()
181 player.stats({
182 videoUUID: options.common.videoUUID,
183 videoIsLive: options.common.isLive,
184 mode
185 })
186
187 return res(player)
188 })
189 })
190 }
191
192 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
193 if (currentMode === 'webtorrent') return
194
195 console.log('Fallback to webtorrent.')
196
197 const newVideoElement = document.createElement('video')
198 newVideoElement.className = this.playerElementClassName
199
200 // VideoJS wraps our video element inside a div
201 let currentParentPlayerElement = options.common.playerElement.parentNode
202 // Fix on IOS, don't ask me why
203 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
204
205 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
206
207 options.common.playerElement = newVideoElement
208 options.common.onPlayerElementChange(newVideoElement)
209
210 player.dispose()
211
212 await import('./webtorrent/webtorrent-plugin')
213
214 const mode = 'webtorrent'
215 const videojsOptions = await this.getVideojsOptions(mode, options)
216
217 const self = this
218 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
219 const player = this
220
221 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
222
223 PeertubePlayerManager.onPlayerChange(player)
224 })
225 }
226
227 private static async getVideojsOptions (
228 mode: PlayerMode,
229 options: PeertubePlayerManagerOptions,
230 p2pMediaLoaderModule?: any
231 ): Promise<videojs.PlayerOptions> {
232 const commonOptions = options.common
233 const isHLS = mode === 'p2p-media-loader'
234
235 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
236 const html5 = {
237 preloadTextTracks: false
238 }
239
240 const plugins: VideoJSPluginOptions = {
241 peertube: {
242 mode,
243 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
244 videoViewUrl: commonOptions.videoViewUrl,
245 videoDuration: commonOptions.videoDuration,
246 userWatching: commonOptions.userWatching,
247 subtitle: commonOptions.subtitle,
248 videoCaptions: commonOptions.videoCaptions,
249 stopTime: commonOptions.stopTime,
250 isLive: commonOptions.isLive,
251 videoUUID: commonOptions.videoUUID
252 }
253 }
254
255 if (commonOptions.playlist) {
256 plugins.playlist = commonOptions.playlist
257 }
258
259 if (commonOptions.enableHotkeys === true) {
260 PeertubePlayerManager.addHotkeysOptions(plugins)
261 }
262
263 if (isHLS) {
264 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
265
266 Object.assign(html5, hlsjs.html5)
267 }
268
269 if (mode === 'webtorrent') {
270 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
271
272 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
273 autoplay = false
274 }
275
276 const videojsOptions = {
277 html5,
278
279 // We don't use text track settings for now
280 textTrackSettings: false as any, // FIXME: typings
281 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
282 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
283
284 muted: commonOptions.muted !== undefined
285 ? commonOptions.muted
286 : undefined, // Undefined so the player knows it has to check the local storage
287
288 autoplay: this.getAutoPlayValue(autoplay),
289
290 poster: commonOptions.poster,
291 inactivityTimeout: commonOptions.inactivityTimeout,
292 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
293
294 plugins,
295
296 controlBar: {
297 children: this.getControlBarChildren(mode, {
298 captions: commonOptions.captions,
299 peertubeLink: commonOptions.peertubeLink,
300 theaterButton: commonOptions.theaterButton,
301
302 nextVideo: commonOptions.nextVideo,
303 hasNextVideo: commonOptions.hasNextVideo,
304
305 previousVideo: commonOptions.previousVideo,
306 hasPreviousVideo: commonOptions.hasPreviousVideo
307 }) as any // FIXME: typings
308 }
309 }
310
311 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
312 Object.assign(videojsOptions, { language: commonOptions.language })
313 }
314
315 return this.pluginsManager.runHook('filter:internal.player.videojs.options.result', videojsOptions)
316 }
317
318 private static addP2PMediaLoaderOptions (
319 plugins: VideoJSPluginOptions,
320 options: PeertubePlayerManagerOptions,
321 p2pMediaLoaderModule: any
322 ) {
323 const p2pMediaLoaderOptions = options.p2pMediaLoader
324 const commonOptions = options.common
325
326 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
327 .filter(t => t.startsWith('ws'))
328
329 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
330
331 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
332 redundancyUrlManager,
333 type: 'application/x-mpegURL',
334 startTime: commonOptions.startTime,
335 src: p2pMediaLoaderOptions.playlistUrl
336 }
337
338 let consumeOnly = false
339 // FIXME: typings
340 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
341 console.log('We are on a cellular connection: disabling seeding.')
342 consumeOnly = true
343 }
344
345 const p2pMediaLoaderConfig = {
346 loader: {
347 trackerAnnounce,
348 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
349 rtcConfig: getRtcConfig(),
350 requiredSegmentsPriority: 1,
351 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
352 useP2P: getStoredP2PEnabled(),
353 consumeOnly
354 },
355 segments: {
356 swarmId: p2pMediaLoaderOptions.playlistUrl
357 }
358 }
359 const hlsjs = {
360 levelLabelHandler: (level: { height: number, width: number }) => {
361 const resolution = Math.min(level.height || 0, level.width || 0)
362
363 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
364 // We don't have files for live videos
365 if (!file) return level.height
366
367 let label = file.resolution.label
368 if (file.fps >= 50) label += file.fps
369
370 return label
371 },
372 html5: {
373 hlsjsConfig: {
374 capLevelToPlayerSize: true,
375 autoStartLoad: false,
376 liveSyncDurationCount: 5,
377 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
378 }
379 }
380 }
381
382 const toAssign = { p2pMediaLoader, hlsjs }
383 Object.assign(plugins, toAssign)
384
385 return toAssign
386 }
387
388 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
389 const commonOptions = options.common
390 const webtorrentOptions = options.webtorrent
391
392 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
393 ? true
394 : false
395
396 const webtorrent = {
397 autoplay,
398 videoDuration: commonOptions.videoDuration,
399 playerElement: commonOptions.playerElement,
400 videoFiles: webtorrentOptions.videoFiles,
401 startTime: commonOptions.startTime
402 }
403
404 Object.assign(plugins, { webtorrent })
405 }
406
407 private static getControlBarChildren (mode: PlayerMode, options: {
408 peertubeLink: boolean
409 theaterButton: boolean
410 captions: boolean
411
412 nextVideo?: Function
413 hasNextVideo?: () => boolean
414
415 previousVideo?: Function
416 hasPreviousVideo?: () => boolean
417 }) {
418 const settingEntries = []
419 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
420
421 // Keep an order
422 settingEntries.push('playbackRateMenuButton')
423 if (options.captions === true) settingEntries.push('captionsButton')
424 settingEntries.push('resolutionMenuButton')
425
426 const children = {}
427
428 if (options.previousVideo) {
429 const buttonOptions: NextPreviousVideoButtonOptions = {
430 type: 'previous',
431 handler: options.previousVideo,
432 isDisabled: () => {
433 if (!options.hasPreviousVideo) return false
434
435 return !options.hasPreviousVideo()
436 }
437 }
438
439 Object.assign(children, {
440 'previousVideoButton': buttonOptions
441 })
442 }
443
444 Object.assign(children, { playToggle: {} })
445
446 if (options.nextVideo) {
447 const buttonOptions: NextPreviousVideoButtonOptions = {
448 type: 'next',
449 handler: options.nextVideo,
450 isDisabled: () => {
451 if (!options.hasNextVideo) return false
452
453 return !options.hasNextVideo()
454 }
455 }
456
457 Object.assign(children, {
458 'nextVideoButton': buttonOptions
459 })
460 }
461
462 Object.assign(children, {
463 'currentTimeDisplay': {},
464 'timeDivider': {},
465 'durationDisplay': {},
466 'liveDisplay': {},
467
468 'flexibleWidthSpacer': {},
469 'progressControl': {
470 children: {
471 'seekBar': {
472 children: {
473 [loadProgressBar]: {},
474 'mouseTimeDisplay': {},
475 'playProgressBar': {}
476 }
477 }
478 }
479 },
480
481 'p2PInfoButton': {},
482
483 'muteToggle': {},
484 'volumeControl': {},
485
486 'settingsButton': {
487 setup: {
488 maxHeightOffset: 40
489 },
490 entries: settingEntries
491 }
492 })
493
494 if (options.peertubeLink === true) {
495 Object.assign(children, {
496 'peerTubeLinkButton': {}
497 })
498 }
499
500 if (options.theaterButton === true) {
501 Object.assign(children, {
502 'theaterButton': {}
503 })
504 }
505
506 Object.assign(children, {
507 'fullscreenToggle': {}
508 })
509
510 return children
511 }
512
513 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
514 const content = () => {
515 const isLoopEnabled = player.options_['loop']
516 const items = [
517 {
518 icon: 'repeat',
519 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
520 listener: function () {
521 player.options_['loop'] = !isLoopEnabled
522 }
523 },
524 {
525 label: player.localize('Copy the video URL'),
526 listener: function () {
527 copyToClipboard(buildVideoLink())
528 }
529 },
530 {
531 label: player.localize('Copy the video URL at the current time'),
532 listener: function (this: videojs.Player) {
533 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
534 }
535 },
536 {
537 icon: 'code',
538 label: player.localize('Copy embed code'),
539 listener: () => {
540 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
541 }
542 }
543 ]
544
545 if (mode === 'webtorrent') {
546 items.push({
547 label: player.localize('Copy magnet URI'),
548 listener: function (this: videojs.Player) {
549 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
550 }
551 })
552 }
553
554 items.push({
555 icon: 'info',
556 label: player.localize('Stats for nerds'),
557 listener: () => {
558 player.stats().show()
559 }
560 })
561
562 return items.map(i => ({
563 ...i,
564 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
565 }))
566 }
567
568 // adding the menu
569 player.contextmenuUI({ content })
570 }
571
572 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
573 const isNaked = (event: KeyboardEvent, key: string) =>
574 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
575
576 Object.assign(plugins, {
577 hotkeys: {
578 skipInitialFocus: true,
579 enableInactiveFocus: false,
580 captureDocumentHotkeys: true,
581 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
582 const tagName = e.tagName.toLowerCase()
583 return e.id === 'content' || tagName === 'body' || tagName === 'video'
584 },
585
586 enableVolumeScroll: false,
587 enableModifiersForNumbers: false,
588
589 rewindKey: function (event: KeyboardEvent) {
590 return isNaked(event, 'ArrowLeft')
591 },
592
593 forwardKey: function (event: KeyboardEvent) {
594 return isNaked(event, 'ArrowRight')
595 },
596
597 fullscreenKey: function (event: KeyboardEvent) {
598 // fullscreen with the f key or Ctrl+Enter
599 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
600 },
601
602 customKeys: {
603 increasePlaybackRateKey: {
604 key: function (event: KeyboardEvent) {
605 return isNaked(event, '>')
606 },
607 handler: function (player: videojs.Player) {
608 const newValue = Math.min(player.playbackRate() + 0.1, 5)
609 player.playbackRate(parseFloat(newValue.toFixed(2)))
610 }
611 },
612 decreasePlaybackRateKey: {
613 key: function (event: KeyboardEvent) {
614 return isNaked(event, '<')
615 },
616 handler: function (player: videojs.Player) {
617 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
618 player.playbackRate(parseFloat(newValue.toFixed(2)))
619 }
620 },
621 frameByFrame: {
622 key: function (event: KeyboardEvent) {
623 return isNaked(event, '.')
624 },
625 handler: function (player: videojs.Player) {
626 player.pause()
627 // Calculate movement distance (assuming 30 fps)
628 const dist = 1 / 30
629 player.currentTime(player.currentTime() + dist)
630 }
631 }
632 }
633 }
634 })
635 }
636
637 private static getAutoPlayValue (autoplay: any) {
638 if (autoplay !== true) return autoplay
639
640 // On first play, disable autoplay to avoid issues
641 // But if the player already played videos, we can safely autoplay next ones
642 if (isIOS() || isSafari()) {
643 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
644 }
645
646 return 'play'
647 }
648 }
649
650 // ############################################################################
651
652 export {
653 videojs
654 }