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