uploadbudget

package
v0.3.17 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: GPL-3.0 Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// TargetUtilizationPct leaves ~15% headroom for TCP/TLS overhead, ACKs,
	// metadata browsing and segment bitrate spikes.
	TargetUtilizationPct = 85

	// MinStreamBitrateKbps prevents extreme crowding from crushing a stream to
	// an unplayable rate.
	MinStreamBitrateKbps = 800

	// DefaultLiveStreamKbps is the fallback estimate for an active remote Live
	// TV stream whose bitrate has not been probed yet.
	DefaultLiveStreamKbps = 4000

	// StepDownMarginPct avoids reacting to negligible (<8%) budget shifts on
	// an already-running stream when total usage is within target.
	StepDownMarginPct = 92

	// StepUpMarginPct requires >= 15% headroom above the next quality step
	// before stepping an adaptive stream back up (hysteresis).
	StepUpMarginPct = 115

	// Cooldowns prevent flapping when viewers join, seek, pause or leave.
	StepDownCooldown = 8 * time.Second
	StepUpCooldown   = 20 * time.Second
)
View Source
const (
	// CapSourceUploadBudget marks a stream whose bitrate cap was chosen by the
	// shared remote upload budget.
	CapSourceUploadBudget = "upload_budget"
)

Variables

This section is empty.

Functions

func AllocateForNewStream

func AllocateForNewStream(usableKbps, externalKbps int, active []ActiveStream, excludeID string, newDemandKbps int) int

AllocateForNewStream computes the dynamic bitrate cap (kbps) for a newly starting remote stream so that all active remote streams (Ether VOD + Live TV + external sibling PMS WAN streams) stay within usableKbps (~85% of total budget). Returns 0 when no upload budget is active.

Invariants:

  • LAN streams (!s.Remote) are never counted.
  • Direct-play / non-adaptive remote streams are counted at their bitrate without being forced to transcode.
  • Live TV remote streams are counted.

func UsableBudgetKbps

func UsableBudgetKbps(capacityKbps int) int

UsableBudgetKbps returns ~85% of total upload capacity (0 when no budget).

Types

type ActiveStream

type ActiveStream struct {
	ID              string
	Remote          bool
	Live            bool
	DirectPlay      bool
	Adaptive        bool
	BitrateKbps     int   // current effective stream bitrate
	BaseBitrateKbps int   // uncapped natural/base bitrate demand (0 = unknown/high)
	CurrentCapKbps  int   // currently applied upload-budget cap (0 = uncapped)
	RungKbps        []int // optional descending ladder rung bitrates (base -> lowest)
}

ActiveStream summarizes one running Ether stream for budget accounting.

type Adjustment

type Adjustment struct {
	SessionID string
	CapKbps   int
	StepDown  bool
}

Adjustment asks a running adaptive remote stream to adopt a new upload budget cap (0 clears the budget cap so the stream steps back up to base).

type Estimator

type Estimator struct {
	// contains filtered or unexported fields
}

Estimator learns a conservative rolling estimate of the server's usable internet upload capacity strictly from real remote streams (never via third-party speed tests). Until sufficient evidence exists, EstimateKbps returns 0 so Ether keeps its existing unlimited default.

func NewEstimator

func NewEstimator(now func() time.Time) *Estimator

NewEstimator creates a passive upload capacity estimator.

func (*Estimator) Estimate

func (e *Estimator) Estimate() (kbps int, samples int)

Estimate returns the conservative rolling upload capacity estimate in kbps (0 when insufficient evidence exists) and the count of active samples.

func (*Estimator) Observe

func (e *Estimator) Observe(obs Observation) bool

Observe records one remote delivery observation. Non-evidential or noisy samples are ignored cleanly.

type ExternalServerStatus

type ExternalServerStatus struct {
	MachineID     string    `json:"machineId,omitempty"`
	Name          string    `json:"name"`
	Source        string    `json:"source"`
	RemoteStreams int       `json:"remoteStreams"`
	BandwidthKbps int       `json:"bandwidthKbps"`
	Reachable     bool      `json:"reachable"`
	LastChecked   time.Time `json:"lastChecked,omitzero"`
}

ExternalServerStatus reports the latest polled remote load on one linked PMS.

type ExternalUsage

type ExternalUsage struct {
	TotalKbps     int
	RemoteStreams int
	Servers       []ExternalServerStatus
	UpdatedAt     time.Time
}

ExternalUsage aggregates remote bandwidth across all linked sibling PMS servers sharing this connection.

type HysteresisController

type HysteresisController struct {
	// contains filtered or unexported fields
}

HysteresisController tracks per-session step-down / step-up timing so running adaptive HLS remote streams step down promptly when capacity tightens and step back up smoothly without flapping once headroom stabilizes.

func NewHysteresisController

func NewHysteresisController() *HysteresisController

NewHysteresisController creates a stateful hysteresis controller for running adaptive remote streams.

func (*HysteresisController) Reconcile

func (h *HysteresisController) Reconcile(now time.Time, usableKbps, externalKbps int, active []ActiveStream) []Adjustment

Reconcile computes budget cap adjustments for currently running adaptive remote streams. LAN streams and direct-play/non-adaptive streams are never adjusted.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager coordinates passive upload capacity estimation, dynamic remote stream admission caps, adaptive HLS rung stepping with hysteresis, and conditional sibling PMS bandwidth polling.

func NewManager

func NewManager(opts Options) *Manager

NewManager creates an upload budget coordinator. Call Run in a background goroutine to keep sibling PMS readings and adaptive rungs reconciled while remote streams are active.

func (*Manager) EffectiveCapacity

func (m *Manager) EffectiveCapacity() (capacityKbps int, source string, overrideKbps int, measuredKbps int, samples int)

EffectiveCapacity returns the active upload capacity in kbps and its source ("override", "measured", or "learning"). Override always wins when > 0.

func (*Manager) ObserveDelivery

func (m *Manager) ObserveDelivery(sessionID string, obs Observation) bool

ObserveDelivery records a passive remote delivery timing/backlog measurement into the upload capacity estimator, combining it with any concurrent remote Ether streams and sibling PMS WAN bandwidth.

func (*Manager) OnSessionsChanged

func (m *Manager) OnSessionsChanged()

OnSessionsChanged signals the background coordinator to reconcile active remote streams and conditional sibling PMS polling.

func (*Manager) ReconcileOnce

func (m *Manager) ReconcileOnce(ctx context.Context) []Adjustment

ReconcileOnce performs one synchronous pass: polls linked PMS servers ONLY when Ether currently has active remote streams, prunes ended cap records, and applies hysteresis-guarded step-down / step-up adjustments to running adaptive remote HLS streams.

func (*Manager) RecordSessionCap

func (m *Manager) RecordSessionCap(sessionID string, capKbps int, fromBudget bool)

RecordSessionCap records or clears whether sessionID's active bitrate cap came from the shared upload budget.

func (*Manager) RemoteCapForNewStream

func (m *Manager) RemoteCapForNewStream(ctx context.Context, sessionID string, remote bool, allowTranscoding bool, existingCapKbps int, demandKbps int) (capKbps int, fromBudget bool)

RemoteCapForNewStream computes the dynamic bitrate cap for a newly starting stream. LAN streams (!remote) are never affected. Direct-play-only streams (allowTranscoding == false or VideoTranscodingOff) are never forced to transcode.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context)

Run keeps sibling PMS polling (strictly while Ether has remote streams) and adaptive HLS rung adjustments synchronized until ctx is cancelled.

func (*Manager) SessionBudgetCap

func (m *Manager) SessionBudgetCap(sessionID string) (capKbps int, active bool)

SessionBudgetCap reports whether sessionID is currently capped by the shared upload budget and at what kbps ceiling.

func (*Manager) Status

func (m *Manager) Status() StatusSnapshot

Status returns a fast, non-blocking snapshot of the upload budget and live remote usage across Ether and any linked sibling Plex Media Servers.

type Observation

type Observation struct {
	At                time.Time
	Bytes             int64
	Duration          time.Duration
	SegDuration       time.Duration
	StreamRateKbps    int
	AggregateKbps     int
	MediaBitrateKbps  int
	TCPBacklogBytes   int
	Starved           bool
	ConcurrentStreams int
}

Observation captures one passive throughput measurement from an active remote Ether stream. LAN streams must never be passed to the estimator.

type Options

type Options struct {
	Logger *slog.Logger
	Now    func() time.Time

	// OverrideKbps reads transcode.remoteUploadBudgetKbps (0 = auto).
	OverrideKbps func() int
	// VideoTranscodingOff reports whether movies/shows forbid video encoding.
	VideoTranscodingOff func() bool

	// ActiveSessions snapshots currently active Ether VOD + Live TV sessions.
	ActiveSessions func() []*core.PlaySession
	// AdaptiveRungs returns a running HLS session's ladder rung bitrates (kbps,
	// high->low) and current budget cap, or ok=false when not an adaptive HLS
	// session.
	AdaptiveInfo func(sessionID string) (rungsKbps []int, currentCapKbps int, adaptive bool)
	// ApplySessionCap updates a running adaptive HLS remote stream's dynamic
	// upload budget cap (0 clears the cap to step back up).
	ApplySessionCap func(sessionID string, capKbps int) (applied bool, rungID string)

	// Poller optionally queries already-linked sibling PMS servers while Ether
	// has active remote streams.
	Poller *PMSPoller
}

Options wires the upload budget coordinator into Ether's live runtime.

type PMSPoller

type PMSPoller struct {
	// contains filtered or unexported fields
}

PMSPoller polls /status/sessions on already-linked Plex Media Servers, strictly on demand when Ether itself has active remote streams.

func NewPMSPoller

func NewPMSPoller(opts PMSPollerOptions) *PMSPoller

NewPMSPoller constructs a sibling PMS poller.

func (*PMSPoller) ClearIdle

func (p *PMSPoller) ClearIdle()

ClearIdle resets live external usage when Ether has no active remote streams.

func (*PMSPoller) PollCount

func (p *PMSPoller) PollCount() int64

PollCount returns how many /status/sessions poll cycles ran (useful in tests to verify zero polling when Ether has no remote streams).

func (*PMSPoller) PollIfDue

func (p *PMSPoller) PollIfDue(ctx context.Context, force bool) ExternalUsage

PollIfDue queries linked PMS servers if at least pmsPollInterval has elapsed (or force is true). Callers must only invoke this when Ether itself has at least one active remote stream.

func (*PMSPoller) Snapshot

func (p *PMSPoller) Snapshot() ExternalUsage

Snapshot returns the current cached external PMS usage without network I/O.

type PMSPollerOptions

type PMSPollerOptions struct {
	HTTP             *http.Client
	ClientID         string
	Now              func() time.Time
	LinkedPMS        func(context.Context) ([]ServerTarget, error)
	AccountResources func(context.Context) (resources []plextv.Resource, selfMachineID string, selfPublicIP string, err error)
}

PMSPollerOptions configures discovery and polling of already-linked PMS servers. No new URL/token setting is ever added: servers come solely from existing Plex Media Server links and/or the owner's Plex account resources.

type ServerTarget

type ServerTarget struct {
	MachineID string
	Name      string
	BaseURLs  []string // tried in order (local non-relay first)
	Token     string
	Source    string // "linked_pms" or "plex_account"
}

ServerTarget identifies one already-linked Plex Media Server whose active remote sessions share this internet connection.

type StatusSnapshot

type StatusSnapshot struct {
	Enabled             bool                   `json:"enabled"`
	Source              string                 `json:"source"` // "override" | "measured" | "learning"
	OverrideKbps        int                    `json:"overrideKbps"`
	MeasuredKbps        int                    `json:"measuredKbps"`
	MeasuredSamples     int                    `json:"measuredSamples"`
	EffectiveKbps       int                    `json:"effectiveKbps"`
	UsableKbps          int                    `json:"usableKbps"`
	EtherRemoteKbps     int                    `json:"etherRemoteKbps"`
	EtherRemoteStreams  int                    `json:"etherRemoteStreams"`
	BudgetCappedStreams int                    `json:"budgetCappedStreams"`
	OtherPMSKbps        int                    `json:"otherPmsKbps"`
	OtherPMSStreams     int                    `json:"otherPmsStreams"`
	TotalUsedKbps       int                    `json:"totalUsedKbps"`
	OtherServers        []ExternalServerStatus `json:"otherServers,omitempty"`
}

StatusSnapshot is the live upload budget status exposed to the owner console.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL