Files
arimius 909e51bc0a
Test / test (pull_request) Canceled after 0s
PR Slack Notifier / notify-devs (pull_request) Canceled after 0s
Add server-side spatial audio with HRTF, occlusion and adaptive quality
2026-10-05 17:29:30 +03:00

253 lines
7.7 KiB
Go

// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"fmt"
"math"
"time"
)
const SampleRate = 48000
const BlockSamples = 480
const PacketSamples = 960
type Config struct {
Enabled bool `yaml:"enabled,omitempty"`
RoomPrefix string `yaml:"room_prefix,omitempty"`
MaxParticipants int `yaml:"max_participants,omitempty"`
NearDistance float64 `yaml:"near_distance,omitempty"`
MaxDistance float64 `yaml:"max_distance,omitempty"`
SmoothingMs int `yaml:"smoothing_ms,omitempty"`
PoseTimeoutMs int `yaml:"pose_timeout_ms,omitempty"`
JitterMs int `yaml:"jitter_ms,omitempty"`
Bitrate int `yaml:"bitrate,omitempty"`
Library string `yaml:"library,omitempty"`
DebugStats bool `yaml:"debug_stats,omitempty"`
Occlusion OcclusionConfig `yaml:"occlusion,omitempty"`
HRTF HRTFConfig `yaml:"hrtf,omitempty"`
Adaptive AdaptiveConfig `yaml:"adaptive,omitempty"`
}
func (c Config) Defaults() Config {
c.Adaptive = c.Adaptive.defaults()
if c.HRTF.Interpolation == "" {
c.HRTF.Interpolation = "bilinear"
}
if c.Occlusion.MaxObjects == 0 {
c.Occlusion.MaxObjects = 64
}
if c.MaxParticipants == 0 {
c.MaxParticipants = 32
}
if c.MaxDistance == 0 {
c.MaxDistance = 20
if c.NearDistance == 0 {
c.NearDistance = 1
}
}
if c.SmoothingMs == 0 {
c.SmoothingMs = 30
}
if c.PoseTimeoutMs == 0 {
c.PoseTimeoutMs = 500
}
if c.JitterMs == 0 {
c.JitterMs = 40
}
if c.Bitrate == 0 {
c.Bitrate = 64000
}
return c
}
func (c Config) Validate() error {
if err := c.Adaptive.validate(); err != nil {
return err
}
if c.HRTF.Interpolation != "bilinear" && c.HRTF.Interpolation != "nearest" {
return fmt.Errorf("spatial_audio: hrtf interpolation must be nearest or bilinear")
}
if c.Occlusion.MaxObjects < 1 || c.Occlusion.MaxObjects > 512 {
return fmt.Errorf("spatial_audio: invalid occlusion max_objects")
}
if !finite(c.NearDistance) || !finite(c.MaxDistance) || c.NearDistance < 0 || c.MaxDistance <= c.NearDistance {
return fmt.Errorf("spatial_audio: require 0 <= near_distance < max_distance")
}
if c.MaxParticipants < 1 || c.MaxParticipants > 128 || c.SmoothingMs < 1 || c.SmoothingMs > 1000 || c.PoseTimeoutMs < 100 || c.JitterMs < 10 || c.JitterMs > 200 || c.Bitrate < 16000 || c.Bitrate > 256000 {
return fmt.Errorf("spatial_audio: invalid capacity, timing or bitrate")
}
return nil
}
func (c Config) PoseTimeout() time.Duration { return time.Duration(c.PoseTimeoutMs) * time.Millisecond }
type Gain struct{ Left, Right float64 }
func Gains(listener, source Pose, c Config) Gain {
d := Vec3{source.Position.X - listener.Position.X, source.Position.Y - listener.Position.Y, source.Position.Z - listener.Position.Z}
distance := math.Sqrt(d.X*d.X + d.Y*d.Y + d.Z*d.Z)
if distance >= c.MaxDistance {
return Gain{}
}
t := math.Max(0, (distance-c.NearDistance)/(c.MaxDistance-c.NearDistance))
a := 1 - t*t*(3-2*t)
pan := 0.0
if distance > 1e-6 {
r := listener.Rotation.Right()
pan = math.Max(-1, math.Min(1, (d.X*r.X+d.Y*r.Y+d.Z*r.Z)/distance))
}
return Gain{a * math.Sqrt((1-pan)/2), a * math.Sqrt((1+pan)/2)}
}
type Mixer struct {
config Config
current map[string]Gain
alpha float64
limiter float64
release float64
hrtf *HRTFRenderer
pairs map[string]*binauralPair
hrtfBlend float64
hrtfNearest bool
}
func NewMixer(c Config) *Mixer {
return &Mixer{config: c, current: make(map[string]Gain), alpha: 1 - math.Exp(-1/(SampleRate*float64(c.SmoothingMs)/1000)), limiter: 1, release: math.Exp(-1 / (SampleRate * 0.1)), pairs: make(map[string]*binauralPair)}
}
// Mix advances gains once per sample. Each mono source is shared by all listeners.
func (m *Mixer) Mix(listenerID string, poses map[string]Pose, sources map[string][]float32, out []float32) {
targets := make(map[string]Gain, len(sources))
lp, hasListener := poses[listenerID]
if hasListener {
for id := range sources {
if sp, ok := poses[id]; ok && id != listenerID {
targets[id] = Gains(lp, sp, m.config)
}
}
}
m.MixTargets(listenerID, targets, sources, out)
}
// MixTargets consumes a precomputed matrix row. A disappearing target fades
// toward zero before it is excluded from sample multiplication.
func (m *Mixer) MixTargets(listenerID string, targets map[string]Gain, sources map[string][]float32, out []float32) {
m.MixSpatial(listenerID, nil, targets, sources, out, false)
}
func (m *Mixer) Close() {
for id, pair := range m.pairs {
pair.Close()
delete(m.pairs, id)
}
}
// HRTF supplies directional filtering; distance/wall attenuation is applied
// as one scalar afterward, avoiding a second left/right panning operation.
// Crossfade between panning and HRTF keeps the publication/encoder unchanged.
func (m *Mixer) MixSpatial(listenerID string, poses map[string]Pose, targets map[string]Gain, sources map[string][]float32, out []float32, enabled bool) uint64 {
var failures uint64
clear(out)
var blend [BlockSamples]float64
wanted := 0.0
if enabled && m.hrtf != nil {
wanted = 1
}
for n := range blend {
m.hrtfBlend += (wanted - m.hrtfBlend) * m.alpha
blend[n] = m.hrtfBlend
}
useHRTF := m.hrtf != nil && (wanted > 0 || m.hrtfBlend > 1e-5)
for id, pcm := range sources {
if id == listenerID {
continue
}
target := targets[id]
g := m.current[id]
if target == (Gain{}) && math.Abs(g.Left) < 1e-5 && math.Abs(g.Right) < 1e-5 {
delete(m.current, id)
if pair := m.pairs[id]; pair != nil {
pair.Close()
delete(m.pairs, id)
}
continue
}
var pair *binauralPair
if useHRTF {
pair = m.pairs[id]
if pair == nil {
var err error
pair, err = m.hrtf.newPair()
if err != nil {
failures++
} else {
pair.amplitude = math.Hypot(g.Left, g.Right)
m.pairs[id] = pair
}
}
if pair != nil {
pair.interpolation = m.hrtf.interpolation
if m.hrtfNearest {
pair.interpolation = 0
}
direction := pair.direction
if lp, ok := poses[listenerID]; ok {
if sp, ok := poses[id]; ok {
direction = headDirection(lp, sp)
}
}
if !pair.process(pcm, direction, 1-math.Exp(-float64(BlockSamples)/(SampleRate*float64(m.config.SmoothingMs)/1000))) {
failures++
pair = nil
}
}
}
targetAmplitude := math.Hypot(target.Left, target.Right)
for n, sample := range pcm {
if 2*n+1 >= len(out) || n >= BlockSamples {
break
}
g.Left += (target.Left - g.Left) * m.alpha
g.Right += (target.Right - g.Right) * m.alpha
left, right := sample*float32(g.Left), sample*float32(g.Right)
if pair != nil {
pair.amplitude += (targetAmplitude - pair.amplitude) * m.alpha
weight := float32(blend[n])
amplitude := float32(pair.amplitude)
left = left*(1-weight) + pair.output[2*n]*amplitude*weight
right = right*(1-weight) + pair.output[2*n+1]*amplitude*weight
}
out[2*n] += left
out[2*n+1] += right
}
m.current[id] = g
}
for id := range m.current {
if _, ok := sources[id]; !ok {
delete(m.current, id)
if pair := m.pairs[id]; pair != nil {
pair.Close()
delete(m.pairs, id)
}
}
}
if !useHRTF {
m.Close()
m.hrtfBlend = 0
}
// Stereo linked limiter: immediate attack, gradual release, bounded peaks.
for n := 0; n+1 < len(out); n += 2 {
peak := math.Max(math.Abs(float64(out[n])), math.Abs(float64(out[n+1])))
wanted := 1.0
if peak > 0.95 {
wanted = 0.95 / peak
}
if wanted < m.limiter {
m.limiter = wanted
} else {
m.limiter = m.release*m.limiter + (1-m.release)*wanted
}
out[n] *= float32(m.limiter)
out[n+1] *= float32(m.limiter)
}
return failures
}