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