]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/assets/player/peertube-player-manager.ts
Merge branch 'release/2.1.0' into develop
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-manager.ts
1 import { VideoFile } from '../../../../shared/models/videos'
2 import videojs, { VideoJsPlayer, VideoJsPlayerOptions } from 'video.js'
3 import 'videojs-hotkeys'
4 import 'videojs-dock'
5 import 'videojs-contextmenu-ui'
6 import 'videojs-contrib-quality-levels'
7 import './upnext/end-card'
8 import './upnext/upnext-plugin'
9 import './bezels/bezels-plugin'
10 import './peertube-plugin'
11 import './videojs-components/next-video-button'
12 import './videojs-components/p2p-info-button'
13 import './videojs-components/peertube-link-button'
14 import './videojs-components/peertube-load-progress-bar'
15 import './videojs-components/resolution-menu-button'
16 import './videojs-components/resolution-menu-item'
17 import './videojs-components/settings-dialog'
18 import './videojs-components/settings-menu-button'
19 import './videojs-components/settings-menu-item'
20 import './videojs-components/settings-panel'
21 import './videojs-components/settings-panel-child'
22 import './videojs-components/theater-button'
23 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions } from './peertube-videojs-typings'
24 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils'
25 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
26 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
27 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
28 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
29 import { getStoredP2PEnabled } from './peertube-player-local-storage'
30 import { TranslationsManager } from './translations-manager'
31
32 // For VideoJS
33 (window as any).WebVTT = require('vtt.js/lib/vtt.js').WebVTT;
34
35 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
36 (videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
37
38 const CaptionsButton = videojs.getComponent('CaptionsButton') as any
39 // Change Captions to Subtitles/CC
40 CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
41 // We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
42 CaptionsButton.prototype.label_ = ' '
43
44 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
45
46 export type WebtorrentOptions = {
47 videoFiles: VideoFile[]
48 }
49
50 export type P2PMediaLoaderOptions = {
51 playlistUrl: string
52 segmentsSha256Url: string
53 trackerAnnounce: string[]
54 redundancyBaseUrls: string[]
55 videoFiles: VideoFile[]
56 }
57
58 export interface CustomizationOptions {
59 startTime: number | string
60 stopTime: number | string
61
62 controls?: boolean
63 muted?: boolean
64 loop?: boolean
65 subtitle?: string
66 resume?: string
67
68 peertubeLink: boolean
69 }
70
71 export interface CommonOptions extends CustomizationOptions {
72 playerElement: HTMLVideoElement
73 onPlayerElementChange: (element: HTMLVideoElement) => void
74
75 autoplay: boolean
76 nextVideo?: Function
77 videoDuration: number
78 enableHotkeys: boolean
79 inactivityTimeout: number
80 poster: string
81
82 theaterButton: boolean
83 captions: boolean
84
85 videoViewUrl: string
86 embedUrl: string
87
88 language?: string
89
90 videoCaptions: VideoJSCaption[]
91
92 userWatching?: UserWatching
93
94 serverUrl: string
95 }
96
97 export type PeertubePlayerManagerOptions = {
98 common: CommonOptions,
99 webtorrent: WebtorrentOptions,
100 p2pMediaLoader?: P2PMediaLoaderOptions
101 }
102
103 export class PeertubePlayerManager {
104 private static playerElementClassName: string
105 private static onPlayerChange: (player: VideoJsPlayer) => void
106
107 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: VideoJsPlayer) => void) {
108 let p2pMediaLoader: any
109
110 this.onPlayerChange = onPlayerChange
111 this.playerElementClassName = options.common.playerElement.className
112
113 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
114 if (mode === 'p2p-media-loader') {
115 [ p2pMediaLoader ] = await Promise.all([
116 import('p2p-media-loader-hlsjs'),
117 import('./p2p-media-loader/p2p-media-loader-plugin')
118 ])
119 }
120
121 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
122
123 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
124
125 const self = this
126 return new Promise(res => {
127 videojs(options.common.playerElement, videojsOptions, function (this: VideoJsPlayer) {
128 const player = this
129
130 let alreadyFallback = false
131
132 player.tech(true).one('error', () => {
133 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
134 alreadyFallback = true
135 })
136
137 player.one('error', () => {
138 if (!alreadyFallback) self.maybeFallbackToWebTorrent(mode, player, options)
139 alreadyFallback = true
140 })
141
142 self.addContextMenu(mode, player, options.common.embedUrl)
143
144 player.bezels()
145
146 return res(player)
147 })
148 })
149 }
150
151 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
152 if (currentMode === 'webtorrent') return
153
154 console.log('Fallback to webtorrent.')
155
156 const newVideoElement = document.createElement('video')
157 newVideoElement.className = this.playerElementClassName
158
159 // VideoJS wraps our video element inside a div
160 let currentParentPlayerElement = options.common.playerElement.parentNode
161 // Fix on IOS, don't ask me why
162 if (!currentParentPlayerElement) currentParentPlayerElement = document.getElementById(options.common.playerElement.id).parentNode
163
164 currentParentPlayerElement.parentNode.insertBefore(newVideoElement, currentParentPlayerElement)
165
166 options.common.playerElement = newVideoElement
167 options.common.onPlayerElementChange(newVideoElement)
168
169 player.dispose()
170
171 await import('./webtorrent/webtorrent-plugin')
172
173 const mode = 'webtorrent'
174 const videojsOptions = this.getVideojsOptions(mode, options)
175
176 const self = this
177 videojs(newVideoElement, videojsOptions, function (this: VideoJsPlayer) {
178 const player = this
179
180 self.addContextMenu(mode, player, options.common.embedUrl)
181
182 PeertubePlayerManager.onPlayerChange(player)
183 })
184 }
185
186 private static getVideojsOptions (
187 mode: PlayerMode,
188 options: PeertubePlayerManagerOptions,
189 p2pMediaLoaderModule?: any
190 ): VideoJsPlayerOptions {
191 const commonOptions = options.common
192
193 let autoplay = commonOptions.autoplay
194 let html5 = {}
195
196 const plugins: VideoJSPluginOptions = {
197 peertube: {
198 mode,
199 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
200 videoViewUrl: commonOptions.videoViewUrl,
201 videoDuration: commonOptions.videoDuration,
202 userWatching: commonOptions.userWatching,
203 subtitle: commonOptions.subtitle,
204 videoCaptions: commonOptions.videoCaptions,
205 stopTime: commonOptions.stopTime
206 }
207 }
208
209 if (commonOptions.enableHotkeys === true) {
210 PeertubePlayerManager.addHotkeysOptions(plugins)
211 }
212
213 if (mode === 'p2p-media-loader') {
214 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
215
216 html5 = hlsjs.html5
217 }
218
219 if (mode === 'webtorrent') {
220 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
221
222 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
223 autoplay = false
224 }
225
226 const videojsOptions = {
227 html5,
228
229 // We don't use text track settings for now
230 textTrackSettings: false as any, // FIXME: typings
231 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
232 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
233
234 muted: commonOptions.muted !== undefined
235 ? commonOptions.muted
236 : undefined, // Undefined so the player knows it has to check the local storage
237
238 autoplay: autoplay === true
239 ? 'any' // Use 'any' instead of true to get notifier by videojs if autoplay fails
240 : autoplay,
241
242 poster: commonOptions.poster,
243 inactivityTimeout: commonOptions.inactivityTimeout,
244 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
245
246 plugins,
247
248 controlBar: {
249 children: this.getControlBarChildren(mode, {
250 captions: commonOptions.captions,
251 peertubeLink: commonOptions.peertubeLink,
252 theaterButton: commonOptions.theaterButton,
253 nextVideo: commonOptions.nextVideo
254 }) as any // FIXME: typings
255 }
256 }
257
258 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
259 Object.assign(videojsOptions, { language: commonOptions.language })
260 }
261
262 return videojsOptions
263 }
264
265 private static addP2PMediaLoaderOptions (
266 plugins: VideoJSPluginOptions,
267 options: PeertubePlayerManagerOptions,
268 p2pMediaLoaderModule: any
269 ) {
270 const p2pMediaLoaderOptions = options.p2pMediaLoader
271 const commonOptions = options.common
272
273 const trackerAnnounce = p2pMediaLoaderOptions.trackerAnnounce
274 .filter(t => t.startsWith('ws'))
275
276 const redundancyUrlManager = new RedundancyUrlManager(options.p2pMediaLoader.redundancyBaseUrls)
277
278 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
279 redundancyUrlManager,
280 type: 'application/x-mpegURL',
281 startTime: commonOptions.startTime,
282 src: p2pMediaLoaderOptions.playlistUrl
283 }
284
285 let consumeOnly = false
286 // FIXME: typings
287 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
288 console.log('We are on a cellular connection: disabling seeding.')
289 consumeOnly = true
290 }
291
292 const p2pMediaLoaderConfig = {
293 loader: {
294 trackerAnnounce,
295 segmentValidator: segmentValidatorFactory(options.p2pMediaLoader.segmentsSha256Url),
296 rtcConfig: getRtcConfig(),
297 requiredSegmentsPriority: 5,
298 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
299 useP2P: getStoredP2PEnabled(),
300 consumeOnly
301 },
302 segments: {
303 swarmId: p2pMediaLoaderOptions.playlistUrl
304 }
305 }
306 const hlsjs = {
307 levelLabelHandler: (level: { height: number, width: number }) => {
308 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === level.height)
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: VideoJsPlayer, 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: VideoJsPlayer) {
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: VideoJsPlayer) {
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 enableVolumeScroll: false,
461 enableModifiersForNumbers: false,
462
463 fullscreenKey: function (event: KeyboardEvent) {
464 // fullscreen with the f key or Ctrl+Enter
465 return event.key === 'f' || (event.ctrlKey && event.key === 'Enter')
466 },
467
468 seekStep: function (event: KeyboardEvent) {
469 // mimic VLC seek behavior, and default to 5 (original value is 5).
470 if (event.ctrlKey && event.altKey) {
471 return 5 * 60
472 } else if (event.ctrlKey) {
473 return 60
474 } else if (event.altKey) {
475 return 10
476 } else {
477 return 5
478 }
479 },
480
481 customKeys: {
482 increasePlaybackRateKey: {
483 key: function (event: KeyboardEvent) {
484 return event.key === '>'
485 },
486 handler: function (player: videojs.Player) {
487 const newValue = Math.min(player.playbackRate() + 0.1, 5)
488 player.playbackRate(parseFloat(newValue.toFixed(2)))
489 }
490 },
491 decreasePlaybackRateKey: {
492 key: function (event: KeyboardEvent) {
493 return event.key === '<'
494 },
495 handler: function (player: videojs.Player) {
496 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
497 player.playbackRate(parseFloat(newValue.toFixed(2)))
498 }
499 },
500 frameByFrame: {
501 key: function (event: KeyboardEvent) {
502 return event.key === '.'
503 },
504 handler: function (player: videojs.Player) {
505 player.pause()
506 // Calculate movement distance (assuming 30 fps)
507 const dist = 1 / 30
508 player.currentTime(player.currentTime() + dist)
509 }
510 }
511 }
512 }
513 })
514 }
515 }
516
517 // ############################################################################
518
519 export {
520 videojs
521 }