1 import videojs from 'video.js'
2 import { HlsJsEngineSettings } from '@peertube/p2p-media-loader-hlsjs'
3 import { PluginsManager } from '@root-helpers/plugins-manager'
4 import { buildVideoLink, decorateVideoLink } from '@shared/core-utils'
5 import { isDefaultLocale } from '@shared/core-utils/i18n'
6 import { VideoFile } from '@shared/models'
7 import { copyToClipboard } from '../../root-helpers/utils'
8 import { RedundancyUrlManager } from './p2p-media-loader/redundancy-url-manager'
9 import { segmentUrlBuilderFactory } from './p2p-media-loader/segment-url-builder'
10 import { segmentValidatorFactory } from './p2p-media-loader/segment-validator'
11 import { getAverageBandwidthInStore } from './peertube-player-local-storage'
13 NextPreviousVideoButtonOptions,
14 P2PMediaLoaderPluginOptions,
15 PeerTubeLinkButtonOptions,
16 PlaylistPluginOptions,
20 } from './peertube-videojs-typings'
21 import { buildVideoOrPlaylistEmbed, getRtcConfig, isIOS, isSafari } from './utils'
22 import { HybridLoaderSettings } from '@peertube/p2p-media-loader-core'
24 export type PlayerMode = 'webtorrent' | 'p2p-media-loader'
26 export type WebtorrentOptions = {
27 videoFiles: VideoFile[]
30 export type P2PMediaLoaderOptions = {
32 segmentsSha256Url: string
33 trackerAnnounce: string[]
34 redundancyBaseUrls: string[]
35 videoFiles: VideoFile[]
38 export interface CustomizationOptions {
39 startTime: number | string
40 stopTime: number | string
51 export interface CommonOptions extends CustomizationOptions {
52 playerElement: HTMLVideoElement
53 onPlayerElementChange: (element: HTMLVideoElement) => void
58 nextVideo?: () => void
59 hasNextVideo?: () => boolean
61 previousVideo?: () => void
62 hasPreviousVideo?: () => boolean
64 playlist?: PlaylistPluginOptions
67 enableHotkeys: boolean
68 inactivityTimeout: number
71 theaterButton: boolean
82 videoCaptions: VideoJSCaption[]
85 videoShortUUID: string
87 userWatching?: UserWatching
91 errorNotifier: (message: string) => void
94 export type PeertubePlayerManagerOptions = {
96 webtorrent: WebtorrentOptions
97 p2pMediaLoader?: P2PMediaLoaderOptions
99 pluginsManager: PluginsManager
102 export class PeertubePlayerOptionsBuilder {
105 private mode: PlayerMode,
106 private options: PeertubePlayerManagerOptions,
107 private p2pMediaLoaderModule?: any
112 getVideojsOptions (alreadyPlayed: boolean): videojs.PlayerOptions {
113 const commonOptions = this.options.common
114 const isHLS = this.mode === 'p2p-media-loader'
116 let autoplay = this.getAutoPlayValue(commonOptions.autoplay, alreadyPlayed)
118 preloadTextTracks: false
121 const plugins: VideoJSPluginOptions = {
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
136 if (commonOptions.playlist) {
137 plugins.playlist = commonOptions.playlist
141 const { hlsjs } = this.addP2PMediaLoaderOptions(plugins)
143 Object.assign(html5, hlsjs.html5)
146 if (this.mode === 'webtorrent') {
147 this.addWebTorrentOptions(plugins, alreadyPlayed)
149 // WebTorrent plugin handles autoplay, because we do some hackish stuff in there
153 const videojsOptions = {
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,
161 muted: commonOptions.muted !== undefined
162 ? commonOptions.muted
163 : undefined, // Undefined so the player knows it has to check the local storage
165 autoplay: this.getAutoPlayValue(autoplay, alreadyPlayed),
167 poster: commonOptions.poster,
168 inactivityTimeout: commonOptions.inactivityTimeout,
169 playbackRates: [ 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2 ],
174 children: this.getControlBarChildren(this.mode, {
175 videoShortUUID: commonOptions.videoShortUUID,
176 p2pEnabled: commonOptions.p2pEnabled,
178 captions: commonOptions.captions,
179 peertubeLink: commonOptions.peertubeLink,
180 theaterButton: commonOptions.theaterButton,
182 nextVideo: commonOptions.nextVideo,
183 hasNextVideo: commonOptions.hasNextVideo,
185 previousVideo: commonOptions.previousVideo,
186 hasPreviousVideo: commonOptions.hasPreviousVideo
187 }) as any // FIXME: typings
191 if (commonOptions.language && !isDefaultLocale(commonOptions.language)) {
192 Object.assign(videojsOptions, { language: commonOptions.language })
195 return videojsOptions
198 private addP2PMediaLoaderOptions (plugins: VideoJSPluginOptions) {
199 const p2pMediaLoaderOptions = this.options.p2pMediaLoader
200 const commonOptions = this.options.common
202 const redundancyUrlManager = new RedundancyUrlManager(this.options.p2pMediaLoader.redundancyBaseUrls)
204 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
205 redundancyUrlManager,
206 type: 'application/x-mpegURL',
207 startTime: commonOptions.startTime,
208 src: p2pMediaLoaderOptions.playlistUrl
211 const p2pMediaLoaderConfig: HlsJsEngineSettings = {
212 loader: this.getP2PMediaLoaderOptions(redundancyUrlManager),
214 swarmId: p2pMediaLoaderOptions.playlistUrl
219 levelLabelHandler: (level: { height: number, width: number }) => {
220 const resolution = Math.min(level.height || 0, level.width || 0)
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
226 let label = file.resolution.label
227 if (file.fps >= 50) label += file.fps
232 hlsjsConfig: this.getHLSOptions(p2pMediaLoaderConfig)
236 const toAssign = { p2pMediaLoader, hlsjs }
237 Object.assign(plugins, toAssign)
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.')
249 const trackerAnnounce = this.options.p2pMediaLoader.trackerAnnounce
250 .filter(t => t.startsWith('ws'))
252 const specificLiveOrVODOptions = this.options.common.isLive
254 requiredSegmentsPriority: 1
257 requiredSegmentsPriority: 3,
259 cachedSegmentExpiration: 86400000,
260 cachedSegmentsCount: 100,
262 httpDownloadMaxPriority: 9,
263 httpDownloadProbability: 0.06,
264 httpDownloadProbabilitySkipIfNoPeers: true,
266 p2pDownloadMaxPriority: 50
271 segmentValidator: segmentValidatorFactory(this.options.p2pMediaLoader.segmentsSha256Url, this.options.common.isLive),
272 rtcConfig: getRtcConfig(),
273 simultaneousHttpDownloads: 1,
274 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager, 1),
275 useP2P: this.options.common.p2pEnabled,
278 ...specificLiveOrVODOptions
282 private getHLSOptions (p2pMediaLoaderConfig: HlsJsEngineSettings) {
284 capLevelToPlayerSize: true,
285 autoStartLoad: false,
286 liveSyncDurationCount: 5,
288 loader: new this.p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass()
291 const averageBandwidth = getAverageBandwidthInStore()
292 if (!averageBandwidth) return base
297 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
299 testBandwidth: false,
304 private addWebTorrentOptions (plugins: VideoJSPluginOptions, alreadyPlayed: boolean) {
305 const commonOptions = this.options.common
306 const webtorrentOptions = this.options.webtorrent
307 const p2pMediaLoaderOptions = this.options.p2pMediaLoader
309 const autoplay = this.getAutoPlayValue(commonOptions.autoplay, alreadyPlayed) === 'play'
314 playerRefusedP2P: commonOptions.p2pEnabled === false,
315 videoDuration: commonOptions.videoDuration,
316 playerElement: commonOptions.playerElement,
318 videoFiles: webtorrentOptions.videoFiles.length !== 0
319 ? webtorrentOptions.videoFiles
320 // The WebTorrent plugin won't be able to play these files, but it will fallback to HTTP mode
321 : p2pMediaLoaderOptions?.videoFiles || [],
323 startTime: commonOptions.startTime
326 Object.assign(plugins, { webtorrent })
329 private getControlBarChildren (mode: PlayerMode, options: {
331 videoShortUUID: string
333 peertubeLink: boolean
334 theaterButton: boolean
337 nextVideo?: () => void
338 hasNextVideo?: () => boolean
340 previousVideo?: () => void
341 hasPreviousVideo?: () => boolean
343 const settingEntries = []
344 const loadProgressBar = mode === 'webtorrent' ? 'peerTubeLoadProgressBar' : 'loadProgressBar'
347 settingEntries.push('playbackRateMenuButton')
348 if (options.captions === true) settingEntries.push('captionsButton')
349 settingEntries.push('resolutionMenuButton')
353 if (options.previousVideo) {
354 const buttonOptions: NextPreviousVideoButtonOptions = {
356 handler: options.previousVideo,
358 if (!options.hasPreviousVideo) return false
360 return !options.hasPreviousVideo()
364 Object.assign(children, {
365 previousVideoButton: buttonOptions
369 Object.assign(children, { playToggle: {} })
371 if (options.nextVideo) {
372 const buttonOptions: NextPreviousVideoButtonOptions = {
374 handler: options.nextVideo,
376 if (!options.hasNextVideo) return false
378 return !options.hasNextVideo()
382 Object.assign(children, {
383 nextVideoButton: buttonOptions
387 Object.assign(children, {
388 currentTimeDisplay: {},
393 flexibleWidthSpacer: {},
398 [loadProgressBar]: {},
399 mouseTimeDisplay: {},
407 p2pEnabled: options.p2pEnabled
417 entries: settingEntries
421 if (options.peertubeLink === true) {
422 Object.assign(children, {
423 peerTubeLinkButton: { shortUUID: options.videoShortUUID } as PeerTubeLinkButtonOptions
427 if (options.theaterButton === true) {
428 Object.assign(children, {
433 Object.assign(children, {
440 private getAutoPlayValue (autoplay: any, alreadyPlayed: boolean) {
441 if (autoplay !== true) return autoplay
443 // On first play, disable autoplay to avoid issues
444 // But if the player already played videos, we can safely autoplay next ones
445 if (isIOS() || isSafari()) {
446 return alreadyPlayed ? 'play' : false
452 getContextMenuOptions (player: videojs.Player, commonOptions: CommonOptions) {
453 const content = () => {
454 const isLoopEnabled = player.options_['loop']
459 label: player.localize('Play in loop') + (isLoopEnabled ? '<span class="vjs-icon-tick-white"></span>' : ''),
460 listener: function () {
461 player.options_['loop'] = !isLoopEnabled
465 label: player.localize('Copy the video URL'),
466 listener: function () {
467 copyToClipboard(buildVideoLink({ shortUUID: commonOptions.videoShortUUID }))
471 label: player.localize('Copy the video URL at the current time'),
472 listener: function (this: videojs.Player) {
473 const url = buildVideoLink({ shortUUID: commonOptions.videoShortUUID })
475 copyToClipboard(decorateVideoLink({ url, startTime: this.currentTime() }))
480 label: player.localize('Copy embed code'),
482 copyToClipboard(buildVideoOrPlaylistEmbed(commonOptions.embedUrl, commonOptions.embedTitle))
487 if (this.mode === 'webtorrent') {
489 label: player.localize('Copy magnet URI'),
490 listener: function (this: videojs.Player) {
491 copyToClipboard(this.webtorrent().getCurrentVideoFile().magnetUri)
498 label: player.localize('Stats for nerds'),
500 player.stats().show()
504 return items.map(i => ({
506 label: `<span class="vjs-icon-${i.icon || 'link-2'}"></span>` + i.label