1 import { HybridLoaderSettings } from '@peertube/p2p-media-loader-core'
2 import { HlsJsEngineSettings } from '@peertube/p2p-media-loader-hlsjs'
3 import { logger } from '@root-helpers/logger'
4 import { LiveVideoLatencyMode } from '@shared/models'
5 import { getAverageBandwidthInStore } from '../../peertube-player-local-storage'
6 import { P2PMediaLoader, P2PMediaLoaderPluginOptions } from '../../types'
7 import { PeertubePlayerManagerOptions } from '../../types/manager-options'
8 import { getRtcConfig, isSameOrigin } from '../common'
9 import { RedundancyUrlManager } from '../p2p-media-loader/redundancy-url-manager'
10 import { segmentUrlBuilderFactory } from '../p2p-media-loader/segment-url-builder'
11 import { segmentValidatorFactory } from '../p2p-media-loader/segment-validator'
13 export class HLSOptionsBuilder {
16 private options: PeertubePlayerManagerOptions,
17 private p2pMediaLoaderModule?: any
22 async getPluginOptions () {
23 const commonOptions = this.options.common
25 const redundancyUrlManager = new RedundancyUrlManager(this.options.p2pMediaLoader.redundancyBaseUrls)
27 const p2pMediaLoaderConfig = await this.options.pluginsManager.runHook(
28 'filter:internal.player.p2p-media-loader.options.result',
29 this.getP2PMediaLoaderOptions(redundancyUrlManager)
31 const loader = new this.p2pMediaLoaderModule.Engine(p2pMediaLoaderConfig).createLoaderClass() as P2PMediaLoader
33 const p2pMediaLoader: P2PMediaLoaderPluginOptions = {
34 requiresAuth: commonOptions.requiresAuth,
35 videoFileToken: commonOptions.videoFileToken,
38 type: 'application/x-mpegURL',
39 startTime: commonOptions.startTime,
40 src: this.options.p2pMediaLoader.playlistUrl,
45 levelLabelHandler: (level: { height: number, width: number }) => {
46 const resolution = Math.min(level.height || 0, level.width || 0)
48 const file = this.options.p2pMediaLoader.videoFiles.find(f => f.resolution.id === resolution)
49 // We don't have files for live videos
50 if (!file) return level.height
52 let label = file.resolution.label
53 if (file.fps >= 50) label += file.fps
60 hlsjsConfig: this.getHLSJSOptions(loader)
63 return { p2pMediaLoader, hlsjs, html5 }
66 // ---------------------------------------------------------------------------
68 private getP2PMediaLoaderOptions (redundancyUrlManager: RedundancyUrlManager): HlsJsEngineSettings {
69 let consumeOnly = false
70 if ((navigator as any)?.connection?.type === 'cellular') {
71 logger.info('We are on a cellular connection: disabling seeding.')
75 const trackerAnnounce = this.options.p2pMediaLoader.trackerAnnounce
76 .filter(t => t.startsWith('ws'))
78 const specificLiveOrVODOptions = this.options.common.isLive
79 ? this.getP2PMediaLoaderLiveOptions()
80 : this.getP2PMediaLoaderVODOptions()
85 rtcConfig: getRtcConfig(),
87 simultaneousHttpDownloads: 1,
88 httpFailedSegmentTimeout: 1000,
90 xhrSetup: (xhr, url) => {
91 if (!this.options.common.requiresAuth) return
92 if (!isSameOrigin(this.options.common.serverUrl, url)) return
94 xhr.setRequestHeader('Authorization', this.options.common.authorizationHeader())
97 segmentValidator: segmentValidatorFactory({
98 segmentsSha256Url: this.options.p2pMediaLoader.segmentsSha256Url,
99 authorizationHeader: this.options.common.authorizationHeader,
100 requiresAuth: this.options.common.requiresAuth,
101 serverUrl: this.options.common.serverUrl
104 segmentUrlBuilder: segmentUrlBuilderFactory(redundancyUrlManager),
106 useP2P: this.options.common.p2pEnabled,
109 ...specificLiveOrVODOptions
112 swarmId: this.options.p2pMediaLoader.playlistUrl,
113 forwardSegmentCount: specificLiveOrVODOptions.p2pDownloadMaxPriority ?? 20
118 private getP2PMediaLoaderLiveOptions (): Partial<HybridLoaderSettings> {
120 requiredSegmentsPriority: 1
123 const latencyMode = this.options.common.liveOptions.latencyMode
125 switch (latencyMode) {
126 case LiveVideoLatencyMode.SMALL_LATENCY:
131 requiredSegmentsPriority: 10
134 case LiveVideoLatencyMode.HIGH_LATENCY:
142 private getP2PMediaLoaderVODOptions (): Partial<HybridLoaderSettings> {
144 requiredSegmentsPriority: 3,
145 skipSegmentBuilderPriority: 1,
147 cachedSegmentExpiration: 86400000,
148 cachedSegmentsCount: 100,
150 httpDownloadMaxPriority: 9,
151 httpDownloadProbability: 0.06,
152 httpDownloadProbabilitySkipIfNoPeers: true,
154 p2pDownloadMaxPriority: 50
158 // ---------------------------------------------------------------------------
160 private getHLSJSOptions (loader: P2PMediaLoader) {
161 const specificLiveOrVODOptions = this.options.common.isLive
162 ? this.getHLSLiveOptions()
163 : this.getHLSVODOptions()
166 capLevelToPlayerSize: true,
167 autoStartLoad: false,
171 ...specificLiveOrVODOptions
174 const averageBandwidth = getAverageBandwidthInStore()
175 if (!averageBandwidth) return base
180 abrEwmaDefaultEstimate: averageBandwidth * 8, // We want bit/s
181 backBufferLength: 90,
183 testBandwidth: false,
188 private getHLSLiveOptions () {
189 const latencyMode = this.options.common.liveOptions.latencyMode
191 switch (latencyMode) {
192 case LiveVideoLatencyMode.SMALL_LATENCY:
194 liveSyncDurationCount: 2
197 case LiveVideoLatencyMode.HIGH_LATENCY:
199 liveSyncDurationCount: 10
204 liveSyncDurationCount: 5
209 private getHLSVODOptions () {
211 liveSyncDurationCount: 5