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