]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
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'
a950e4c8 9import './videojs-components/next-previous-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'
4572c3d0 21import './playlist/playlist-plugin'
3e2bc4ea 22import videojs from 'video.js'
bd45d503 23import { isDefaultLocale } from '@shared/core-utils/i18n'
4572c3d0 24import { VideoFile } from '@shared/models'
da332417 25import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
3e2bc4ea
C
26import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
27import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
43c66a91 28import { getStoredP2PEnabled } from './peertube-player-local-storage'
4572c3d0 29import {
a950e4c8 30 NextPreviousVideoButtonOptions,
4572c3d0
C
31 P2PMediaLoaderPluginOptions,
32 PlaylistPluginOptions,
33 UserWatching,
34 VideoJSCaption,
35 VideoJSPluginOptions
36} from './peertube-videojs-typings'
3f9c4955 37import { TranslationsManager } from './translations-manager'
9eccae74 38import { buildVideoOrPlaylistEmbed, buildVideoLink, copyToClipboard, getRtcConfig, isSafari, isIOS } from './utils'
2adfc7ea
C
39
40// Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
f5fcd9f7
C
41(videojs.getComponent('PlaybackRateMenuButton') as any).prototype.controlText_ = 'Speed'
42
43const CaptionsButton = videojs.getComponent('CaptionsButton') as any
2adfc7ea 44// Change Captions to Subtitles/CC
f5fcd9f7 45CaptionsButton.prototype.controlText_ = 'Subtitles/CC'
2adfc7ea 46// We just want to display 'Off' instead of 'captions off', keep a space so the variable == true (hacky I know)
f5fcd9f7 47CaptionsButton.prototype.label_ = ' '
2adfc7ea 48
3b6f205c 49export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
2adfc7ea 50
3b6f205c 51export type WebtorrentOptions = {
2adfc7ea
C
52 videoFiles: VideoFile[]
53}
54
3b6f205c 55export type P2PMediaLoaderOptions = {
2adfc7ea 56 playlistUrl: string
09209296 57 segmentsSha256Url: string
4348a27d 58 trackerAnnounce: string[]
09209296
C
59 redundancyBaseUrls: string[]
60 videoFiles: VideoFile[]
2adfc7ea
C
61}
62
5efab546
C
63export interface CustomizationOptions {
64 startTime: number | string
65 stopTime: number | string
66
67 controls?: boolean
68 muted?: boolean
69 loop?: boolean
70 subtitle?: string
96f6278f 71 resume?: string
5efab546
C
72
73 peertubeLink: boolean
74}
75
76export interface CommonOptions extends CustomizationOptions {
2adfc7ea 77 playerElement: HTMLVideoElement
6ec0b75b 78 onPlayerElementChange: (element: HTMLVideoElement) => void
2adfc7ea
C
79
80 autoplay: boolean
a950e4c8
C
81
82 nextVideo?: () => void
83 hasNextVideo?: () => boolean
84
85 previousVideo?: () => void
86 hasPreviousVideo?: () => boolean
4572c3d0
C
87
88 playlist?: PlaylistPluginOptions
89
2adfc7ea
C
90 videoDuration: number
91 enableHotkeys: boolean
92 inactivityTimeout: number
93 poster: string
2adfc7ea 94
3d9a63d3 95 theaterButton: boolean
2adfc7ea 96 captions: boolean
2adfc7ea
C
97
98 videoViewUrl: string
99 embedUrl: string
100
101 language?: string
2adfc7ea
C
102
103 videoCaptions: VideoJSCaption[]
104
105 userWatching?: UserWatching
106
107 serverUrl: string
108}
109
110export type PeertubePlayerManagerOptions = {
111 common: CommonOptions,
6ec0b75b 112 webtorrent: WebtorrentOptions,
2adfc7ea
C
113 p2pMediaLoader?: P2PMediaLoaderOptions
114}
115
116export class PeertubePlayerManager {
6ec0b75b 117 private static playerElementClassName: string
7e37e111 118 private static onPlayerChange: (player: videojs.Player) => void
2adfc7ea 119
9eccae74
C
120 private static alreadyPlayed = false
121
7e37e111 122 static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: videojs.Player) => void) {
4348a27d
C
123 let p2pMediaLoader: any
124
bfbd9128 125 this.onPlayerChange = onPlayerChange
6ec0b75b
C
126 this.playerElementClassName = options.common.playerElement.className
127
09209296 128 if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
4348a27d
C
129 if (mode === 'p2p-media-loader') {
130 [ p2pMediaLoader ] = await Promise.all([
131 import('p2p-media-loader-hlsjs'),
09209296 132 import('./p2p-media-loader/p2p-media-loader-plugin')
4348a27d
C
133 ])
134 }
2adfc7ea 135
4348a27d 136 const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
2adfc7ea 137
3f9c4955 138 await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
2adfc7ea
C
139
140 const self = this
141 return new Promise(res => {
7e37e111 142 videojs(options.common.playerElement, videojsOptions, function (this: videojs.Player) {
2adfc7ea
C
143 const player = this
144
536598cf
C
145 let alreadyFallback = false
146
f5fcd9f7 147 player.tech(true).one('error', () => {
536598cf
C
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 })
6ec0b75b 156
9eccae74
C
157 player.one('play', () => {
158 PeertubePlayerManager.alreadyPlayed = true
159 })
160
2adfc7ea
C
161 self.addContextMenu(mode, player, options.common.embedUrl)
162
10475dea
RK
163 player.bezels()
164
2adfc7ea
C
165 return res(player)
166 })
167 })
168 }
169
96cb4527
C
170 private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
171 if (currentMode === 'webtorrent') return
172
173 console.log('Fallback to webtorrent.')
174
6ec0b75b
C
175 const newVideoElement = document.createElement('video')
176 newVideoElement.className = this.playerElementClassName
177
178 // VideoJS wraps our video element inside a div
96cb4527
C
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
6ec0b75b
C
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
7e37e111 196 videojs(newVideoElement, videojsOptions, function (this: videojs.Player) {
6ec0b75b
C
197 const player = this
198
199 self.addContextMenu(mode, player, options.common.embedUrl)
bfbd9128
C
200
201 PeertubePlayerManager.onPlayerChange(player)
6ec0b75b
C
202 })
203 }
204
f5fcd9f7
C
205 private static getVideojsOptions (
206 mode: PlayerMode,
207 options: PeertubePlayerManagerOptions,
208 p2pMediaLoaderModule?: any
7e37e111 209 ): videojs.PlayerOptions {
2adfc7ea 210 const commonOptions = options.common
9eccae74 211 const isHLS = mode === 'p2p-media-loader'
09209296 212
72efdda5 213 let autoplay = this.getAutoPlayValue(commonOptions.autoplay)
3b6f205c 214 let html5 = {}
2adfc7ea
C
215
216 const plugins: VideoJSPluginOptions = {
217 peertube: {
09209296
C
218 mode,
219 autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
2adfc7ea
C
220 videoViewUrl: commonOptions.videoViewUrl,
221 videoDuration: commonOptions.videoDuration,
2adfc7ea
C
222 userWatching: commonOptions.userWatching,
223 subtitle: commonOptions.subtitle,
f0a39880
C
224 videoCaptions: commonOptions.videoCaptions,
225 stopTime: commonOptions.stopTime
2adfc7ea
C
226 }
227 }
228
4572c3d0
C
229 if (commonOptions.playlist) {
230 plugins.playlist = commonOptions.playlist
231 }
232
39aad8cc
C
233 if (commonOptions.enableHotkeys === true) {
234 PeertubePlayerManager.addHotkeysOptions(plugins)
235 }
09209296 236
9eccae74 237 if (isHLS) {
83fcadac 238 const { hlsjs } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
2adfc7ea 239
83fcadac 240 html5 = hlsjs.html5
2adfc7ea
C
241 }
242
6ec0b75b 243 if (mode === 'webtorrent') {
39aad8cc 244 PeertubePlayerManager.addWebTorrentOptions(plugins, options)
09209296
C
245
246 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
247 autoplay = false
2adfc7ea
C
248 }
249
250 const videojsOptions = {
3b6f205c
C
251 html5,
252
2adfc7ea 253 // We don't use text track settings for now
f5fcd9f7 254 textTrackSettings: false as any, // FIXME: typings
2adfc7ea
C
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
72efdda5 262 autoplay: this.getAutoPlayValue(autoplay),
39aad8cc 263
2adfc7ea 264 poster: commonOptions.poster,
2adfc7ea
C
265 inactivityTimeout: commonOptions.inactivityTimeout,
266 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
39aad8cc 267
2adfc7ea 268 plugins,
39aad8cc 269
2adfc7ea
C
270 controlBar: {
271 children: this.getControlBarChildren(mode, {
272 captions: commonOptions.captions,
273 peertubeLink: commonOptions.peertubeLink,
1dc240a9 274 theaterButton: commonOptions.theaterButton,
a950e4c8
C
275
276 nextVideo: commonOptions.nextVideo,
277 hasNextVideo: commonOptions.hasNextVideo,
278
279 previousVideo: commonOptions.previousVideo,
280 hasPreviousVideo: commonOptions.hasPreviousVideo
f5fcd9f7 281 }) as any // FIXME: typings
2adfc7ea
C
282 }
283 }
284
39aad8cc
C
285 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
286 Object.assign(videojsOptions, { language: commonOptions.language })
287 }
2adfc7ea 288
39aad8cc
C
289 return videojsOptions
290 }
2adfc7ea 291
39aad8cc
C
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
fe9d0531 314 if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
39aad8cc
C
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 }
83fcadac 333 const hlsjs = {
39aad8cc 334 levelLabelHandler: (level: { height: number, width: number }) => {
dca0fe12
C
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 }
39aad8cc
C
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()
2adfc7ea 354 }
39aad8cc 355 }
2adfc7ea
C
356 }
357
83fcadac 358 const toAssign = { p2pMediaLoader, hlsjs }
39aad8cc
C
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
ebc8dd52
C
368 const autoplay = this.getAutoPlayValue(commonOptions.autoplay) === 'play'
369 ? true
370 : false
371
39aad8cc 372 const webtorrent = {
ebc8dd52 373 autoplay,
39aad8cc
C
374 videoDuration: commonOptions.videoDuration,
375 playerElement: commonOptions.playerElement,
376 videoFiles: webtorrentOptions.videoFiles,
377 startTime: commonOptions.startTime
2adfc7ea
C
378 }
379
39aad8cc 380 Object.assign(plugins, { webtorrent })
2adfc7ea
C
381 }
382
383 private static getControlBarChildren (mode: PlayerMode, options: {
384 peertubeLink: boolean
a950e4c8
C
385 theaterButton: boolean
386 captions: boolean
387
1dc240a9 388 nextVideo?: Function
a950e4c8
C
389 hasNextVideo?: () => boolean
390
391 previousVideo?: Function
392 hasPreviousVideo?: () => boolean
2adfc7ea
C
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
a950e4c8
C
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 })
1dc240a9
RK
418 }
419
a950e4c8
C
420 Object.assign(children, { playToggle: {} })
421
1dc240a9 422 if (options.nextVideo) {
a950e4c8
C
423 const buttonOptions: NextPreviousVideoButtonOptions = {
424 type: 'next',
425 handler: options.nextVideo,
426 isDisabled: () => {
427 if (!options.hasNextVideo) return false
428
429 return !options.hasNextVideo()
1dc240a9 430 }
a950e4c8
C
431 }
432
433 Object.assign(children, {
434 'nextVideoButton': buttonOptions
1dc240a9
RK
435 })
436 }
437
438 Object.assign(children, {
2adfc7ea
C
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 }
1dc240a9 468 })
2adfc7ea
C
469
470 if (options.peertubeLink === true) {
471 Object.assign(children, {
472 'peerTubeLinkButton': {}
473 })
474 }
475
3d9a63d3 476 if (options.theaterButton === true) {
2adfc7ea
C
477 Object.assign(children, {
478 'theaterButton': {}
479 })
480 }
481
482 Object.assign(children, {
483 'fullscreenToggle': {}
484 })
485
486 return children
487 }
488
7e37e111 489 private static addContextMenu (mode: PlayerMode, player: videojs.Player, videoEmbedUrl: string) {
2adfc7ea
C
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'),
7e37e111 499 listener: function (this: videojs.Player) {
f5fcd9f7 500 copyToClipboard(buildVideoLink({ startTime: this.currentTime() }))
2adfc7ea
C
501 }
502 },
503 {
504 label: player.localize('Copy embed code'),
505 listener: () => {
951b582f 506 copyToClipboard(buildVideoOrPlaylistEmbed(videoEmbedUrl))
2adfc7ea
C
507 }
508 }
509 ]
510
511 if (mode === 'webtorrent') {
512 content.push({
513 label: player.localize('Copy magnet URI'),
7e37e111 514 listener: function (this: videojs.Player) {
f5fcd9f7 515 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
2adfc7ea
C
516 }
517 })
518 }
519
520 player.contextmenuUI({ content })
521 }
522
39aad8cc
C
523 private static addHotkeysOptions (plugins: VideoJSPluginOptions) {
524 Object.assign(plugins, {
525 hotkeys: {
7ede74ad
C
526 skipInitialFocus: true,
527 enableInactiveFocus: false,
528 captureDocumentHotkeys: true,
529 documentHotkeysFocusElementFilter: (e: HTMLElement) => {
e85bfe96
C
530 const tagName = e.tagName.toLowerCase()
531 return e.id === 'content' || tagName === 'body' || tagName === 'video'
7ede74ad
C
532 },
533
39aad8cc
C
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) {
f5fcd9f7
C
561 const newValue = Math.min(player.playbackRate() + 0.1, 5)
562 player.playbackRate(parseFloat(newValue.toFixed(2)))
39aad8cc
C
563 }
564 },
565 decreasePlaybackRateKey: {
566 key: function (event: KeyboardEvent) {
567 return event.key === '<'
568 },
569 handler: function (player: videojs.Player) {
f5fcd9f7
C
570 const newValue = Math.max(player.playbackRate() - 0.1, 0.10)
571 player.playbackRate(parseFloat(newValue.toFixed(2)))
39aad8cc
C
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 }
64228474 589
72efdda5
C
590 private static getAutoPlayValue (autoplay: any) {
591 if (autoplay !== true) return autoplay
592
ebc8dd52
C
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()) {
9eccae74
C
596 return PeertubePlayerManager.alreadyPlayed ? 'play' : false
597 }
64228474
C
598
599 return 'play'
600 }
2adfc7ea
C
601}
602
603// ############################################################################
604
605export {
606 videojs
607}