]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/assets/player/peertube-player-options-builder.ts
Fix stuck hls player with bad redundancy
[github/Chocobozzz/PeerTube.git] / client / src / assets / player / peertube-player-options-builder.ts
CommitLineData
c4207f97
C
1import videojs from 'video.js'
2import { HlsJsEngineSettings } from '@peertube/p2p-media-loader-hlsjs'
3import { PluginsManager } from '@root-helpers/plugins-manager'
4import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
5import { isDefaultLocale } from '@shared/core-utils/i18n'
6import { VideoFile } from '@shared/models'
7import { copyToClipboard } from '../../root-helpers/utils'
8import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
9import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
10import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
11import { getAverageBandwidthInStore } from './peertube-player-local-storage'
12import {
13 NextPreviousVideoButtonOptions,
14 P2PMediaLoaderPluginOptions,
15 PeerTubeLinkButtonOptions,
16 PlaylistPluginOptions,
17 UserWatching,
18 VideoJSCaption,
19 VideoJSPluginOptions
20} from './peertube-videojs-typings'
21import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isSafari } from './utils'
ac5f679a 22import { HybridLoaderSettings } from '@peertube/p2p-media-loader-core'
c4207f97
C
23
24export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
25
26export type WebtorrentOptions = {
27 videoFiles: VideoFile[]
28}
29
30export type P2PMediaLoaderOptions = {
31 playlistUrl: string
32 segmentsSha256Url: string
33 trackerAnnounce: string[]
34 redundancyBaseUrls: string[]
35 videoFiles: VideoFile[]
36}
37
38export interface CustomizationOptions {
39 startTime: number | string
40 stopTime: number | string
41
42 controls?: boolean
43 muted?: boolean
44 loop?: boolean
45 subtitle?: string
46 resume?: string
47
48 peertubeLink: boolean
49}
50
51export interface CommonOptions extends CustomizationOptions {
52 playerElement: HTMLVideoElement
53 onPlayerElementChange: (element: HTMLVideoElement) => void
54
55 autoplay: boolean
56 p2pEnabled: boolean
57
58 nextVideo?: () => void
59 hasNextVideo?: () => boolean
60
61 previousVideo?: () => void
62 hasPreviousVideo?: () => boolean
63
64 playlist?: PlaylistPluginOptions
65
66 videoDuration: number
67 enableHotkeys: boolean
68 inactivityTimeout: number
69 poster: string
70
71 theaterButton: boolean
72 captions: boolean
73
74 videoViewUrl: string
75 embedUrl: string
76 embedTitle: string
77
78 isLive: boolean
79
80 language?: string
81
82 videoCaptions: VideoJSCaption[]
83
84 videoUUID: string
85 videoShortUUID: string
86
87 userWatching?: UserWatching
88
89 serverUrl: string
90
91 errorNotifier: (message: string) => void
92}
93
94export type PeertubePlayerManagerOptions = {
95 common: CommonOptions
96 webtorrent: WebtorrentOptions
97 p2pMediaLoader?: P2PMediaLoaderOptions
98
99 pluginsManager: PluginsManager
100}
101
102export class PeertubePlayerOptionsBuilder {
103
104 constructor (
105 private mode: PlayerMode,
106 private options: PeertubePlayerManagerOptions,
107 private p2pMediaLoaderModule?: any
108 ) {
109
110 }
111
112 getVideojsOptions (alreadyPlayed: boolean): videojs.PlayerOptions {
113 const commonOptions = this.options.common
114 const isHLS = this.mode === 'p2p-media-loader'
115
116 let autoplay = this.getAutoPlayValue(commonOptions.autoplay, alreadyPlayed)
117 const html5 = {
118 preloadTextTracks: false
119 }
120
121 const plugins: VideoJSPluginOptions = {
122 peertube: {
123 mode: this.mode,
124 autoplay, // Use peertube plugin autoplay because we could get the file by webtorrent
125 videoViewUrl: commonOptions.videoViewUrl,
126 videoDuration: commonOptions.videoDuration,
127 userWatching: commonOptions.userWatching,
128 subtitle: commonOptions.subtitle,
129 videoCaptions: commonOptions.videoCaptions,
130 stopTime: commonOptions.stopTime,
131 isLive: commonOptions.isLive,
132 videoUUID: commonOptions.videoUUID
133 }
134 }
135
136 if (commonOptions.playlist) {
137 plugins.playlist = commonOptions.playlist
138 }
139
140 if (isHLS) {
141 const { hlsjs } = this.addP2PMediaLoaderOptions(plugins)
142
143 Object.assign(html5, hlsjs.html5)
144 }
145
146 if (this.mode === 'webtorrent') {
147 this.addWebTorrentOptions(plugins, alreadyPlayed)
148
149 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
150 autoplay = false
151 }
152
153 const videojsOptions = {
154 html5,
155
156 // We don't use text track settings for now
157 textTrackSettings: false as any, // FIXME: typings
158 controls: commonOptions.controls !== undefined ? commonOptions.controls : true,
159 loop: commonOptions.loop !== undefined ? commonOptions.loop : false,
160
161 muted: commonOptions.muted !== undefined
162 ? commonOptions.muted
163 : undefined, // Undefined so the player knows it has to check the local storage
164
165 autoplay: this.getAutoPlayValue(autoplay, alreadyPlayed),
166
167 poster: commonOptions.poster,
168 inactivityTimeout: commonOptions.inactivityTimeout,
169 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
170
171 plugins,
172
173 controlBar: {
174 children: this.getControlBarChildren(this.mode, {
175 videoShortUUID: commonOptions.videoShortUUID,
176 p2pEnabled: commonOptions.p2pEnabled,
177
178 captions: commonOptions.captions,
179 peertubeLink: commonOptions.peertubeLink,
180 theaterButton: commonOptions.theaterButton,
181
182 nextVideo: commonOptions.nextVideo,
183 hasNextVideo: commonOptions.hasNextVideo,
184
185 previousVideo: commonOptions.previousVideo,
186 hasPreviousVideo: commonOptions.hasPreviousVideo
187 }) as any // FIXME: typings
188 }
189 }
190
191 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
192 Object.assign(videojsOptions, { language: commonOptions.language })
193 }
194
195 return videojsOptions
196 }
197
198 private addP2PMediaLoaderOptions (plugins: VideoJSPluginOptions) {
199 const p2pMediaLoaderOptions = this.options.p2pMediaLoader
200 const commonOptions = this.options.common
201
c4207f97
C
202 const redundancyUrlManager = new RedundancyUrlManager(this.options.p2pMediaLoader.redundancyBaseUrls)
203
204 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
205 redundancyUrlManager,
206 type: 'application/x-mpegURL',
207 startTime: commonOptions.startTime,
208 src: p2pMediaLoaderOptions.playlistUrl
209 }
210
c4207f97 211 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
ac5f679a 212 loader: this.getP2PMediaLoaderOptions(redundancyUrlManager),
c4207f97
C
213 segments: {
214 swarmId: p2pMediaLoaderOptions.playlistUrl
215 }
216 }
217
218 const hlsjs = {
219 levelLabelHandler: (level: { height: number, width: number }) => {
220 const resolution = Math.min(level.height || 0, level.width || 0)
221
222 const file = p2pMediaLoaderOptions.videoFiles.find(f => f.resolution.id === resolution)
223 // We don't have files for live videos
224 if (!file) return level.height
225
226 let label = file.resolution.label
227 if (file.fps >= 50) label += file.fps
228
229 return label
230 },
231 html5: {
232 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderConfig)
233 }
234 }
235
236 const toAssign = { p2pMediaLoader, hlsjs }
237 Object.assign(plugins, toAssign)
238
239 return toAssign
240 }
241
ac5f679a
C
242 private getP2PMediaLoaderOptions (redundancyUrlManager: RedundancyUrlManager): Partial<HybridLoaderSettings> {
243 let consumeOnly = false
244 if ((navigator as any)?.connection?.type === 'cellular') {
245 console.log('We are on a cellular connection: disabling seeding.')
246 consumeOnly = true
247 }
248
249 const trackerAnnounce = this.options.p2pMediaLoader.trackerAnnounce
250 .filter(t => t.startsWith('ws'))
251
252 const specificLiveOrVODOptions = this.options.common.isLive
253 ? { // Live
254 requiredSegmentsPriority: 1
255 }
256 : { // VOD
257 requiredSegmentsPriority: 3,
258
259 cachedSegmentExpiration: 86400000,
260 cachedSegmentsCount: 100,
261
262 httpDownloadMaxPriority: 9,
263 httpDownloadProbability: 0.06,
264 httpDownloadProbabilitySkipIfNoPeers: true,
265
266 p2pDownloadMaxPriority: 50
267 }
268
269 return {
270 trackerAnnounce,
ac5f679a 271 rtcConfig: getRtcConfig(),
6385fe58 272
ac5f679a 273 simultaneousHttpDownloads: 1,
6385fe58
C
274 httpFailedSegmentTimeout: 1000,
275
276 segmentValidator: segmentValidatorFactory(this.options.p2pMediaLoader.segmentsSha256Url, this.options.common.isLive),
ac5f679a 277 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager, 1),
6385fe58 278
ac5f679a
C
279 useP2P: this.options.common.p2pEnabled,
280 consumeOnly,
281
282 ...specificLiveOrVODOptions
283 }
284 }
285
c4207f97
C
286 private getHLSOptions (p2pMediaLoaderConfig: HlsJsEngineSettings) {
287 const base = {
288 capLevelToPlayerSize: true,
289 autoStartLoad: false,
290 liveSyncDurationCount: 5,
291
292 loader: new this.p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
293 }
294
295 const averageBandwidth = getAverageBandwidthInStore()
296 if (!averageBandwidth) return base
297
298 return {
299 ...base,
300
301 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
302 startLevel: -1,
303 testBandwidth: false,
304 debug: false
305 }
306 }
307
308 private addWebTorrentOptions (plugins: VideoJSPluginOptions, alreadyPlayed: boolean) {
309 const commonOptions = this.options.common
310 const webtorrentOptions = this.options.webtorrent
311 const p2pMediaLoaderOptions = this.options.p2pMediaLoader
312
313 const autoplay = this.getAutoPlayValue(commonOptions.autoplay, alreadyPlayed) === 'play'
314
315 const webtorrent = {
316 autoplay,
317
318 playerRefusedP2P: commonOptions.p2pEnabled === false,
319 videoDuration: commonOptions.videoDuration,
320 playerElement: commonOptions.playerElement,
321
322 videoFiles: webtorrentOptions.videoFiles.length !== 0
323 ? webtorrentOptions.videoFiles
324 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
325 : p2pMediaLoaderOptions?.videoFiles || [],
326
327 startTime: commonOptions.startTime
328 }
329
330 Object.assign(plugins, { webtorrent })
331 }
332
333 private getControlBarChildren (mode: PlayerMode, options: {
334 p2pEnabled: boolean
335 videoShortUUID: string
336
337 peertubeLink: boolean
338 theaterButton: boolean
339 captions: boolean
340
341 nextVideo?: () => void
342 hasNextVideo?: () => boolean
343
344 previousVideo?: () => void
345 hasPreviousVideo?: () => boolean
346 }) {
347 const settingEntries = []
348 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
349
350 // Keep an order
351 settingEntries.push('playbackRateMenuButton')
352 if (options.captions === true) settingEntries.push('captionsButton')
353 settingEntries.push('resolutionMenuButton')
354
355 const children = {}
356
357 if (options.previousVideo) {
358 const buttonOptions: NextPreviousVideoButtonOptions = {
359 type: 'previous',
360 handler: options.previousVideo,
361 isDisabled: () => {
362 if (!options.hasPreviousVideo) return false
363
364 return !options.hasPreviousVideo()
365 }
366 }
367
368 Object.assign(children, {
369 previousVideoButton: buttonOptions
370 })
371 }
372
373 Object.assign(children, { playToggle: {} })
374
375 if (options.nextVideo) {
376 const buttonOptions: NextPreviousVideoButtonOptions = {
377 type: 'next',
378 handler: options.nextVideo,
379 isDisabled: () => {
380 if (!options.hasNextVideo) return false
381
382 return !options.hasNextVideo()
383 }
384 }
385
386 Object.assign(children, {
387 nextVideoButton: buttonOptions
388 })
389 }
390
391 Object.assign(children, {
392 currentTimeDisplay: {},
393 timeDivider: {},
394 durationDisplay: {},
395 liveDisplay: {},
396
397 flexibleWidthSpacer: {},
398 progressControl: {
399 children: {
400 seekBar: {
401 children: {
402 [loadProgressBar]: {},
403 mouseTimeDisplay: {},
404 playProgressBar: {}
405 }
406 }
407 }
408 },
409
410 p2PInfoButton: {
411 p2pEnabled: options.p2pEnabled
412 },
413
414 muteToggle: {},
415 volumeControl: {},
416
417 settingsButton: {
418 setup: {
419 maxHeightOffset: 40
420 },
421 entries: settingEntries
422 }
423 })
424
425 if (options.peertubeLink === true) {
426 Object.assign(children, {
427 peerTubeLinkButton: { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
428 })
429 }
430
431 if (options.theaterButton === true) {
432 Object.assign(children, {
433 theaterButton: {}
434 })
435 }
436
437 Object.assign(children, {
438 fullscreenToggle: {}
439 })
440
441 return children
442 }
443
444 private getAutoPlayValue (autoplay: any, alreadyPlayed: boolean) {
445 if (autoplay !== true) return autoplay
446
447 // On first play, disable autoplay to avoid issues
448 // But if the player already played videos, we can safely autoplay next ones
449 if (isIOS() || isSafari()) {
450 return alreadyPlayed ? 'play' : false
451 }
452
453 return 'play'
454 }
455
456 getContextMenuOptions (player: videojs.Player, commonOptions: CommonOptions) {
457 const content = () => {
458 const isLoopEnabled = player.options_['loop']
459
460 const items = [
461 {
462 icon: 'repeat',
463 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
464 listener: function () {
465 player.options_['loop'] = !isLoopEnabled
466 }
467 },
468 {
469 label: player.localize('Copy the video URL'),
470 listener: function () {
471 copyToClipboard(buildVideoLink({ shortUUID: commonOptions.videoShortUUID }))
472 }
473 },
474 {
475 label: player.localize('Copy the video URL at the current time'),
476 listener: function (this: videojs.Player) {
477 const url = buildVideoLink({ shortUUID: commonOptions.videoShortUUID })
478
479 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
480 }
481 },
482 {
483 icon: 'code',
484 label: player.localize('Copy embed code'),
485 listener: () => {
486 copyToClipboard(buildVideoOrPlaylistEmbed(commonOptions.embedUrl, commonOptions.embedTitle))
487 }
488 }
489 ]
490
491 if (this.mode === 'webtorrent') {
492 items.push({
493 label: player.localize('Copy magnet URI'),
494 listener: function (this: videojs.Player) {
495 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
496 }
497 })
498 }
499
500 items.push({
501 icon: 'info',
502 label: player.localize('Stats for nerds'),
503 listener: () => {
504 player.stats().show()
505 }
506 })
507
508 return items.map(i => ({
509 ...i,
510 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label
511 }))
512 }
513
514 return { content }
515 }
516}