]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
Resume videos for non-logged in users (#3885)
[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 embedTitle: string
102
103 isLive: boolean
104
105 language?: string
106
107 videoCaptions: VideoJSCaption[]
108
109 videoUUID: string
110
111 userWatching?: UserWatching
112
113 serverUrl: string
114 }
115
116 export type PeertubePlayerManagerOptions = {
117 common: CommonOptions,
118 webtorrent: WebtorrentOptions,
119 p2pMediaLoader?: P2PMediaLoaderOptions
120 }
121
122 export class PeertubePlayerManager {
123 private static playerElementClassName: string
124 private static onPlayerChange: (player: videojs.Player) => void
125
126 private static alreadyPlayed = false
127
128 static initState () {
129 PeertubePlayerManager.alreadyPlayed = false
130 }
131
132 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
133 let p2pMediaLoader: any
134
135 this.onPlayerChange = onPlayerChange
136 this.playerElementClassName = options.common.playerElement.className
137
138 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
139 if (mode === 'p2p-media-loader') {
140 [ p2pMediaLoader ] = await Promise.all([
141 import('p2p-media-loader-hlsjs'),
142 import('./p2p-media-loader/p2p-media-loader-plugin')
143 ])
144 }
145
146 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
147
148 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
149
150 const self = this
151 return new Promise(res => {
152 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
153 const player = this
154
155 let alreadyFallback = false
156
157 player.tech(true).one('error', () => {
158 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
159 alreadyFallback = true
160 })
161
162 player.one('error', () => {
163 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
164 alreadyFallback = true
165 })
166
167 player.one('play', () => {
168 PeertubePlayerManager.alreadyPlayed = true
169 })
170
171 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
172
173 player.bezels()
174
175 return res(player)
176 })
177 })
178 }
179
180 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
181 if (currentMode === 'webtorrent') return
182
183 console.log('Fallback to webtorrent.')
184
185 const newVideoElement = document.createElement('video')
186 newVideoElement.className = this.playerElementClassName
187
188 // VideoJS wraps our video element inside a div
189 let currentParentPlayerElement = options.common.playerElement.parentNode
190 // Fix on IOS, don't ask me why
191 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
192
193 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
194
195 options.common.playerElement = newVideoElement
196 options.common.onPlayerElementChange(newVideoElement)
197
198 player.dispose()
199
200 await import('./webtorrent/webtorrent-plugin')
201
202 const mode = 'webtorrent'
203 const videojsOptions = this.getVideojsOptions(mode, options)
204
205 const self = this
206 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
207 const player = this
208
209 self.addContextMenu(mode, player, options.common.embedUrl, options.common.embedTitle)
210
211 PeertubePlayerManager.onPlayerChange(player)
212 })
213 }
214
215 private static getVideojsOptions (
216 mode: PlayerMode,
217 options: PeertubePlayerManagerOptions,
218 p2pMediaLoaderModule?: any
219 ): videojs.PlayerOptions {
220 const commonOptions = options.common
221 const isHLS = mode === 'p2p-media-loader'
222
223 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
224 let html5 = {}
225
226 const plugins: VideoJSPluginOptions = {
227 peertube: {
228 mode,
229 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
230 videoViewUrl: commonOptions.videoViewUrl,
231 videoDuration: commonOptions.videoDuration,
232 userWatching: commonOptions.userWatching,
233 subtitle: commonOptions.subtitle,
234 videoCaptions: commonOptions.videoCaptions,
235 stopTime: commonOptions.stopTime,
236 isLive: commonOptions.isLive,
237 videoUUID: commonOptions.videoUUID
238 }
239 }
240
241 if (commonOptions.playlist) {
242 plugins.playlist = commonOptions.playlist
243 }
244
245 if (commonOptions.enableHotkeys === true) {
246 PeertubePlayerManager.addHotkeysOptions(plugins)
247 }
248
249 if (isHLS) {
250 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
251
252 html5 = hlsjs.html5
253 }
254
255 if (mode === 'webtorrent') {
256 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
257
258 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
259 autoplay = false
260 }
261
262 const videojsOptions = {
263 html5,
264
265 // We don't use text track settings for now
266 textTrackSettings: false as any, // FIXME: typings
267 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
268 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
269
270 muted: commonOptions.muted !== undefined
271 ? commonOptions.muted
272 : undefined, // Undefined so the player knows it has to check the local storage
273
274 autoplay: this.getAutoPlayValue(autoplay),
275
276 poster: commonOptions.poster,
277 inactivityTimeout: commonOptions.inactivityTimeout,
278 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
279
280 plugins,
281
282 controlBar: {
283 children: this.getControlBarChildren(mode, {
284 captions: commonOptions.captions,
285 peertubeLink: commonOptions.peertubeLink,
286 theaterButton: commonOptions.theaterButton,
287
288 nextVideo: commonOptions.nextVideo,
289 hasNextVideo: commonOptions.hasNextVideo,
290
291 previousVideo: commonOptions.previousVideo,
292 hasPreviousVideo: commonOptions.hasPreviousVideo
293 }) as any // FIXME: typings
294 }
295 }
296
297 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
298 Object.assign(videojsOptions, { language: commonOptions.language })
299 }
300
301 return videojsOptions
302 }
303
304 private static addP2PMediaLoaderOptions (
305 plugins: VideoJSPluginOptions,
306 options: PeertubePlayerManagerOptions,
307 p2pMediaLoaderModule: any
308 ) {
309 const p2pMediaLoaderOptions = options.p2pMediaLoader
310 const commonOptions = options.common
311
312 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
313 .filter(t => t.startsWith('ws'))
314
315 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
316
317 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
318 redundancyUrlManager,
319 type: 'application/x-mpegURL',
320 startTime: commonOptions.startTime,
321 src: p2pMediaLoaderOptions.playlistUrl
322 }
323
324 let consumeOnly = false
325 // FIXME: typings
326 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
327 console.log('We are on a cellular connection: disabling seeding.')
328 consumeOnly = true
329 }
330
331 const p2pMediaLoaderConfig = {
332 loader: {
333 trackerAnnounce,
334 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url, options.common.isLive),
335 rtcConfig: getRtcConfig(),
336 requiredSegmentsPriority: 1,
337 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
338 useP2P: getStoredP2PEnabled(),
339 consumeOnly
340 },
341 segments: {
342 swarmId: p2pMediaLoaderOptions.playlistUrl
343 }
344 }
345 const hlsjs = {
346 levelLabelHandler: (level: { height: number, width: number }) => {
347 const resolution = Math.min(level.height || 0, level.width || 0)
348
349 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
350 // We don't have files for live videos
351 if (!file) return level.height
352
353 let label = file.resolution.label
354 if (file.fps >= 50) label += file.fps
355
356 return label
357 },
358 html5: {
359 hlsjsConfig: {
360 capLevelToPlayerSize: true,
361 autoStartLoad: false,
362 liveSyncDurationCount: 5,
363 loader: new p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
364 }
365 }
366 }
367
368 const toAssign = { p2pMediaLoader, hlsjs }
369 Object.assign(plugins, toAssign)
370
371 return toAssign
372 }
373
374 private static addWebTorrentOptions (plugins: VideoJSPluginOptions, options: PeertubePlayerManagerOptions) {
375 const commonOptions = options.common
376 const webtorrentOptions = options.webtorrent
377
378 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
379 ? true
380 : false
381
382 const webtorrent = {
383 autoplay,
384 videoDuration: commonOptions.videoDuration,
385 playerElement: commonOptions.playerElement,
386 videoFiles: webtorrentOptions.videoFiles,
387 startTime: commonOptions.startTime
388 }
389
390 Object.assign(plugins, { webtorrent })
391 }
392
393 private static getControlBarChildren (mode: PlayerMode, options: {
394 peertubeLink: boolean
395 theaterButton: boolean
396 captions: boolean
397
398 nextVideo?: Function
399 hasNextVideo?: () => boolean
400
401 previousVideo?: Function
402 hasPreviousVideo?: () => boolean
403 }) {
404 const settingEntries = []
405 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
406
407 // Keep an order
408 settingEntries.push('playbackRateMenuButton')
409 if (options.captions === true) settingEntries.push('captionsButton')
410 settingEntries.push('resolutionMenuButton')
411
412 const children = {}
413
414 if (options.previousVideo) {
415 const buttonOptions: NextPreviousVideoButtonOptions = {
416 type: 'previous',
417 handler: options.previousVideo,
418 isDisabled: () => {
419 if (!options.hasPreviousVideo) return false
420
421 return !options.hasPreviousVideo()
422 }
423 }
424
425 Object.assign(children, {
426 'previousVideoButton': buttonOptions
427 })
428 }
429
430 Object.assign(children, { playToggle: {} })
431
432 if (options.nextVideo) {
433 const buttonOptions: NextPreviousVideoButtonOptions = {
434 type: 'next',
435 handler: options.nextVideo,
436 isDisabled: () => {
437 if (!options.hasNextVideo) return false
438
439 return !options.hasNextVideo()
440 }
441 }
442
443 Object.assign(children, {
444 'nextVideoButton': buttonOptions
445 })
446 }
447
448 Object.assign(children, {
449 'currentTimeDisplay': {},
450 'timeDivider': {},
451 'durationDisplay': {},
452 'liveDisplay': {},
453
454 'flexibleWidthSpacer': {},
455 'progressControl': {
456 children: {
457 'seekBar': {
458 children: {
459 [loadProgressBar]: {},
460 'mouseTimeDisplay': {},
461 'playProgressBar': {}
462 }
463 }
464 }
465 },
466
467 'p2PInfoButton': {},
468
469 'muteToggle': {},
470 'volumeControl': {},
471
472 'settingsButton': {
473 setup: {
474 maxHeightOffset: 40
475 },
476 entries: settingEntries
477 }
478 })
479
480 if (options.peertubeLink === true) {
481 Object.assign(children, {
482 'peerTubeLinkButton': {}
483 })
484 }
485
486 if (options.theaterButton === true) {
487 Object.assign(children, {
488 'theaterButton': {}
489 })
490 }
491
492 Object.assign(children, {
493 'fullscreenToggle': {}
494 })
495
496 return children
497 }
498
499 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string, videoEmbedTitle: string) {
500 const content = [
501 {
502 label: player.localize('Copy the video URL'),
503 listener: function () {
504 copyToClipboard(buildVideoLink())
505 }
506 },
507 {
508 label: player.localize('Copy the video URL at the current time'),
509 listener: function (this: videojs.Player) {
510 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
511 }
512 },
513 {
514 label: player.localize('Copy embed code'),
515 listener: () => {
516 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl, videoEmbedTitle))
517 }
518 }
519 ]
520
521 if (mode === 'webtorrent') {
522 content.push({
523 label: player.localize('Copy magnet URI'),
524 listener: function (this: videojs.Player) {
525 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
526 }
527 })
528 }
529
530 player.contextmenuUI({ content })
531 }
532
533 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
534 const isNaked = (event: KeyboardEvent, key: string) =>
535 (!event.ctrlKey && !event.altKey && !event.metaKey && !event.shiftKey && event.key === key)
536
537 Object.assign(plugins, {
538 hotkeys: {
539 skipInitialFocus: true,
540 enableInactiveFocus: false,
541 captureDocumentHotkeys: true,
542 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
543 const tagName = e.tagName.toLowerCase()
544 return e.id === 'content' || tagName === 'body' || tagName === 'video'
545 },
546
547 enableVolumeScroll: false,
548 enableModifiersForNumbers: false,
549
550 rewindKey: function (event: KeyboardEvent) {
551 return isNaked(event, 'ArrowLeft')
552 },
553
554 forwardKey: function (event: KeyboardEvent) {
555 return isNaked(event, 'ArrowRight')
556 },
557
558 fullscreenKey: function (event: KeyboardEvent) {
559 // fullscreen with the f key or Ctrl+Enter
560 return isNaked(event, 'f') || (!event.altKey && event.ctrlKey && event.key === 'Enter')
561 },
562
563 customKeys: {
564 increasePlaybackRateKey: {
565 key: function (event: KeyboardEvent) {
566 return isNaked(event, '>')
567 },
568 handler: function (player: videojs.Player) {
569 const newValue = Math.min(player.playbackRate() + 0.1, 5)
570 player.playbackRate(parseFloat(newValue.toFixed(2)))
571 }
572 },
573 decreasePlaybackRateKey: {
574 key: function (event: KeyboardEvent) {
575 return isNaked(event, '<')
576 },
577 handler: function (player: videojs.Player) {
578 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
579 player.playbackRate(parseFloat(newValue.toFixed(2)))
580 }
581 },
582 frameByFrame: {
583 key: function (event: KeyboardEvent) {
584 return isNaked(event, '.')
585 },
586 handler: function (player: videojs.Player) {
587 player.pause()
588 // Calculate movement distance (assuming 30 fps)
589 const dist = 1 / 30
590 player.currentTime(player.currentTime() + dist)
591 }
592 }
593 }
594 }
595 })
596 }
597
598 private static getAutoPlayValue (autoplay: any) {
599 if (autoplay !== true) return autoplay
600
601 // On first play, disable autoplay to avoid issues
602 // But if the player already played videos, we can safely autoplay next ones
603 if (isIOS() || isSafari()) {
604 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
605 }
606
607 return 'play'
608 }
609 }
610
611 // ############################################################################
612
613 export {
614 videojs
615 }