// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0. package spatialaudio import ( "fmt" "math" "runtime" "sync" "time" ) type AdaptiveConfig struct { Enabled bool `yaml:"enabled,omitempty"` PoseIntervalMs int `yaml:"pose_interval_ms,omitempty"` OverloadRatio float64 `yaml:"overload_ratio,omitempty"` RecoveryRatio float64 `yaml:"recovery_ratio,omitempty"` DegradeAfterMs int `yaml:"degrade_after_ms,omitempty"` RecoverAfterMs int `yaml:"recover_after_ms,omitempty"` CooldownMs int `yaml:"cooldown_ms,omitempty"` } func (c AdaptiveConfig) defaults() AdaptiveConfig { if c.PoseIntervalMs == 0 { c.PoseIntervalMs = 50 } if c.OverloadRatio == 0 { c.OverloadRatio = .7 } if c.RecoveryRatio == 0 { c.RecoveryRatio = .4 } if c.DegradeAfterMs == 0 { c.DegradeAfterMs = 2000 } if c.RecoverAfterMs == 0 { c.RecoverAfterMs = 10000 } if c.CooldownMs == 0 { c.CooldownMs = 3000 } return c } func (c AdaptiveConfig) validate() error { if c.PoseIntervalMs < 10 || c.PoseIntervalMs > 100 || !finite(c.OverloadRatio) || !finite(c.RecoveryRatio) || c.RecoveryRatio <= 0 || c.RecoveryRatio >= c.OverloadRatio || c.OverloadRatio > 1 || c.DegradeAfterMs < 1000 || c.RecoverAfterMs < 1000 || c.CooldownMs < 1000 { return fmt.Errorf("spatial_audio: invalid adaptive timing or load thresholds") } return nil } // Reports measure spatial workers, not total process CPU. Worst room deadline // pressure protects one saturated worker; aggregate busy time accounts for // other spatial rooms. Report once a second, never lock for every audio sample. type loadContribution struct { at time.Time busy, deadline float64 } var spatialLoad = struct { sync.Mutex rooms map[*Engine]loadContribution }{rooms: make(map[*Engine]loadContribution)} func reportSpatialLoad(e *Engine, now time.Time, elapsed, busy time.Duration, ticks, missed uint64) float64 { spatialLoad.Lock() defer spatialLoad.Unlock() average := float64(busy) / float64(max(ticks, 1)) / float64(10*time.Millisecond) missedRatio := float64(missed) / float64(max(ticks+missed, 1)) spatialLoad.rooms[e] = loadContribution{now, float64(busy) / float64(elapsed), math.Max(average, missedRatio/.05)} var total, worst float64 for room, load := range spatialLoad.rooms { if now.Sub(load.at) > 3*time.Second { delete(spatialLoad.rooms, room) continue } total += load.busy worst = math.Max(worst, load.deadline) } return math.Max(worst, total/float64(runtime.GOMAXPROCS(0))) } func forgetSpatialLoad(e *Engine) { spatialLoad.Lock() delete(spatialLoad.rooms, e) spatialLoad.Unlock() } type adaptiveController struct { config AdaptiveConfig enabled bool level int pressure float64 sampled bool windowStart time.Time busy time.Duration ticks, missed uint64 highSince, lowSince, changedAt time.Time transitions uint64 } func (a *adaptiveController) setEnabled(enabled bool) { a.enabled = enabled a.highSince = time.Time{} a.lowSince = time.Time{} if !enabled && a.level != 0 { a.level = 0 a.transitions++ } } func (a *adaptiveController) observe(e *Engine, now time.Time, duration time.Duration, missed uint64) bool { if a.windowStart.IsZero() { a.windowStart = now } a.busy += duration a.ticks++ a.missed += missed elapsed := now.Sub(a.windowStart) if elapsed < time.Second { return false } pressure := reportSpatialLoad(e, now, elapsed, a.busy, a.ticks, a.missed) a.busy = 0 a.ticks = 0 a.missed = 0 a.windowStart = now if !a.sampled { a.pressure = pressure a.sampled = true } else { a.pressure += .25 * (pressure - a.pressure) } if !a.enabled { return false } if a.pressure >= a.config.OverloadRatio { a.lowSince = time.Time{} if a.highSince.IsZero() { a.highSince = now } } else if a.pressure <= a.config.RecoveryRatio { a.highSince = time.Time{} if a.lowSince.IsZero() { a.lowSince = now } } else { a.highSince = time.Time{} a.lowSince = time.Time{} } if now.Sub(a.changedAt) < time.Duration(a.config.CooldownMs)*time.Millisecond { return false } previous := a.level if !a.highSince.IsZero() && now.Sub(a.highSince) >= time.Duration(a.config.DegradeAfterMs)*time.Millisecond && a.level < 3 { a.level++ } if !a.lowSince.IsZero() && now.Sub(a.lowSince) >= time.Duration(a.config.RecoverAfterMs)*time.Millisecond && a.level > 0 { a.level-- } if previous == a.level { return false } a.transitions++ a.changedAt = now a.highSince = time.Time{} a.lowSince = time.Time{} return true } func (a *adaptiveController) poseInterval() time.Duration { if !a.enabled { return 10 * time.Millisecond } return time.Duration(a.config.PoseIntervalMs*[]int{1, 2, 3, 5}[a.level]) * time.Millisecond } func (a *adaptiveController) minWallPriority() int { return []int{0, 0, 50, 100}[a.level] } func (a *adaptiveController) hrtfMode(requested bool, configured string) string { if !requested || a.level == 3 { return "off" } if configured == "nearest" || a.level > 0 { return "nearest" } return "bilinear" }