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