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