Fix is managaeble for channels
[oweals/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/next-video-button'
12 import './videojs-components/peertube-link-button'
13 import './videojs-components/resolution-menu-button'
14 import './videojs-components/settings-menu-button'
15 import './videojs-components/p2p-info-button'
16 import './videojs-components/peertube-load-progress-bar'
17 import './videojs-components/theater-button'
18 import { P2PMediaLoaderPluginOptions, UserWatching, VideoJSCaption, VideoJSPluginOptions, videojsUntyped } from './peertube-videojs-typings'
19 import { buildVideoEmbed, buildVideoLink, copyToClipboard, getRtcConfig } from './utils'
20 import { isDefaultLocale } from '../../../../shared/models/i18n/i18n'
21 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
22 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
23 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
24 import { getStoredP2PEnabled } from './peertube-player-local-storage'
25 import { TranslationsManager } from './translations-manager'
26
27 // Change 'Playback Rate' to 'Speed' (smaller for our settings menu)
28 videojsUntyped.getComponent('PlaybackRateMenuButton').prototype.controlText_ = 'Speed'
29 // Change Captions to Subtitles/CC
30 videojsUntyped.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)
32 videojsUntyped.getComponent('CaptionsButton').prototype.label_ = ' '
33
34 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
35
36 export type WebtorrentOptions = {
37   videoFiles: VideoFile[]
38 }
39
40 export type P2PMediaLoaderOptions = {
41   playlistUrl: string
42   segmentsSha256Url: string
43   trackerAnnounce: string[]
44   redundancyBaseUrls: string[]
45   videoFiles: VideoFile[]
46 }
47
48 export interface CustomizationOptions {
49   startTime: number | string
50   stopTime: number | string
51
52   controls?: boolean
53   muted?: boolean
54   loop?: boolean
55   subtitle?: string
56   resume?: string
57
58   peertubeLink: boolean
59 }
60
61 export interface CommonOptions extends CustomizationOptions {
62   playerElement: HTMLVideoElement
63   onPlayerElementChange: (element: HTMLVideoElement) => void
64
65   autoplay: boolean
66   nextVideo?: Function
67   videoDuration: number
68   enableHotkeys: boolean
69   inactivityTimeout: number
70   poster: string
71
72   theaterButton: boolean
73   captions: boolean
74
75   videoViewUrl: string
76   embedUrl: string
77
78   language?: string
79
80   videoCaptions: VideoJSCaption[]
81
82   userWatching?: UserWatching
83
84   serverUrl: string
85 }
86
87 export type PeertubePlayerManagerOptions = {
88   common: CommonOptions,
89   webtorrent: WebtorrentOptions,
90   p2pMediaLoader?: P2PMediaLoaderOptions
91 }
92
93 export class PeertubePlayerManager {
94   private static playerElementClassName: string
95   private static onPlayerChange: (player: any) => void
96
97   static async initialize (mode: PlayerMode, options: PeertubePlayerManagerOptions, onPlayerChange: (player: any) => void) {
98     let p2pMediaLoader: any
99
100     this.onPlayerChange = onPlayerChange
101     this.playerElementClassName = options.common.playerElement.className
102
103     if (mode === 'webtorrent') await import('./webtorrent/webtorrent-plugin')
104     if (mode === 'p2p-media-loader') {
105       [ p2pMediaLoader ] = await Promise.all([
106         import('p2p-media-loader-hlsjs'),
107         import('./p2p-media-loader/p2p-media-loader-plugin')
108       ])
109     }
110
111     const videojsOptions = this.getVideojsOptions(mode, options, p2pMediaLoader)
112
113     await TranslationsManager.loadLocaleInVideoJS(options.common.serverUrl, options.common.language, videojs)
114
115     const self = this
116     return new Promise(res => {
117       videojs(options.common.playerElement, videojsOptions, function (this: any) {
118         const player = this
119
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         })
131
132         self.addContextMenu(mode, player, options.common.embedUrl)
133
134         player.bezels()
135
136         return res(player)
137       })
138     })
139   }
140
141   private static async maybeFallbackToWebTorrent (currentMode: PlayerMode, player: any, options: PeertubePlayerManagerOptions) {
142     if (currentMode === 'webtorrent') return
143
144     console.log('Fallback to webtorrent.')
145
146     const newVideoElement = document.createElement('video')
147     newVideoElement.className = this.playerElementClassName
148
149     // VideoJS wraps our video element inside a div
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
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)
171
172       PeertubePlayerManager.onPlayerChange(player)
173     })
174   }
175
176   private static getVideojsOptions (mode: PlayerMode, options: PeertubePlayerManagerOptions, p2pMediaLoaderModule?: any) {
177     const commonOptions = options.common
178
179     let autoplay = commonOptions.autoplay
180     let html5 = {}
181
182     const plugins: VideoJSPluginOptions = {
183       peertube: {
184         mode,
185         autoplay, // Use peertube plugin autoplay because we get the file by webtorrent
186         videoViewUrl: commonOptions.videoViewUrl,
187         videoDuration: commonOptions.videoDuration,
188         userWatching: commonOptions.userWatching,
189         subtitle: commonOptions.subtitle,
190         videoCaptions: commonOptions.videoCaptions,
191         stopTime: commonOptions.stopTime
192       }
193     }
194
195     if (commonOptions.enableHotkeys === true) {
196       PeertubePlayerManager.addHotkeysOptions(plugins)
197     }
198
199     if (mode === 'p2p-media-loader') {
200       const { streamrootHls } = PeertubePlayerManager.addP2PMediaLoaderOptions(plugins, options, p2pMediaLoaderModule)
201
202       html5 = streamrootHls.html5
203     }
204
205     if (mode === 'webtorrent') {
206       PeertubePlayerManager.addWebTorrentOptions(plugins, options)
207
208       // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
209       autoplay = false
210     }
211
212     const videojsOptions = {
213       html5,
214
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
224       autoplay: autoplay === true
225         ? 'any' // Use 'any' instead of true to get notifier by videojs if autoplay fails
226         : autoplay,
227
228       poster: commonOptions.poster,
229       inactivityTimeout: commonOptions.inactivityTimeout,
230       playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 2 ],
231
232       plugins,
233
234       controlBar: {
235         children: this.getControlBarChildren(mode, {
236           captions: commonOptions.captions,
237           peertubeLink: commonOptions.peertubeLink,
238           theaterButton: commonOptions.theaterButton,
239           nextVideo: commonOptions.nextVideo
240         })
241       }
242     }
243
244     if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
245       Object.assign(videojsOptions, { language: commonOptions.language })
246     }
247
248     return videojsOptions
249   }
250
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
273     if (navigator && (navigator as any).connection && (navigator as any).connection.type === 'cellular') {
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()
307         }
308       }
309     }
310
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
327     }
328
329     Object.assign(plugins, { webtorrent })
330   }
331
332   private static getControlBarChildren (mode: PlayerMode, options: {
333     peertubeLink: boolean
334     theaterButton: boolean,
335     captions: boolean,
336     nextVideo?: Function
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 = {
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, {
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       }
388     })
389
390     if (options.peertubeLink === true) {
391       Object.assign(children, {
392         'peerTubeLinkButton': {}
393       })
394     }
395
396     if (options.theaterButton === true) {
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
421           copyToClipboard(buildVideoLink({ startTime: player.currentTime() }))
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
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   }
501 }
502
503 // ############################################################################
504
505 export {
506   videojs
507 }