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