]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-player-manager.ts
Upgrade to angular 10
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
CommitLineData
512decf3 1import 'videojs-hotkeys/videojs.hotkeys'
2adfc7ea
C
2import 'videojs-dock'
3import 'videojs-contextmenu-ui'
4import 'videojs-contrib-quality-levels'
f5fcd9f7 5import './upnext/end-card'
3bcb4fd7 6import './upnext/upnext-plugin'
62ab565d 7import './bezels/bezels-plugin'
2adfc7ea 8import './peertube-plugin'
1dc240a9 9import './videojs-components/next-video-button'
f5fcd9f7 10import './videojs-components/p2p-info-button'
2adfc7ea 11import './videojs-components/peertube-link-button'
f5fcd9f7 12import './videojs-components/peertube-load-progress-bar'
2adfc7ea 13import './videojs-components/resolution-menu-button'
f5fcd9f7
C
14import './videojs-components/resolution-menu-item'
15import './videojs-components/settings-dialog'
2adfc7ea 16import './videojs-components/settings-menu-button'
f5fcd9f7
C
17import './videojs-components/settings-menu-item'
18import './videojs-components/settings-panel'
19import './videojs-components/settings-panel-child'
2adfc7ea 20import './videojs-components/theater-button'
3e2bc4ea 21import videojs from 'video.js'
583eb04b 22import { isDefaultLocale, VideoFile } from '@shared/models'
da332417 23import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
3e2bc4ea
C
24import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
25import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
43c66a91 26import { getStoredP2PEnabled } from './peertube-player-local-storage'
3e2bc4ea 27import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings'
3f9c4955 28import { TranslationsManager } from './translations-manager'
3e2bc4ea 29import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig, isIOS, isSafari } from './utils'
2adfc7ea
C
30
31// Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
f5fcd9f7
C
32(videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
33
34const CaptionsButton = videojs.getComponent('CaptionsButton') as any
2adfc7ea 35// Change Captions to Subtitles/CC
f5fcd9f7 36CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
2adfc7ea 37// We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
f5fcd9f7 38CaptionsButton.prototype.label_ = ' '
2adfc7ea 39
3b6f205c 40export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
2adfc7ea 41
3b6f205c 42export type WebtorrentOptions = {
2adfc7ea
C
43 videoFiles: VideoFile[]
44}
45
3b6f205c 46export type P2PMediaLoaderOptions = {
2adfc7ea 47 playlistUrl: string
09209296 48 segmentsSha256Url: string
4348a27d 49 trackerAnnounce: string[]
09209296
C
50 redundancyBaseUrls: string[]
51 videoFiles: VideoFile[]
2adfc7ea
C
52}
53
5efab546
C
54export interface CustomizationOptions {
55 startTime: number | string
56 stopTime: number | string
57
58 controls?: boolean
59 muted?: boolean
60 loop?: boolean
61 subtitle?: string
96f6278f 62 resume?: string
5efab546
C
63
64 peertubeLink: boolean
65}
66
67export interface CommonOptions extends CustomizationOptions {
2adfc7ea 68 playerElement: HTMLVideoElement
6ec0b75b 69 onPlayerElementChange: (element: HTMLVideoElement) => void
2adfc7ea
C
70
71 autoplay: boolean
1dc240a9 72 nextVideo?: Function
2adfc7ea
C
73 videoDuration: number
74 enableHotkeys: boolean
75 inactivityTimeout: number
76 poster: string
2adfc7ea 77
3d9a63d3 78 theaterButton: boolean
2adfc7ea 79 captions: boolean
2adfc7ea
C
80
81 videoViewUrl: string
82 embedUrl: string
83
84 language?: string
2adfc7ea
C
85
86 videoCaptions: VideoJSCaption[]
87
88 userWatching?: UserWatching
89
90 serverUrl: string
91}
92
93export type PeertubePlayerManagerOptions = {
94 common: CommonOptions,
6ec0b75b 95 webtorrent: WebtorrentOptions,
2adfc7ea
C
96 p2pMediaLoader?: P2PMediaLoaderOptions
97}
98
99export class PeertubePlayerManager {
6ec0b75b 100 private static playerElementClassName: string
7e37e111 101 private static onPlayerChange: (player: videojs.Player) => void
2adfc7ea 102
7e37e111 103 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
4348a27d
C
104 let p2pMediaLoader: any
105
bfbd9128 106 this.onPlayerChange = onPlayerChange
6ec0b75b
C
107 this.playerElementClassName = options.common.playerElement.className
108
09209296 109 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
4348a27d
C
110 if (mode === 'p2p-media-loader') {
111 [ p2pMediaLoader ] = await Promise.all([
112 import('p2p-media-loader-hlsjs'),
09209296 113 import('./p2p-media-loader/p2p-media-loader-plugin')
4348a27d
C
114 ])
115 }
2adfc7ea 116
4348a27d 117 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
2adfc7ea 118
3f9c4955 119 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
2adfc7ea
C
120
121 const self = this
122 return new Promise(res => {
7e37e111 123 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
2adfc7ea
C
124 const player = this
125
536598cf
C
126 let alreadyFallback = false
127
f5fcd9f7 128 player.tech(true).one('error', () => {
536598cf
C
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 })
6ec0b75b 137
2adfc7ea
C
138 self.addContextMenu(mode, player, options.common.embedUrl)
139
10475dea
RK
140 player.bezels()
141
2adfc7ea
C
142 return res(player)
143 })
144 })
145 }
146
96cb4527
C
147 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
148 if (currentMode === 'webtorrent') return
149
150 console.log('Fallback to webtorrent.')
151
6ec0b75b
C
152 const newVideoElement = document.createElement('video')
153 newVideoElement.className = this.playerElementClassName
154
155 // VideoJS wraps our video element inside a div
96cb4527
C
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
6ec0b75b
C
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
7e37e111 173 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
6ec0b75b
C
174 const player = this
175
176 self.addContextMenu(mode, player, options.common.embedUrl)
bfbd9128
C
177
178 PeertubePlayerManager.onPlayerChange(player)
6ec0b75b
C
179 })
180 }
181
f5fcd9f7
C
182 private static getVideojsOptions (
183 mode: PlayerMode,
184 options: PeertubePlayerManagerOptions,
185 p2pMediaLoaderModule?: any
7e37e111 186 ): videojs.PlayerOptions {
2adfc7ea 187 const commonOptions = options.common
09209296 188
72efdda5 189 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
3b6f205c 190 let html5 = {}
2adfc7ea
C
191
192 const plugins: VideoJSPluginOptions = {
193 peertube: {
09209296
C
194 mode,
195 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
2adfc7ea
C
196 videoViewUrl: commonOptions.videoViewUrl,
197 videoDuration: commonOptions.videoDuration,
2adfc7ea
C
198 userWatching: commonOptions.userWatching,
199 subtitle: commonOptions.subtitle,
f0a39880
C
200 videoCaptions: commonOptions.videoCaptions,
201 stopTime: commonOptions.stopTime
2adfc7ea
C
202 }
203 }
204
39aad8cc
C
205 if (commonOptions.enableHotkeys === true) {
206 PeertubePlayerManager.addHotkeysOptions(plugins)
207 }
09209296 208
39aad8cc 209 if (mode === 'p2p-media-loader') {
83fcadac 210 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
2adfc7ea 211
83fcadac 212 html5 = hlsjs.html5
2adfc7ea
C
213 }
214
6ec0b75b 215 if (mode === 'webtorrent') {
39aad8cc 216 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
09209296
C
217
218 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
219 autoplay = false
2adfc7ea
C
220 }
221
222 const videojsOptions = {
3b6f205c
C
223 html5,
224
2adfc7ea 225 // We don't use text track settings for now
f5fcd9f7 226 textTrackSettings: false as any, // FIXME: typings
2adfc7ea
C
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
72efdda5 234 autoplay: this.getAutoPlayValue(autoplay),
39aad8cc 235
2adfc7ea 236 poster: commonOptions.poster,
2adfc7ea
C
237 inactivityTimeout: commonOptions.inactivityTimeout,
238 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
39aad8cc 239
2adfc7ea 240 plugins,
39aad8cc 241
2adfc7ea
C
242 controlBar: {
243 children: this.getControlBarChildren(mode, {
244 captions: commonOptions.captions,
245 peertubeLink: commonOptions.peertubeLink,
1dc240a9
RK
246 theaterButton: commonOptions.theaterButton,
247 nextVideo: commonOptions.nextVideo
f5fcd9f7 248 }) as any // FIXME: typings
2adfc7ea
C
249 }
250 }
251
39aad8cc
C
252 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
253 Object.assign(videojsOptions, { language: commonOptions.language })
254 }
2adfc7ea 255
39aad8cc
C
256 return videojsOptions
257 }
2adfc7ea 258
39aad8cc
C
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
fe9d0531 281 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
39aad8cc
C
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 }
83fcadac 300 const hlsjs = {
39aad8cc 301 levelLabelHandler: (level: { height: number, width: number }) => {
dca0fe12
C
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 }
39aad8cc
C
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()
2adfc7ea 321 }
39aad8cc 322 }
2adfc7ea
C
323 }
324
83fcadac 325 const toAssign = { p2pMediaLoader, hlsjs }
39aad8cc
C
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
2adfc7ea
C
341 }
342
39aad8cc 343 Object.assign(plugins, { webtorrent })
2adfc7ea
C
344 }
345
346 private static getControlBarChildren (mode: PlayerMode, options: {
347 peertubeLink: boolean
3d9a63d3 348 theaterButton: boolean,
1dc240a9
RK
349 captions: boolean,
350 nextVideo?: Function
2adfc7ea
C
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 = {
1dc240a9
RK
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, {
2adfc7ea
C
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 }
1dc240a9 402 })
2adfc7ea
C
403
404 if (options.peertubeLink === true) {
405 Object.assign(children, {
406 'peerTubeLinkButton': {}
407 })
408 }
409
3d9a63d3 410 if (options.theaterButton === true) {
2adfc7ea
C
411 Object.assign(children, {
412 'theaterButton': {}
413 })
414 }
415
416 Object.assign(children, {
417 'fullscreenToggle': {}
418 })
419
420 return children
421 }
422
7e37e111 423 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
2adfc7ea
C
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'),
7e37e111 433 listener: function (this: videojs.Player) {
f5fcd9f7 434 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
2adfc7ea
C
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'),
7e37e111 448 listener: function (this: videojs.Player) {
f5fcd9f7 449 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
2adfc7ea
C
450 }
451 })
452 }
453
454 player.contextmenuUI({ content })
455 }
456
39aad8cc
C
457 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
458 Object.assign(plugins, {
459 hotkeys: {
7ede74ad
C
460 skipInitialFocus: true,
461 enableInactiveFocus: false,
462 captureDocumentHotkeys: true,
463 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
e85bfe96
C
464 const tagName = e.tagName.toLowerCase()
465 return e.id === 'content' || tagName === 'body' || tagName === 'video'
7ede74ad
C
466 },
467
39aad8cc
C
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) {
f5fcd9f7
C
495 const newValue = Math.min(player.playbackRate() + 0.1, 5)
496 player.playbackRate(parseFloat(newValue.toFixed(2)))
39aad8cc
C
497 }
498 },
499 decreasePlaybackRateKey: {
500 key: function (event: KeyboardEvent) {
501 return event.key === '<'
502 },
503 handler: function (player: videojs.Player) {
f5fcd9f7
C
504 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
505 player.playbackRate(parseFloat(newValue.toFixed(2)))
39aad8cc
C
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 }
64228474 523
72efdda5
C
524 private static getAutoPlayValue (autoplay: any) {
525 if (autoplay !== true) return autoplay
526
72efdda5 527 // Giving up with iOS
3e2bc4ea 528 if (isIOS()) return false
72efdda5 529
64228474
C
530 // We have issues with autoplay and Safari.
531 // any that tries to play using auto mute seems to work
3e2bc4ea 532 if (isSafari()) return 'any'
64228474
C
533
534 return 'play'
535 }
2adfc7ea
C
536}
537
538// ############################################################################
539
540export {
541 videojs
542}