Author SHA1 Message Date
arimius bd68856189 Document Linux container HRTF deployment as the primary setup 2026-10-06 14:44:08 +03:00
arimius cfae0d2131 Define flat walls in local XY with positive Z normal 2026-10-05 20:11:45 +03:00
arimius fa8be77559 Replace volumetric audio obstacles with flat rectangular walls 2026-10-05 20:09:43 +03:00
arimius d88a4b11fd Add Docker deployment package for spatial LiveKit location rooms 2026-10-05 17:55:27 +03:00
artorius_great 2051cf5122 Merge pull request 'Server-side spatial audio: HRTF, occlusion and adaptive quality' (#1) from artorius_great/codex/spatial-audio into master
Test / test (push) Canceled after 0s
Release to Docker / docker (push) Canceled after 0s
Release Test Server to Docker / docker (push) Canceled after 0s
Reviewed-on: #1
2026-10-05 17:34:18 +03:00
arimius 909e51bc0a Add server-side spatial audio with HRTF, occlusion and adaptive quality
Test / test (pull_request) Canceled after 0s
PR Slack Notifier / notify-devs (pull_request) Canceled after 0s
2026-10-05 17:29:30 +03:00
Raja SubramanianandClaude Opus 5.5 44b791ad50 test: give mock participants a connection quality, close test rooms (#4933)
Test / test (push) Canceled after 0s
Release to Docker / docker (push) Canceled after 0s
Release Test Server to Docker / docker (push) Canceled after 0s
* test: give mock participants a connection quality

A real participant never returns a nil connection quality. The mock
did, which can crash code that does not expect nil.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test: close test rooms when each test ends

Most room tests left their rooms open, so each room's workers kept
running for the rest of the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:54:14 +05:30
Raja SubramanianandClaude Opus 4.8 c2339b2b85 fix: skip RTX/FEC when picking a fallback video codec (#4930)
selectAlternativeVideoCodec walked the enabled codecs and returned the
first one with a video/ prefix. video/rtx and video/flexfec-03 both have
that prefix, so when the requested codec was not enabled the track could
fall back to RTX. RTX is a retransmission stream, not a real codec, so
the track got registered as video/rtx and subscribers saw a blank tile.

Skip RTX and FEC entries so the fallback is always a valid video codec.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-10-04 21:20:28 +05:30
He Chen edb19c9e8f fix: reject instead of drop for no dispatch rule (#4927) 2026-10-01 11:06:35 -07:00
Perfloop Agent 7ef0cd014e Reduce descriptor marshal allocations on Go 1.26.4/linux-amd64 (#4681)
* Reduce descriptor marshal allocations on Go 1.26.4/linux-amd64

Signed-off-by: Perfloop Agent <agent@perfloop.ai>

* Use require in the descriptor marshal benchmark test

Signed-off-by: Perfloop Agent <agent@perfloop.ai>

* sfu: marshal dependency descriptors into caller-owned scratch

* sfu: reuse the selector's descriptor clone

* sfu: share one inline header-extension size constant

---------

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
2026-09-30 23:11:49 +08:00
Martin Njalale 2fab31691b service: start room composite egress configured in a room preset (#4926)
* service: start room composite egress configured in a room preset

StandardRoomAllocator.CreateRoom merged a room preset into a copy of the
request and discarded it. RoomInternal has no field for room composite
egress, and getOrCreateRoom started it from the caller's original request,
so a room composite egress from a preset was never started.

RoomAllocator.CreateRoom now also returns the request with the preset
applied, and getOrCreateRoom starts the egress from it.

* service: return ErrEgressNotConnected instead of calling a nil egress launcher

getOrCreateRoom started a room composite egress without checking that an
egress launcher exists. RoomService.CreateRoom rejects egress on the request
when there is none, but not egress from a room preset or a token's roomConfig.
2026-09-30 13:25:24 +02:00
Nikolay IvankoandClaude Opus 5 aa08becc6a config: reject unknown send_side_bwe_pacer, warn on unwired fallback (#4804)
send_side_bwe_pacer accepted any string and silently ran no-queue. leaky-bucket
is a defined PacerBehavior with a full LeakyBucket implementation, but the
selection switch in NewPCTransport only handled pass-through and no-queue, so
both leaky-bucket and outright typos fell through to the default with no
diagnostic.

leaky-bucket is deliberately left unwired here. LeakyBucket paces to a bitrate
supplied via Pacer.SetBitrate, and no production code calls SetBitrate or
SetInterval -- Base no-ops both and the only caller in the tree is the
test-only capturingPacer. Wiring it as-is would pace at a static bitrate and
ignore the bandwidth estimate, which is worse than the fallback.

Instead, make the existing behaviour visible: CongestionControlConfig.Validate
rejects unrecognised values at startup, the fallback logs a warning naming the
requested pacer, and config-sample.yaml documents send_side_bwe_pacer and
use_send_side_bwe for the first time.

Refs #4724

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-30 16:07:19 +05:30
RaphaelFakhri ad54223d1b sfu: fix data stats active window bitrate and duration units (#4922) 2026-09-29 23:18:25 +05:30
RaphaelFakhri 2d9bf12581 rtc: measure data blob keys by their content, not their text form (#4923) 2026-09-29 23:17:42 +05:30
Raja Subramanian d91b16238a rtc: accept ICE Completed in ICE-restart connect assertions (#4921) 2026-09-29 08:02:36 +05:30
Raja SubramanianandClaude Opus 4.8 6ed445bad1 sfu: report forwarding latency as p90 instead of the mean (#4920)
* sfu: report forwarding latency as p90 instead of the mean

The forwarding-latency metric was the mean transit over all forwarded
packets. A mean is dominated by a few slow outliers, so a handful of
packets stalled on the forward path (e.g. goroutine scheduling latency)
inflated the whole node's reported latency even when nearly every packet
was forwarded promptly.

Report p90 instead: p90 rising means roughly a tenth of forwarded packets
are slow, a broad signal of systemic forwarding load rather than a sparse
tail. To read a percentile over the report window, the mergeable
per-interval summary now keeps a small power-of-two-bucket histogram of
transit instead of running moments (sum, sum-of-squares).

Drop the jitter (transit std dev) gauge: nothing consumed it, and any
spread is derivable from the forward-latency histogram. The protobuf
ForwardJitter field is left in place, now unset, to deprecate separately.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: clamp forwarding percentile to the observed [min, max]

Bucket interpolation assumes a uniform fill, so a single 20ms packet (or
uniform traffic) could report a p90 above every observed sample. Clamp the
interpolated value to the summary's already-tracked min/max, so a quantile
never falls outside the data. Exact for single samples and repeated
identical latencies.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: fix stale p50 comment in the percentile test

The reported metric is p90; the test comment still said p50 replaced the
mean. Reword it to reflect that a percentile, not the mean, is reported.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: quarter-octave forwarding-latency buckets for threshold resolution

Octave buckets are too coarse near the overload thresholds: 300us falls in
[256,512), so a p90 clustered at ~265us and one at ~500us interpolate to the
same value and would trip (or not) identically. Split each octave into four
linear sub-buckets so the two land in different buckets, on the correct side
of the threshold. Min/max clamping alone does not fix this once a node has a
high tail, since its max no longer bounds the interpolation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: interpolate percentiles within each bucket's observed range

Replace the quarter-octave split with plain octave buckets that also carry
the observed [min, max] of their samples, and interpolate a percentile
within that range instead of the bucket's nominal edges. This is exact when
a bucket's samples cluster, so a p90 near an overload threshold that falls
mid-bucket lands on the correct side of it regardless of bucket width -- no
threshold-aware boundaries needed. It subsumes the min/max clamp, since an
estimate can no longer leave the observed samples.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: cover the 500us cluster in the threshold test

Assert milos's full review example exactly: 265us and 500us clusters that
octave-nominal interpolation both read as ~341us now read 265us and 500us.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: make forwardSummary.addSample a pointer receiver

The summary grew from a small moments struct into a per-bucket histogram
(~700 bytes), so the value-receiver addSample copied the whole summary on
every drained sample in the flush loop. Mutate in place instead: ~28ns ->
~2ns per sample in the background fold, no behavior change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* sfu: eighth-octave buckets for accuracy near thresholds

Split each octave into 8 linear sub-buckets (was plain octaves). With the
per-bucket min/max interpolation this reports a tight p90 cluster exactly
even when it sits mid-octave: 850x265us + 150x410us now reads 410us (above a
400us threshold) instead of 395.5us, and a lognormal p90 lands within ~0.2us
of exact. Per-sample add cost is unchanged (~2ns); cost is ~5KB per summary
and a larger but per-report merge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-29 01:39:05 +05:30
88 changed files with 7174 additions and 214 deletions
+10
View File
@@ -0,0 +1,10 @@
.git
.spatial-runtime
bin
dist
**/*.exe
**/*.dll
**/.env
**/.env.*
**/instances
!deploy/spatial/.env.example
+5
View File
@@ -27,3 +27,8 @@ proto/
.idea/
dist/
# Local native dependencies and spatial audio development logs
.spatial-runtime/
deploy/spatial/.env
deploy/spatial/instances/
+3
View File
@@ -55,6 +55,9 @@ FROM alpine:3.24.1@sha256:28bd5fe8b56d1bd048e5babf5b10710ebe0bae67db86916198a6ee
# with SECURITY_REFRESH) or it will be served stale.
RUN apk upgrade --no-cache
# Sverse spatial audio loads libopus at runtime (Go remains CGO_ENABLED=0).
RUN apk add --no-cache opus
COPY --from=builder /workspace/livekit-server /livekit-server
# Run the binary.
+338
View File
@@ -0,0 +1,338 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
// Container launcher: render configuration, initialize native audio, bootstrap
// rooms and forward termination signals. Never log configuration or credentials.
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/livekit/livekit-server/pkg/spatialaudio"
"github.com/livekit/protocol/auth"
"gopkg.in/yaml.v3"
)
func env(name, fallback string) string {
if v, ok := os.LookupEnv(name); ok {
return v
}
return fallback
}
func integer(name string, fallback int) (int, error) {
v, err := strconv.Atoi(env(name, strconv.Itoa(fallback)))
if err != nil {
return 0, fmt.Errorf("%s must be an integer", name)
}
return v, nil
}
func boolean(name string, fallback bool) (bool, error) {
v, err := strconv.ParseBool(env(name, strconv.FormatBool(fallback)))
if err != nil {
return false, fmt.Errorf("%s must be true or false", name)
}
return v, nil
}
func decimal(name string, fallback float64) (float64, error) {
v, err := strconv.ParseFloat(env(name, strconv.FormatFloat(fallback, 'g', -1, 64)), 64)
if err != nil {
return 0, fmt.Errorf("%s must be a number", name)
}
return v, nil
}
func credentials() (string, string, error) {
key, secret := os.Getenv("LIVEKIT_API_KEY"), os.Getenv("LIVEKIT_API_SECRET")
if strings.TrimSpace(key) == "" || len(secret) < 32 {
return "", "", errors.New("set LIVEKIT_API_KEY and LIVEKIT_API_SECRET (at least 32 bytes)")
}
return key, secret, nil
}
func portBase() (int, error) {
p, err := integer("SPATIAL_PORT_BASE", 7880)
if err != nil {
return 0, err
}
if p < 1024 || p > 65533 {
return 0, errors.New("SPATIAL_PORT_BASE must be 1024..65533")
}
return p, nil
}
func audioConfig() (spatialaudio.Config, error) {
c := spatialaudio.Config{Enabled: true, RoomPrefix: env("SPATIAL_ROOM_PREFIX", "spatial-"), Library: "libopus.so.0"}.Defaults()
if c.RoomPrefix == "" {
return c, errors.New("SPATIAL_ROOM_PREFIX cannot be empty")
}
var err error
for _, setting := range []struct {
name string
dest *int
}{
{"SPATIAL_MAX_PARTICIPANTS", &c.MaxParticipants}, {"SPATIAL_BITRATE", &c.Bitrate},
{"SPATIAL_MAX_OBSTACLES", &c.Occlusion.MaxObjects}, {"SPATIAL_POSE_INTERVAL_MS", &c.Adaptive.PoseIntervalMs},
} {
*setting.dest, err = integer(setting.name, *setting.dest)
if err != nil {
return c, err
}
}
c.NearDistance, err = decimal("SPATIAL_NEAR_DISTANCE", 1)
if err != nil {
return c, err
}
c.MaxDistance, err = decimal("SPATIAL_MAX_DISTANCE", 20)
if err != nil {
return c, err
}
for _, setting := range []struct {
name string
dest *bool
}{
{"SPATIAL_HRTF", &c.HRTF.Enabled}, {"SPATIAL_OCCLUSION", &c.Occlusion.Enabled},
{"SPATIAL_ADAPTIVE", &c.Adaptive.Enabled}, {"SPATIAL_DEBUG_STATS", &c.DebugStats},
} {
*setting.dest, err = boolean(setting.name, true)
if err != nil {
return c, err
}
}
c.HRTF.Library = "/opt/sverse/hrtf/libsverse_hrtf.so"
c.HRTF.Interpolation = env("SPATIAL_HRTF_INTERPOLATION", "bilinear")
return c, c.Validate()
}
func rooms(prefix string) ([]string, error) {
var result []string
seen := map[string]bool{}
for _, name := range strings.Split(env("SPATIAL_ROOMS", "spatial-main"), ",") {
name = strings.TrimSpace(name)
if name == "" {
continue
}
if len(name) > 100 || !strings.HasPrefix(name, prefix) || seen[name] {
return nil, errors.New("SPATIAL_ROOMS must contain unique names with the configured spatial prefix, at most 100 bytes each")
}
seen[name] = true
result = append(result, name)
}
return result, nil
}
func render() (int, []string, int, spatialaudio.Config, error) {
var zero spatialaudio.Config
key, secret, err := credentials()
if err != nil {
return 0, nil, 0, zero, err
}
port, err := portBase()
if err != nil {
return 0, nil, 0, zero, err
}
ip := net.ParseIP(os.Getenv("SPATIAL_NODE_IP"))
if ip == nil || ip.IsUnspecified() || ip.IsMulticast() {
return 0, nil, 0, zero, errors.New("SPATIAL_NODE_IP must be an address reachable by players")
}
bind := env("SPATIAL_BIND_IP", "127.0.0.1")
if bind != "127.0.0.1" && bind != "0.0.0.0" {
return 0, nil, 0, zero, errors.New("SPATIAL_BIND_IP must be 127.0.0.1 or 0.0.0.0")
}
c, err := audioConfig()
if err != nil {
return 0, nil, 0, zero, err
}
names, err := rooms(c.RoomPrefix)
if err != nil {
return 0, nil, 0, zero, err
}
timeout, err := integer("SPATIAL_EMPTY_TIMEOUT", 300)
if err != nil || timeout < 1 || timeout > 86400 {
return 0, nil, 0, zero, errors.New("SPATIAL_EMPTY_TIMEOUT must be 1..86400 seconds")
}
data, err := yaml.Marshal(map[string]any{
"port": port, "bind_addresses": []string{bind}, "keys": map[string]string{key: secret},
"rtc": map[string]any{"tcp_port": port + 1, "udp_port": port + 2, "node_ip": ip.String(), "use_external_ip": false},
"room": map[string]any{"spatial_audio": c}, "logging": map[string]string{"level": "info"},
})
if err != nil {
return 0, nil, 0, zero, err
}
if err = os.MkdirAll("/run/spatial", 0700); err != nil {
return 0, nil, 0, zero, err
}
if err = os.WriteFile("/run/spatial/livekit.yaml", data, 0600); err != nil {
return 0, nil, 0, zero, err
}
return port, names, timeout, c, nil
}
func serviceCall(ctx context.Context, port int, method string, grant *auth.VideoGrant, body any) error {
key, secret, err := credentials()
if err != nil {
return err
}
jwt, err := auth.NewAccessToken(key, secret).SetValidFor(time.Minute).SetVideoGrant(grant).ToJWT()
if err != nil {
return err
}
data, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/twirp/livekit.RoomService/%s", port, method), bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+jwt)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 3 * time.Second}
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return fmt.Errorf("RoomService.%s returned HTTP %d", method, res.StatusCode)
}
_, err = io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
return err
}
func bootstrap(ctx context.Context, port int, names []string, timeout int) error {
deadline, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
for {
if serviceCall(deadline, port, "ListRooms", &auth.VideoGrant{RoomList: true}, map[string]any{}) == nil {
break
}
select {
case <-deadline.Done():
return errors.New("LiveKit API did not become ready within 45 seconds")
case <-time.After(500 * time.Millisecond):
}
}
metadata, _ := json.Marshal(map[string]string{"location_id": env("SPATIAL_LOCATION_ID", "local-location")})
for _, name := range names {
if err := serviceCall(deadline, port, "CreateRoom", &auth.VideoGrant{RoomCreate: true}, map[string]any{"name": name, "empty_timeout": timeout, "metadata": string(metadata)}); err != nil {
return err
}
}
return os.WriteFile("/run/spatial/bootstrap.ready", []byte("ready\n"), 0600)
}
func run() error {
port, names, timeout, c, err := render()
if err != nil {
return err
}
// Fail startup if native libraries cannot initialize, even before any player joins.
engine, err := spatialaudio.NewEngine(c)
if err != nil {
return fmt.Errorf("native audio initialization: %w", err)
}
engine.Close()
_ = os.Remove("/run/spatial/bootstrap.ready")
cmd := exec.Command("/usr/local/bin/livekit-server", "--config", "/run/spatial/livekit.yaml")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Start(); err != nil {
return err
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() { done <- cmd.Wait(); cancel() }()
signals := make(chan os.Signal, 2)
signal.Notify(signals, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(signals)
go func() {
for {
select {
case sig := <-signals:
_ = cmd.Process.Signal(sig)
case <-ctx.Done():
return
}
}
}()
if err = bootstrap(ctx, port, names, timeout); err != nil {
_ = cmd.Process.Signal(syscall.SIGTERM)
select {
case <-done:
case <-time.After(10 * time.Second):
_ = cmd.Process.Kill()
<-done
}
return err
}
fmt.Fprintf(os.Stderr, "Spatial node ready: %d room(s), API %d, ICE TCP %d, ICE UDP %d\n", len(names), port, port+1, port+2)
return <-done
}
func health() error {
if _, err := os.Stat("/run/spatial/bootstrap.ready"); err != nil {
return errors.New("room bootstrap not ready")
}
port, err := portBase()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return serviceCall(ctx, port, "ListRooms", &auth.VideoGrant{RoomList: true}, map[string]any{})
}
func token(args []string) error {
flags := flag.NewFlagSet("token", flag.ContinueOnError)
room := flags.String("room", "", "target room")
identity := flags.String("identity", "", "participant identity")
publicURL := flags.String("url", "", "public ws/wss signaling URL")
controller := flags.Bool("controller", false, "trusted scene controller")
if err := flags.Parse(args); err != nil {
return err
}
u, err := url.Parse(*publicURL)
if err != nil || u.Host == "" || (u.Scheme != "ws" && u.Scheme != "wss") || u.User != nil {
return errors.New("--url must be a ws/wss URL without credentials")
}
if *room == "" || len(*room) > 100 || !strings.HasPrefix(*room, env("SPATIAL_ROOM_PREFIX", "spatial-")) || *identity == "" || len(*identity) > 100 || strings.HasPrefix(*identity, "__spatial_") {
return errors.New("set valid --room and --identity")
}
key, secret, err := credentials()
if err != nil {
return err
}
allow, media := true, !*controller
grant := &auth.VideoGrant{RoomJoin: true, Room: *room, CanPublish: &media, CanSubscribe: &media, CanPublishData: &allow, RoomAdmin: *controller, Hidden: *controller}
jwt, err := auth.NewAccessToken(key, secret).SetIdentity(*identity).SetValidFor(15 * time.Minute).SetVideoGrant(grant).ToJWT()
if err != nil {
return err
}
return json.NewEncoder(os.Stdout).Encode(map[string]string{"url": *publicURL, "room": *room, "token": jwt})
}
func main() {
var err error
if len(os.Args) < 2 {
err = errors.New("usage: spatial-node run | health | token --room NAME --identity NAME --url URL [--controller]")
} else {
switch os.Args[1] {
case "run":
err = run()
case "health":
err = health()
case "token":
err = token(os.Args[2:])
default:
err = errors.New("unknown command")
}
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
+81
View File
@@ -0,0 +1,81 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
// spatial-test serves a loopback-only browser laboratory and issues short-lived
// tokens with server-side credentials. It is not a production token service.
package main
import (
"embed"
"encoding/json"
"flag"
"fmt"
"io/fs"
"log"
"net"
"net/http"
"os"
"strings"
"time"
"github.com/livekit/protocol/auth"
)
//go:embed web/*
var web embed.FS
func main() {
listen := flag.String("listen", "127.0.0.1:8899", "loopback HTTP address")
url := flag.String("livekit-url", "ws://127.0.0.1:7880", "LiveKit websocket URL")
prefix := flag.String("room-prefix", "spatial-", "allowed laboratory room prefix")
flag.Parse()
host, _, err := net.SplitHostPort(*listen)
if err != nil || net.ParseIP(host) == nil || !net.ParseIP(host).IsLoopback() {
log.Fatal("spatial-test must bind to a loopback IP")
}
key, secret := os.Getenv("LIVEKIT_API_KEY"), os.Getenv("LIVEKIT_API_SECRET")
if key == "" || secret == "" {
log.Fatal("set LIVEKIT_API_KEY and LIVEKIT_API_SECRET")
}
files, _ := fs.Sub(web, "web")
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(files)))
mux.HandleFunc("POST /token", func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" && origin != "http://"+r.Host {
http.Error(w, "origin not allowed", http.StatusForbidden)
return
}
var request struct {
Room string `json:"room"`
Identity string `json:"identity"`
SceneController bool `json:"scene_controller"`
}
r.Body = http.MaxBytesReader(w, r.Body, 1024)
if json.NewDecoder(r.Body).Decode(&request) != nil || !strings.HasPrefix(request.Room, *prefix) || len(request.Room) > 100 || len(request.Identity) < 1 || len(request.Identity) > 100 || strings.HasPrefix(request.Identity, "__spatial_") {
http.Error(w, "invalid room or identity", http.StatusBadRequest)
return
}
allow := true
grant := &auth.VideoGrant{RoomJoin: true, Room: request.Room, CanPublish: &allow, CanSubscribe: &allow, CanPublishData: &allow}
if request.SceneController {
if !strings.HasPrefix(request.Identity, "scene-controller-") {
http.Error(w, "invalid scene controller identity", http.StatusBadRequest)
return
}
deny := false
grant.RoomAdmin = true
grant.Hidden = true
grant.CanPublish = &deny
grant.CanSubscribe = &deny
}
token, err := auth.NewAccessToken(key, secret).SetIdentity(request.Identity).SetValidFor(15 * time.Minute).SetVideoGrant(grant).ToJWT()
if err != nil {
http.Error(w, "token generation failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
_ = json.NewEncoder(w).Encode(map[string]string{"url": *url, "token": token})
})
server := &http.Server{Addr: *listen, Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second}
fmt.Printf("Spatial audio laboratory: http://%s\n", *listen)
log.Fatal(server.ListenAndServe())
}
+319
View File
@@ -0,0 +1,319 @@
/* Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0. */
"use strict";
const actors = new Map(), colors = ["#79d5be", "#f5bc73", "#8eb5fc", "#dc99d6", "#becc72"];
const session = crypto.randomUUID().slice(0,8), canvas = document.querySelector("#map"), ctx = canvas.getContext("2d");
let audioContext, nextActor = 1, poseTimer, previousTime = performance.now();
let wallController,wallConnectPromise,wallPending,appliedScene,wallRetryTimer,wallRetryAttempt=0,wallRevision=0;
const log = (text) => { const el=document.querySelector("#log"); el.textContent=(new Date().toLocaleTimeString()+" "+text+"\n"+el.textContent).slice(0,4000); };
async function audio() { audioContext ??= new AudioContext({sampleRate:48000}); await audioContext.resume(); return audioContext; }
function setPosition(actor, key, value) { actor[key]=value; const input=actor.el.querySelector(`[data-axis="${key}"]`); input.value=value; input.closest(".axis").querySelector("output").value=Number(value).toFixed(key==="yaw"?0:1); }
function addActor(initial={}) {
const number=nextActor++, id=`actor-${number}-${session}`, el=document.querySelector("#actor-template").content.firstElementChild.cloneNode(true);
const actor={id,number,el,x:0,y:0,z:0,yaw:0,seq:0,color:colors[(number-1)%colors.length],room:null,connected:false,connecting:false,generation:0,desiredConnected:false,retryAttempt:0};
actors.set(id,actor); el.style.setProperty("--actor-color",actor.color); el.querySelector("strong").textContent=`Актор ${number}`;
for (const key of ["x","y","z","yaw"]) { setPosition(actor,key,initial[key]??0); el.querySelector(`[data-axis="${key}"]`).addEventListener("input",event=>{setPosition(actor,key,Number(event.target.value));}); }
el.querySelector(".frequency").value=initial.frequency??440+number*110;
el.querySelector(".frequency").addEventListener("input",()=>{if(actor.oscillator)actor.oscillator.frequency.setTargetAtTime(Number(el.querySelector(".frequency").value),audioContext.currentTime,.02);});
el.querySelector(".source").addEventListener("change",()=>{if(actor.connected)changeInput(actor);});
el.querySelector(".connect").addEventListener("click",()=>actor.desiredConnected?disconnect(actor):connect(actor));
el.querySelector(".remove").addEventListener("click",async()=>{await disconnect(actor); actors.delete(id); el.remove(); updateAudition();});
document.querySelector("#actors").append(el); updateAudition(); return actor;
}
function updateAudition() {
const select=document.querySelector("#audition"), selected=select.value; select.replaceChildren(new Option("Тишина",""));
for(const actor of actors.values())select.add(new Option(`Актор ${actor.number}`,actor.id));
select.value=actors.has(selected)?selected:""; applyAudition();
}
function applyAudition() {
const selected=document.querySelector("#audition").value;
for(const actor of actors.values())if(actor.outputElement)actor.outputElement.volume=actor.id===selected?1:0;
}
function pose(actor) {
const buffer=new ArrayBuffer(44), v=new DataView(buffer), yaw=actor.yaw*Math.PI/180;
v.setUint8(0,1);v.setUint32(4,++actor.seq,true);v.setFloat64(8,performance.now(),true);
[actor.x,actor.y,actor.z,0,0,Math.sin(yaw/2),Math.cos(yaw/2)].forEach((n,i)=>v.setFloat32(16+i*4,n,true));
return new Uint8Array(buffer);
}
function sendPose(actor) {
if(!actor.connected||!actor.room||actor.posePending)return;
actor.posePending=true;
actor.room.localParticipant.publishData(pose(actor),{reliable:false,topic:"sverse.spatial.pose.v1"})
.catch(error=>{if(performance.now()-(actor.lastPoseError??-Infinity)>5000){actor.lastPoseError=performance.now();log(`${actor.id}: ${error.message}`);}})
.finally(()=>actor.posePending=false);
}
function startPoseTimer() { clearInterval(poseTimer); poseTimer=setInterval(()=>{for(const actor of actors.values())sendPose(actor);},Number(document.querySelector("#interval").value)); }
function attachOutput(actor, track, publication) {
if(publication.trackName!=="spatial_mix" || track.kind!==LivekitClient.Track.Kind.Audio)return;
clearOutput(actor);
// Keep a playing media element attached to the remote WebRTC track. Chrome
// can leave remote audio silent when it is consumed only through Web Audio.
const element=track.attach();element.autoplay=true;element.volume=0;element.hidden=true;
document.body.append(element);actor.outputElement=element;actor.outputTrack=track;
element.play().catch(error=>log(`Актор ${actor.number}: нажмите «Включить звук» (${error.message})`));
for(const node of actor.outputNodes??[])node.disconnect();
const source=audioContext.createMediaStreamSource(new MediaStream([track.mediaStreamTrack])), gain=audioContext.createGain(), splitter=audioContext.createChannelSplitter(2), left=audioContext.createAnalyser(), right=audioContext.createAnalyser();
left.fftSize=right.fftSize=8192;left.smoothingTimeConstant=right.smoothingTimeConstant=.1; source.connect(splitter); splitter.connect(left,0); splitter.connect(right,1); source.connect(gain);gain.gain.value=0; gain.connect(audioContext.destination);
actor.outputGain=gain;actor.outputNodes=[source,gain,splitter,left,right]; actor.analyzers=[left,right];actor.meterSamples=new Float32Array(1024);actor.hasMix=true;
actor.spectrum=new Float32Array(left.frequencyBinCount);actor.lastSpectrumTime=0;
actor.el.querySelector(".state").textContent="Персональный стереомикс";applyAudition();log(`Актор ${actor.number}: получен spatial_mix (${track.mediaStreamTrack.getSettings().channelCount??"Opus"} канала)`);
}
function clearOutput(actor) {
for(const node of actor.outputNodes??[])node.disconnect();
if(actor.outputElement){actor.outputTrack?.detach(actor.outputElement);actor.outputElement.pause();actor.outputElement.srcObject=null;actor.outputElement.remove();}
actor.outputNodes=[];actor.outputElement=null;actor.outputTrack=null;actor.outputGain=null;actor.analyzers=null;actor.hasMix=false;
for(const meter of actor.el.querySelectorAll("meter"))meter.value=0;
for(const value of actor.el.querySelectorAll(".left-value,.right-value"))value.textContent="0.000";
actor.el.querySelector(".spectrum-value").textContent="—";
}
function stopInput(input) {
if(!input)return;
if(input.oscillator){try{input.oscillator.stop();}catch{}}
if(input.generator){try{input.generator.stop();}catch{}}
input.track.stop();for(const node of input.nodes)node.disconnect();
}
function clearMedia(actor) { stopInput(actor.input);actor.input=null;actor.inputTrack=null;actor.oscillator=null;clearOutput(actor); }
async function createInput(actor, mode) {
if(mode==="silent")return null;
if(mode==="microphone")return {track:await LivekitClient.createLocalAudioTrack({channelCount:1,echoCancellation:true,noiseSuppression:true}),nodes:[],mode};
if(mode==="noise") {
const destination=audioContext.createMediaStreamDestination(),generator=audioContext.createBufferSource(),level=audioContext.createGain();
destination.channelCount=1;level.gain.value=.12;
const buffer=audioContext.createBuffer(1,audioContext.sampleRate*2,audioContext.sampleRate),samples=buffer.getChannelData(0);
let seed=12345+actor.number;
for(let i=0;i<samples.length;i++){seed=(Math.imul(seed,1664525)+1013904223)>>>0;samples[i]=seed/2147483648-1;}
generator.buffer=buffer;generator.loop=true;generator.connect(level);level.connect(destination);generator.start();
return {track:new LivekitClient.LocalAudioTrack(destination.stream.getAudioTracks()[0],undefined,true,audioContext),nodes:[generator,level,destination],generator,mode};
}
const destination=audioContext.createMediaStreamDestination(),oscillator=audioContext.createOscillator(),level=audioContext.createGain();
destination.channelCount=1;level.gain.value=.16;oscillator.frequency.value=Number(actor.el.querySelector(".frequency").value);
oscillator.connect(level);level.connect(destination);oscillator.start();
// This stream is generated by our oscillator, not by getUserMedia. Mark it
// user-provided so SDK reconnect cannot reacquire a physical microphone.
return {track:new LivekitClient.LocalAudioTrack(destination.stream.getAudioTracks()[0],undefined,true,audioContext),nodes:[oscillator,level,destination],oscillator,mode};
}
const inputOptions={name:"microphone",forceStereo:false,red:false,dtx:false};
async function changeInput(actor) {
actor.inputRequested=true;if(actor.inputBusy)return;
actor.inputBusy=true;
try {
while(actor.inputRequested&&actor.connected&&actor.room) {
actor.inputRequested=false;
const room=actor.room,generation=actor.generation,mode=actor.el.querySelector(".source").value;
let next;
try {
next=await createInput(actor,mode);
if(actor.room!==room||generation!==actor.generation||!actor.desiredConnected){stopInput(next);continue;}
const old=actor.input;
if(old)await room.localParticipant.unpublishTrack(old.track,false);
if(actor.room!==room||generation!==actor.generation){stopInput(next);continue;}
stopInput(old);actor.input=null;actor.inputTrack=null;actor.oscillator=null;
if(next) {
await room.localParticipant.publishTrack(next.track,{...inputOptions,source:LivekitClient.Track.Source.Microphone});
if(actor.room!==room||generation!==actor.generation||!actor.desiredConnected){stopInput(next);continue;}
actor.input=next;actor.inputTrack=next.track;actor.oscillator=next.oscillator;
}
log(`Актор ${actor.number}: источник ${mode==="tone"?"тестовый тон":mode==="noise"?"шум":mode==="silent"?"тишина":"микрофон"}`);
}catch(error){stopInput(next);if(actor.room===room&&generation===actor.generation){log(`Источник актора ${actor.number}: ${error.message}`);actor.el.querySelector(".source").value=actor.input?.mode??"silent";}}
}
}finally{actor.inputBusy=false;}
}
function subscribeMix(room) {
for(const participant of room.remoteParticipants.values())for(const publication of participant.audioTrackPublications.values())if(publication.trackName==="spatial_mix")publication.setSubscribed(true);
}
function scheduleRetry(actor) {
if(!actor.desiredConnected||actor.retryTimer)return;
const delay=Math.min(1000*2**Math.min(actor.retryAttempt++,3),8000);
actor.el.querySelector(".state").textContent=`Восстановление через ${delay/1000} с`;
actor.el.querySelector(".connect").textContent="Отключить";
actor.retryTimer=setTimeout(()=>{actor.retryTimer=null;if(actor.desiredConnected)connect(actor);},delay);
}
async function connect(actor) {
if(actor.connecting||actor.room)return;actor.desiredConnected=true;actor.connecting=true;
clearTimeout(actor.retryTimer);actor.retryTimer=null;
const generation=++actor.generation,button=actor.el.querySelector(".connect");button.disabled=true;
try {
if(!window.LivekitClient)throw new Error("Не загрузился LiveKit SDK. Проверьте доступ к CDN.");
if(location.protocol==="file:")throw new Error("Откройте http://127.0.0.1:8899/ вместо HTML файла.");
await audio();actor.el.querySelector(".state").textContent="Подключение…";
actor.roomName??=document.querySelector("#room").value;
const response=await fetch("/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({room:actor.roomName,identity:actor.id}),signal:AbortSignal.timeout(10000)});
if(!response.ok)throw new Error(await response.text());const credentials=await response.json();
if(generation!==actor.generation||!actor.desiredConnected)return;
const room=new LivekitClient.Room({adaptiveStream:false,dynacast:false});actor.room=room;
const current=()=>actor.room===room&&actor.generation===generation;
room.on(LivekitClient.RoomEvent.TrackPublished,pub=>{if(current()&&pub.trackName==="spatial_mix")pub.setSubscribed(true);});
room.on(LivekitClient.RoomEvent.TrackSubscribed,(track,pub)=>{if(current())attachOutput(actor,track,pub);});
room.on(LivekitClient.RoomEvent.TrackUnsubscribed,track=>{if(current()&&actor.outputTrack===track){clearOutput(actor);actor.el.querySelector(".state").textContent="Подключён · ожидание микса";}});
room.on(LivekitClient.RoomEvent.Reconnecting,()=>{if(current()){actor.connected=false;actor.el.querySelector(".state").textContent="Восстановление соединения…";}});
room.on(LivekitClient.RoomEvent.Reconnected,async()=>{
if(!current())return;
actor.connected=true;actor.retryAttempt=0;sendPose(actor);subscribeMix(room);applyAudition();
actor.outputElement?.play().catch(()=>{});
actor.el.querySelector(".state").textContent=actor.hasMix?"Персональный стереомикс":"Подключён · ожидание микса";
try {
const input=actor.input;
if(input&&!actor.inputBusy&&![...room.localParticipant.audioTrackPublications.values()].some(pub=>pub.track?.mediaStreamTrack===input.track.mediaStreamTrack))await room.localParticipant.publishTrack(input.track,{...inputOptions,source:LivekitClient.Track.Source.Microphone});
if(current()&&actor.inputRequested)changeInput(actor);
}catch(error){if(current())log(`Восстановление источника актора ${actor.number}: ${error.message}`);}
log(`Актор ${actor.number}: восстановлено соединение`);
});
room.on(LivekitClient.RoomEvent.Disconnected,()=>{if(current()){actor.room=null;actor.connected=false;clearMedia(actor);scheduleRetry(actor);}});
await room.connect(credentials.url,credentials.token,{autoSubscribe:false});
if(!current()||!actor.desiredConnected){await room.disconnect();return;}
actor.connected=true;actor.retryAttempt=0;sendPose(actor);subscribeMix(room);
if(!document.querySelector("#audition").value && ![...actors.values()].some(other=>other!==actor&&other.connected))document.querySelector("#audition").value=actor.id;
applyAudition();
await changeInput(actor);
if(!current())return;
button.textContent="Отключить";if(!actor.hasMix)actor.el.querySelector(".state").textContent="Подключён · ожидание микса";
log(`Актор ${actor.number}: подключён к ${actor.roomName}`);
}catch(error){if(generation===actor.generation&&actor.desiredConnected){log(`Ошибка актора ${actor.number}: ${error.message}`);const room=actor.room;actor.room=null;actor.connected=false;clearMedia(actor);await room?.disconnect();scheduleRetry(actor);}}
finally{if(generation===actor.generation){actor.connecting=false;button.disabled=false;}}
}
async function disconnect(actor) {
actor.generation++;actor.desiredConnected=false;actor.connected=false;actor.connecting=false;actor.inputRequested=false;actor.roomName=null;
clearTimeout(actor.retryTimer);actor.retryTimer=null;
const room=actor.room;actor.room=null;clearMedia(actor);
await room?.disconnect();actor.el.querySelector(".state").textContent="Отключён";actor.el.querySelector(".connect").textContent="Подключить";actor.el.querySelector(".connect").disabled=false;
}
function frame(now) {
const dt=Math.min((now-previousTime)/1000,.1);previousTime=now;
ctx.clearRect(0,0,canvas.width,canvas.height);const scale=canvas.width/66,cx=canvas.width/2,cy=canvas.height/2;
ctx.strokeStyle="#263b4e";ctx.lineWidth=1;ctx.fillStyle="#71879d";ctx.font="12px system-ui";
for(let n=-30;n<=30;n+=5){const x=cx+n*scale,y=cy-n*scale;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,canvas.height);ctx.moveTo(0,y);ctx.lineTo(canvas.width,y);ctx.stroke();if(n)ctx.fillText(String(n),x+3,cy+15);}
ctx.fillText("+X",cx+8,16);ctx.fillText("+Y",canvas.width-26,cy-8);
drawWalls(scale,cx,cy);
const selected=document.querySelector("#audition").value;
for(const actor of actors.values()) {
if(actor.el.querySelector(".moving").checked){actor.phase=(actor.phase??0)+dt*.6;setPosition(actor,"x",8*Math.cos(actor.phase));setPosition(actor,"y",8*Math.sin(actor.phase));}
if(actor.el.querySelector(".turning").checked)setPosition(actor,"yaw",((actor.yaw+dt*60+180)%360)-180);
const x=cx+actor.y*scale,y=cy-actor.x*scale,a=actor.yaw*Math.PI/180;
if(actor.id===selected){ctx.strokeStyle=actor.color+"44";ctx.beginPath();ctx.arc(x,y,20*scale,0,2*Math.PI);ctx.stroke();}
ctx.fillStyle=actor.color;ctx.beginPath();ctx.arc(x,y,8,0,2*Math.PI);ctx.fill();ctx.strokeStyle=actor.color;ctx.lineWidth=3;ctx.beginPath();ctx.moveTo(x,y);ctx.lineTo(x+Math.sin(a)*24,y-Math.cos(a)*24);ctx.stroke();ctx.fillText(String(actor.number),x+12,y+18);
if(actor.analyzers) {
actor.analyzers.forEach((analyzer,i)=>{analyzer.getFloatTimeDomainData(actor.meterSamples);const rms=Math.sqrt(actor.meterSamples.reduce((sum,n)=>sum+n*n,0)/actor.meterSamples.length);actor.el.querySelector(i===0?".left":".right").value=rms;actor.el.querySelector(i===0?".left-value":".right-value").textContent=rms.toFixed(3);});
if(now-actor.lastSpectrumTime>250) {
const peaks=actor.analyzers.map(analyzer=>spectralPeak(analyzer,actor.spectrum));
actor.el.querySelector(".spectrum-value").textContent=`L: ${peaks[0]} · R: ${peaks[1]}`;actor.lastSpectrumTime=now;
}
}
}
requestAnimationFrame(frame);
}
let dragging;
canvas.addEventListener("pointerdown",event=>{const rect=canvas.getBoundingClientRect(),y=(event.clientX-rect.left)/rect.width*canvas.width,x=(event.clientY-rect.top)/rect.height*canvas.height,scale=canvas.width/66;dragging=[...actors.values()].find(actor=>Math.hypot(canvas.width/2+actor.y*scale-y,canvas.height/2-actor.x*scale-x)<18);if(dragging)canvas.setPointerCapture(event.pointerId);});
canvas.addEventListener("pointermove",event=>{if(!dragging)return;const rect=canvas.getBoundingClientRect(),scale=canvas.width/66;setPosition(dragging,"y",Math.max(-30,Math.min(30,((event.clientX-rect.left)/rect.width*canvas.width-canvas.width/2)/scale)));setPosition(dragging,"x",Math.max(-30,Math.min(30,(canvas.height/2-(event.clientY-rect.top)/rect.height*canvas.height)/scale)));});
canvas.addEventListener("pointerup",()=>dragging=null);canvas.addEventListener("pointercancel",()=>dragging=null);
document.querySelector("#add").addEventListener("click",()=>addActor());
document.querySelector("#demo").addEventListener("click",async()=>{await audio();for(const initial of [{x:0,y:0,frequency:440},{x:0,y:4,frequency:660},{x:0,y:-4,frequency:880}]){const actor=addActor(initial);await connect(actor);}document.querySelector("#audition").value=[...actors.keys()][0];applyAudition();});
document.querySelector("#audio").addEventListener("click",async()=>{
await audio();
if(!document.querySelector("#audition").value){const actor=[...actors.values()].find(actor=>actor.connected);if(actor)document.querySelector("#audition").value=actor.id;}
applyAudition();
for(const actor of actors.values())if(actor.outputElement)actor.outputElement.play().catch(error=>log(`Не удалось включить звук: ${error.message}`));
});
document.querySelector("#interval").addEventListener("change",startPoseTimer);document.querySelector("#audition").addEventListener("change",applyAudition);
startPoseTimer();requestAnimationFrame(frame);
function spectralPeak(analyzer,bins) {
analyzer.getFloatFrequencyData(bins);
const resolution=audioContext.sampleRate/analyzer.fftSize;
let peak=Math.max(1,Math.ceil(40/resolution));
for(let i=peak+1;i<Math.min(bins.length-1,Math.ceil(4000/resolution));i++)if(bins[i]>bins[peak])peak=i;
if(!Number.isFinite(bins[peak])||bins[peak]<-65)return "—";
const a=bins[peak-1],b=bins[peak],c=bins[peak+1],denominator=a-2*b+c;
const offset=Number.isFinite(denominator)&&Math.abs(denominator)>1e-8?Math.max(-.5,Math.min(.5,.5*(a-c)/denominator)):0;
return `${Math.round((peak+offset)*resolution)} Гц`;
}
function sceneStatus(text) { document.querySelector("#walls-state").textContent=text; }
function recoverScene() {
if(!appliedScene||wallRetryTimer)return;
const delay=Math.min(1000*2**Math.min(wallRetryAttempt++,3),8000);
wallRetryTimer=setTimeout(async()=>{
wallRetryTimer=null;
try{await publishScene(appliedScene.objects,appliedScene.enabled,appliedScene.roomName,appliedScene.hrtf,appliedScene.adaptive);}
catch(error){sceneStatus(`Восстановление геометрии: ${error.message}`);recoverScene();}
},delay);
}
async function sceneController(roomName) {
if(wallController?.roomName===roomName&&wallController.room.state===LivekitClient.ConnectionState.Connected)return wallController.room;
if(wallConnectPromise)return wallConnectPromise;
wallConnectPromise=(async()=>{
if(wallController){const old=wallController;wallController=null;await old.room.disconnect();}
const response=await fetch("/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({room:roomName,identity:`scene-controller-${session}`,scene_controller:true}),signal:AbortSignal.timeout(10000)});
if(!response.ok)throw new Error(await response.text());const credentials=await response.json();
const room=new LivekitClient.Room({adaptiveStream:false,dynacast:false}),controller={room,roomName};wallController=controller;
room.on(LivekitClient.RoomEvent.DataReceived,(payload,participant,kind,topic)=>{
if(wallController!==controller||topic!=="sverse.spatial.scene.ack.v1"||!wallPending)return;
try {
const result=JSON.parse(new TextDecoder().decode(payload));
if(result.revision!==wallPending.revision&&result.revision!==0)return;
const pending=wallPending;wallPending=null;clearTimeout(pending.timer);
if(!result.ok){pending.reject(new Error(result.error??"Сцена отклонена сервером"));return;}
appliedScene={objects:pending.objects,enabled:pending.enabled,roomName:pending.roomName,hrtf:pending.hrtf,adaptive:pending.adaptive};wallRetryAttempt=0;
sceneStatus(`HRTF разрешён: ${pending.hrtf?"да":"нет"} · адаптация: ${pending.adaptive?"вкл":"выкл"} · препятствия: ${pending.enabled?"вкл":"выкл"} · объектов: ${pending.objects.length} · сервер подтвердил`);
pending.resolve();
}catch(error){log(`Ответ сервера геометрии: ${error.message}`);}
});
room.on(LivekitClient.RoomEvent.Reconnected,()=>{if(wallController===controller&&appliedScene?.roomName===roomName&&!wallPending)recoverScene();});
room.on(LivekitClient.RoomEvent.Disconnected,()=>{
if(wallController!==controller)return;wallController=null;
if(wallPending){clearTimeout(wallPending.timer);wallPending.reject(new Error("Соединение контроллера прервано"));wallPending=null;}
sceneStatus("Контроллер отключён · восстановление геометрии");recoverScene();
});
try{await room.connect(credentials.url,credentials.token,{autoSubscribe:false});return room;}
catch(error){if(wallController===controller)wallController=null;await room.disconnect();throw error;}
})();
try{return await wallConnectPromise;}finally{wallConnectPromise=null;}
}
async function publishScene(objects,enabled,roomName,hrtf,adaptive) {
const room=await sceneController(roomName);
if(wallPending)throw new Error("Дождитесь подтверждения предыдущей сцены");
wallRevision=Math.max(wallRevision+1,Date.now());
const snapshot={version:1,revision:wallRevision,location_id:roomName,enabled,objects,hrtf,adaptive};
const payload=new TextEncoder().encode(JSON.stringify(snapshot));
if(payload.length>15000)throw new Error("Сцена должна быть не больше 15000 байт");
sceneStatus("Ожидание подтверждения сервера…");
return new Promise((resolve,reject)=>{
const pending={revision:wallRevision,objects,enabled,roomName,hrtf,adaptive,resolve,reject};wallPending=pending;
pending.timer=setTimeout(()=>{if(wallPending===pending){wallPending=null;reject(new Error("Сервер не подтвердил сцену за 5 секунд"));}},5000);
room.localParticipant.publishData(payload,{reliable:true,topic:"sverse.spatial.scene.v1"}).catch(error=>{if(wallPending===pending){clearTimeout(pending.timer);wallPending=null;reject(error);}});
});
}
document.querySelector("#walls-apply").addEventListener("click",async()=>{
const button=document.querySelector("#walls-apply");button.disabled=true;
try {
const objects=JSON.parse(document.querySelector("#walls-json").value);
if(!Array.isArray(objects))throw new Error("Ожидается массив объектов");
clearTimeout(wallRetryTimer);wallRetryTimer=null;
await publishScene(objects,document.querySelector("#walls-enabled").checked,document.querySelector("#room").value,document.querySelector("#hrtf-enabled").checked,document.querySelector("#adaptive-enabled").checked);
}catch(error){sceneStatus(error.message);log(`Геометрия: ${error.message}`);}
finally{button.disabled=false;}
});
document.querySelector("#wall-example").addEventListener("click",()=>{
document.querySelector("#walls-json").value=JSON.stringify([{id:"wall-1",center:[0,2,0],size:[12,6],rotation:[Math.SQRT1_2,0,0,Math.SQRT1_2],transmission:.2}],null,2);
document.querySelector("#walls-enabled").checked=true;sceneStatus("Пример подготовлен · нажмите «Применить к комнате»");
});
document.querySelector("#walls-clear").addEventListener("click",()=>{document.querySelector("#walls-json").value="[]";sceneStatus("Список очищен · нажмите «Применить к комнате»");});
function drawWalls(scale,cx,cy) {
if(!appliedScene||appliedScene.roomName!==document.querySelector("#room").value)return;
for(const object of appliedScene.objects) {
const [qx,qy,qz,qw]=object.rotation,n=Math.hypot(qx,qy,qz,qw),x=qx/n,y=qy/n,z=qz/n,w=qw/n;
const axes=[[1-2*(y*y+z*z),2*(x*y+z*w)],[2*(x*y-z*w),1-2*(x*x+z*z)],[2*(x*z+y*w),2*(y*z-x*w)]];
const points=[];
for(const sx of [-1,1])for(const sy of [-1,1]) {
const offsets=[sx*object.size[0]/2,sy*object.size[1]/2,0];
const px=object.center[0]+offsets.reduce((sum,v,i)=>sum+v*axes[i][0],0),py=object.center[1]+offsets.reduce((sum,v,i)=>sum+v*axes[i][1],0);
points.push([cx+py*scale,cy-px*scale]);
}
points.sort((a,b)=>a[0]-b[0]||a[1]-b[1]);
const cross=(a,b,c)=>(b[0]-a[0])*(c[1]-a[1])-(b[1]-a[1])*(c[0]-a[0]);
const half=list=>{const result=[];for(const point of list){while(result.length>1&&cross(result.at(-2),result.at(-1),point)<=0)result.pop();result.push(point);}return result;};
const hull=half(points).slice(0,-1).concat(half([...points].reverse()).slice(0,-1));
if(!hull.length)continue;
ctx.fillStyle=appliedScene.enabled?"#e4a56c44":"#78839022";ctx.strokeStyle=appliedScene.enabled?"#e4a56c":"#788390";ctx.lineWidth=2;
ctx.beginPath();hull.forEach((p,i)=>i?ctx.lineTo(...p):ctx.moveTo(...p));ctx.closePath();ctx.fill();ctx.stroke();
ctx.fillStyle=ctx.strokeStyle;ctx.fillText(`${object.id} · ×${object.transmission}`,cx+object.center[1]*scale+5,cy-object.center[0]*scale-7);
}
}
+50
View File
@@ -0,0 +1,50 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Spatial audio laboratory</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="walls.css">
<script defer src="https://cdn.jsdelivr.net/npm/livekit-client@2.22.3/dist/livekit-client.umd.js"></script>
<script defer src="app.js"></script>
</head>
<body>
<header><div><h1>Пространственный голос</h1><p>Персональные стереомиксы LiveKit · координаты в метрах</p></div><span id="connection">Локальная лаборатория</span></header>
<main>
<section class="scene">
<div class="toolbar"><label>Комната <input id="room" value="spatial-demo"></label><button id="add">Добавить актора</button><button id="demo">Три тестовых актора</button></div>
<canvas id="map" width="760" height="680" aria-label="Расположение акторов сверху"></canvas>
<div class="settings"><label>Отправка позы <select id="interval"><option>25</option><option selected>50</option><option>75</option><option>100</option><option>150</option></select> мс</label><label>Слушать <select id="audition"><option value="">Тишина</option></select></label><button id="audio">Включить звук</button></div>
<p class="hint">На карте X направлен вверх, Y вправо. Стрелка показывает взгляд. Перетащите актора мышью или используйте ползунки. Радиус на схеме — 20 м; серверные настройки имеют приоритет. Выбранный актор слышит тоны остальных, свой тон в его микс не входит.</p>
<details class="walls-panel" open>
<summary>HRTF, стены и препятствия</summary>
<div class="row"><label><input id="hrtf-enabled" type="checkbox" checked> HRTF для наушников</label></div>
<div class="row"><label><input id="adaptive-enabled" type="checkbox" checked> Автоматически снижать качество при перегрузке</label></div>
<p class="hint">Переключение применяется кнопкой «Применить к комнате». Для оценки направления используйте шум или голос; одиночный тон менее показателен.</p>
<div class="row"><label><input id="walls-enabled" type="checkbox"> Учитывать препятствия</label><button id="wall-example">Пример стены</button><button id="walls-clear">Очистить</button></div>
<p class="hint">Стены плоские, без толщины. size: [ширина, высота] в метрах по локальным X/Y, нормаль — локальная +Z. Центр — в метрах, поворот — quaternion XYZW. transmission: 1 пропускает звук, 0 блокирует. Несколько стен перемножают ослабление.</p>
<p class="hint">priority: 0–100. Без этого поля приоритет 100: объект учитывается всегда. При перегрузке сервер сначала исключает объекты ниже 50, затем ниже 100.</p>
<label for="walls-json">Плоские прямоугольные стены (JSON)</label>
<textarea id="walls-json" spellcheck="false" rows="8">[]</textarea>
<div class="row"><button id="walls-apply">Применить к комнате</button><span id="walls-state" role="status">Геометрия ещё не отправлена</span></div>
</details>
<pre id="log" aria-live="polite"></pre>
</section>
<section id="actors" class="actors" aria-label="Управление акторами"></section>
</main>
<template id="actor-template">
<article class="actor">
<div class="actor-title"><strong></strong><span class="state">Отключён</span></div>
<div class="axis"><label>X <output></output> м</label><input data-axis="x" type="range" min="-30" max="30" step="0.1" value="0"></div>
<div class="axis"><label>Y <output></output> м</label><input data-axis="y" type="range" min="-30" max="30" step="0.1" value="0"></div>
<div class="axis"><label>Z <output></output> м</label><input data-axis="z" type="range" min="-5" max="5" step="0.1" value="0"></div>
<div class="axis"><label>Поворот <output></output> °</label><input data-axis="yaw" type="range" min="-180" max="180" step="1" value="0"></div>
<div class="row"><label>Источник <select class="source"><option value="tone">Тестовый тон</option><option value="noise">Шум</option><option value="microphone">Микрофон</option><option value="silent">Тишина</option></select></label><label>Тон <input class="frequency" type="number" min="100" max="2000" step="10" value="440"> Гц</label></div>
<div class="row"><label><input class="moving" type="checkbox"> Движение по кругу</label><label><input class="turning" type="checkbox"> Поворот головы</label></div>
<div class="meters"><label>L <meter class="left" min="0" max="1" value="0"></meter> <output class="left-value">0.000</output></label><label>R <meter class="right" min="0" max="1" value="0"></meter> <output class="right-value">0.000</output></label></div>
<div class="row">Пик принятого спектра: <output class="spectrum-value">—</output></div>
<div class="row"><button class="connect">Подключить</button><button class="remove">Удалить</button></div>
</article>
</template>
</body>
</html>
+1
View File
@@ -0,0 +1 @@
:root{color-scheme:dark;font-family:system-ui,sans-serif;background:#10161e;color:#e8eef5}*{box-sizing:border-box}body{margin:0}header{display:flex;align-items:center;justify-content:space-between;padding:24px 32px;border-bottom:1px solid #2b3645}h1{font-size:24px;margin:0 0 6px}p{margin:0;color:#99acc0;font-size:14px}#connection{font-size:13px;color:#86d1c2}main{display:grid;grid-template-columns:minmax(420px,1.5fr) minmax(330px,1fr);gap:24px;padding:24px 32px;max-width:1600px;margin:auto}.scene{min-width:0}.toolbar,.settings,.row{display:flex;flex-wrap:wrap;align-items:center;gap:12px}button,input,select{font:inherit;color:inherit}button{background:#2b695c;border:1px solid #398775;border-radius:8px;padding:8px 12px;cursor:pointer}button:hover{background:#347c6d}button:disabled{opacity:.5;cursor:wait}input:not([type=range]):not([type=checkbox]),select{background:#1b2634;border:1px solid #38495e;border-radius:6px;padding:6px;max-width:180px}.toolbar input{width:145px}canvas{display:block;width:100%;height:auto;background:#14202c;border:1px solid #304052;border-radius:12px;margin:16px 0;touch-action:none}.hint{line-height:1.6;margin-top:14px}#log{font:12px ui-monospace,monospace;white-space:pre-wrap;max-height:160px;overflow:auto;color:#a3c2ba}.actors{display:flex;flex-direction:column;gap:16px}.actor{background:#1a2533;border:1px solid #334457;border-left:4px solid var(--actor-color);padding:16px;border-radius:10px}.actor-title{display:flex;justify-content:space-between;margin-bottom:14px}.state{font-size:12px;color:#99acc0}.axis{margin:8px 0}.axis label{display:flex;justify-content:space-between;font-size:13px}.axis input{width:100%;accent-color:var(--actor-color)}.row{margin-top:12px;font-size:13px}.frequency{width:80px}.meters{display:flex;gap:16px;margin-top:14px}.meters label{display:flex;align-items:center;gap:8px;flex:1;font-size:12px}meter{width:100%}@media(max-width:850px){main{display:block;padding:16px}.actors{margin-top:24px}header{padding:16px}#connection{display:none}}
+5
View File
@@ -0,0 +1,5 @@
.walls-panel{background:#1a2533;border:1px solid #334457;border-radius:10px;padding:14px;margin-top:16px}
.walls-panel summary{cursor:pointer;font-weight:600}
.walls-panel textarea{display:block;width:100%;margin-top:8px;padding:10px;background:#101a25;color:#d9e6f0;border:1px solid #38495e;border-radius:6px;font:12px ui-monospace,monospace;resize:vertical}
.walls-panel>label{display:block;font-size:13px;margin-top:12px}
#walls-state{font-size:12px;color:#a3c2ba}
+41
View File
@@ -0,0 +1,41 @@
# Local development only. Start from the repository root.
port: 7880
bind_addresses:
- 127.0.0.1
rtc:
tcp_port: 7881
udp_port: 7882
use_external_ip: false
keys:
devkey: spatial-local-development-secret
room:
spatial_audio:
enabled: true
room_prefix: spatial-
max_participants: 32
near_distance: 1
max_distance: 20
smoothing_ms: 30
pose_timeout_ms: 500
jitter_ms: 40
bitrate: 64000
debug_stats: true
adaptive:
enabled: true
pose_interval_ms: 50
overload_ratio: 0.7
recovery_ratio: 0.4
degrade_after_ms: 2000
recover_after_ms: 10000
cooldown_ms: 3000
hrtf:
enabled: true
interpolation: bilinear
library: .spatial-runtime/hrtf-build/Release/sverse_hrtf.dll
occlusion:
enabled: true
max_objects: 64
# Windows development build; on Linux use library: libopus.so.0
library: .spatial-runtime/opus-build/Release/opus.dll
logging:
level: info
+10
View File
@@ -117,6 +117,16 @@ rtc:
# # in the unlikely event of highly congested networks, SFU may choose to pause some tracks
# # in order to allow others to stream smoothly. You can disable this behavior here
# allow_pause: true
# # use send-side bandwidth estimation instead of relying on receiver reports, default false
# use_send_side_bwe: false
# # how egress is paced when use_send_side_bwe is enabled. one of:
# # no-queue - hand packets to a send worker that drains them without rate
# # limiting, so the sender never blocks on a write (default)
# # pass-through - send each packet inline on the calling goroutine
# # leaky-bucket - accepted, but not currently wired to the bandwidth estimate; it
# # logs a warning and falls back to no-queue. see livekit/livekit#4724
# # an unrecognized value is rejected at startup.
# send_side_bwe_pacer: no-queue
# # allows automatic connection fallback to TCP and TURN/TLS (if configured) when UDP has been unstable, default true
# allow_tcp_fallback: true
# # signaling RTT (in milliseconds) below which ICE/TCP is attempted on a UDP failure; at or above it,
+21
View File
@@ -0,0 +1,21 @@
# Copy to an untracked file, e.g. deploy/spatial/instances/courtyard.env.
SPATIAL_DEPLOYMENT_ID=sverse-courtyard
SPATIAL_LOCATION_ID=courtyard-session-1
SPATIAL_IMAGE=sverse/livekit-spatial:local
# Replace with the address reachable by players, not the Docker container IP.
SPATIAL_NODE_IP=192.168.22.100
# 127.0.0.1 for reverse proxy on this host; 0.0.0.0 for direct LAN access.
SPATIAL_BIND_IP=127.0.0.1
# Signaling/API: base; ICE TCP: base+1; ICE UDP: base+2.
SPATIAL_PORT_BASE=17880
SPATIAL_ROOMS=spatial-courtyard-main,spatial-courtyard-stage
SPATIAL_EMPTY_TIMEOUT=300
LIVEKIT_API_KEY=replace-with-location-key
LIVEKIT_API_SECRET=
SPATIAL_HRTF=true
SPATIAL_HRTF_INTERPOLATION=bilinear
SPATIAL_OCCLUSION=true
SPATIAL_ADAPTIVE=true
SPATIAL_MAX_PARTICIPANTS=32
SPATIAL_CPUS=2
SPATIAL_MEMORY=1g
+47
View File
@@ -0,0 +1,47 @@
# syntax=docker/dockerfile:1
# Linux amd64: Steam Audio's official x64 SDK requires glibc.
ARG GO_IMAGE=golang:1.26.7-bookworm@sha256:e8c859f5632dcfde7b32d2012b4351728f6437930887c2f6a91ea242459e5514
ARG RUNTIME_IMAGE=debian:bookworm-slim@sha256:3783cc01769c7b2b1b83a5c5ad96c815348e28ed7da68e2e3687004faa906251
FROM ${GO_IMAGE} AS builder
ARG TARGETARCH
RUN test "$TARGETARCH" = amd64
WORKDIR /src
ENV GOTOOLCHAIN=local CGO_ENABLED=0
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod go mod download
COPY cmd/ cmd/
COPY pkg/ pkg/
COPY version/ version/
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
go build -trimpath -o /out/livekit-server ./cmd/server && \
go build -trimpath -o /out/spatial-node ./cmd/spatial-node
FROM ${RUNTIME_IMAGE} AS hrtf-builder
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl unzip cmake g++ make \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /sdk
RUN curl --fail --location --retry 3 --output steam.zip \
https://github.com/ValveSoftware/steam-audio/releases/download/v4.8.1/steamaudio_4.8.1.zip \
&& echo '4a0aa5ec1176f38f0b0993a37c2259d9e86f27e22d5e24f83ec4c3cb9a1d5449 steam.zip' | sha256sum -c - \
&& unzip -q steam.zip && rm steam.zip
COPY native/hrtf/ /bridge/
RUN cmake -S /bridge -B /build -DCMAKE_BUILD_TYPE=Release -DSTEAMAUDIO_ROOT=/sdk/steamaudio \
&& cmake --build /build --parallel 2
FROM ${RUNTIME_IMAGE} AS runtime
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates libopus0 libstdc++6 libgcc-s1 libgomp1 \
&& rm -rf /var/lib/apt/lists/* \
&& groupadd --gid 10001 spatial && useradd --uid 10001 --gid spatial --no-create-home spatial \
&& mkdir -p /run/spatial && chown spatial:spatial /run/spatial
COPY --from=builder /out/ /usr/local/bin/
COPY --from=hrtf-builder /build/libsverse_hrtf.so /build/libphonon.so /opt/sverse/hrtf/
COPY --from=hrtf-builder /sdk/steamaudio/THIRDPARTY.md /usr/share/licenses/steam-audio/THIRDPARTY.md
COPY docs/third-party/steam-audio-LICENSE.md /usr/share/licenses/steam-audio/LICENSE.md
COPY LICENSE /usr/share/licenses/livekit/LICENSE
ENV LD_LIBRARY_PATH=/opt/sverse/hrtf
USER 10001:10001
STOPSIGNAL SIGTERM
HEALTHCHECK --interval=10s --timeout=3s --start-period=60s --retries=3 \
CMD ["/usr/local/bin/spatial-node", "health"]
ENTRYPOINT ["/usr/local/bin/spatial-node"]
CMD ["run"]
+181
View File
@@ -0,0 +1,181 @@
# Docker: LiveKit с пространственными комнатами
Пакет для будущего Linux x64 Docker-хоста. Один Compose project — один процесс
нашего LiveKit для экземпляра локации. В нём может быть несколько комнат.
Развёртывание инфраструктуры, DNS, TLS и TURN в этот пакет не входят.
Образ содержит наш сервер, libopus, Steam Audio 4.8.1, нативный HRTF-адаптер,
лицензии и утилиту `spatial-node`. Debian/glibc нужен для официальной библиотеки
Steam Audio. Go остаётся без CGO. Базовые образы закреплены digest, SDK — SHA256.
APT-пакеты получают версии доступного репозитория Debian: вся сборка не побитово
воспроизводима. Для поставки образа фиксировать digest уже собранного результата.
## Сборка
Из корня репозитория на хосте с работающим Docker Engine и Compose:
```bash
docker buildx build --platform linux/amd64 --load \
-f deploy/spatial/Dockerfile -t sverse/livekit-spatial:local .
```
Для сборки нужен интернет: Go modules, Debian packages и официальный архив
Steam Audio (около 180 МБ). Поддерживается только linux/amd64; ARM64 пока нет.
Оригинальный корневой Dockerfile остаётся вариантом Alpine без HRTF.
## Параметры экземпляра локации
```bash
mkdir -p deploy/spatial/instances
cp deploy/spatial/.env.example deploy/spatial/instances/courtyard.env
chmod 600 deploy/spatial/instances/courtyard.env
```
Отредактировать файл:
- SPATIAL_DEPLOYMENT_ID — уникальное имя Compose project, например sverse-courtyard.
- SPATIAL_LOCATION_ID — идентификатор экземпляра локации; попадает в metadata комнат.
- SPATIAL_NODE_IP — IP Docker-хоста, доступный игрокам по медиапортам.
- SPATIAL_PORT_BASE — первый из трёх портов: API/WebSocket, затем ICE TCP и ICE UDP.
- SPATIAL_ROOMS — имена комнат через запятую, каждое с префиксом spatial-.
- LIVEKIT_API_KEY и LIVEKIT_API_SECRET — свои ключи; secret минимум 32 байта.
Для генерации, например `openssl rand -hex 32`; поместить результат в env-файл.
- SPATIAL_BIND_IP=127.0.0.1 — сигналинг/API только для reverse proxy на этом хосте;
SPATIAL_BIND_IP=0.0.0.0 — прямой доступ по LAN без TLS. Это два поддержанных значения.
Файл экземпляра содержит секрет. instances/ и .env исключены из Git и Docker
build context. Не выполнять `docker compose config` без `--quiet` на реальных
секретах в публичном терминале: команда разворачивает значения environment.
Переменные контейнера доступны пользователю с правами Docker — это модель первого
пакета, без собственного secret-manager. В бэкенд передавать те же ключи защищённо.
## Запуск и остановка
```bash
docker compose --env-file deploy/spatial/instances/courtyard.env \
-f deploy/spatial/compose.yaml up -d --no-build
docker compose --env-file deploy/spatial/instances/courtyard.env \
-f deploy/spatial/compose.yaml ps
docker compose --env-file deploy/spatial/instances/courtyard.env \
-f deploy/spatial/compose.yaml logs --tail=100 livekit
docker compose --env-file deploy/spatial/instances/courtyard.env \
-f deploy/spatial/compose.yaml down
```
Для build + up можно убрать --no-build и использовать up -d --build.
Изменённые параметры применяются через повторный up -d, с пересозданием контейнера.
Это прерывает комнаты. RoomAdmin-флаги текущих комнат по-прежнему меняются scene v1.
Жёсткое runtime-управление нодой без restart пока не реализовано.
Compose использует Linux network_mode=host без ports mapping: портовое значение
в конфигурации совпадает с адресом, который LiveKit сообщает клиенту. Сигналинг/API
не должен конфликтовать с уже запущенным сервером или другим Compose project.
Для Docker Desktop этот шаблон не заявлен рабочим production-развёртыванием:
планировать Linux-хост с прямой сетевой доступностью.
## Несколько локаций на одном хосте
Создать второй env-файл с другим SPATIAL_DEPLOYMENT_ID, SPATIAL_LOCATION_ID,
ключами, комнатами и SPATIAL_PORT_BASE. Например:
| Локация | Project | API/WS TCP | ICE TCP | ICE UDP |
|---|---|---|---|---|
| courtyard | sverse-courtyard | 17880 | 17881 | 17882 |
| hall | sverse-hall | 17890 | 17891 | 17892 |
Запустить тот же compose.yaml с env-файлом hall.env. Комнаты разных процессов
независимы, общий Redis здесь не настроен. В metadata указывается location_id,
но она не назначает стены или профиль автоматически. Для единого акустического
пространства использовать одну комнату: между разными комнатами звук не миксуется.
## Что происходит при старте
1. spatial-node проверяет переменные, формирует `/run/spatial/livekit.yaml`
в tmpfs, с правами 0600; YAML/ключи в лог не выводятся.
2. Загружает Opus и, если разрешён, HRTF, создаёт/закрывает движок для проверки
доступности библиотек. Ошибка останавливает контейнер до допуска игроков.
3. Запускает LiveKit, пересылает SIGTERM/SIGINT. Compose init=true помогает
корректно собирать дочерние процессы.
4. Ждёт штатный API до 45 секунд и вызывает CreateRoom для SPATIAL_ROOMS.
5. Записывает readiness-файл после успешного bootstrap. Docker healthcheck
проверяет его и авторизованный ListRooms; token/grants/scene в лог не выводятся.
Health означает доступность процесса/API и успешную начальную инициализацию,
а не подтверждение загрузки стен или слышимости звука. Стены и requested-флаги
локации должен отправить контроллер с RoomAdmin, затем дождаться scene ACK
до открытия голосового допуска игрокам. [Протокол и роли](../../docs/spatial-integration/README.md).
Автоматически созданные пустые комнаты могут исчезнуть через SPATIAL_EMPTY_TIMEOUT
(по умолчанию 300 секунд). Bootstrap не держит их живыми и не воссоздаёт циклически.
Первое подключение может создать комнату заново; контроллер должен прислать сцену
для её нового экземпляра. Постоянный контроллер удерживает комнату непустой.
Пустой SPATIAL_ROOMS разрешён: комнаты создаёт внешний бэкенд. Bootstrap-проверка
API и нативных библиотек всё равно выполняется.
## Доступ для клиента и контроллера
Внешний бэкенд подписывает JWT ключами этого контейнера. Для ручной интеграции
есть утилита выдачи room-specific токена с TTL 15 минут. Пример для LAN:
```bash
docker compose --env-file deploy/spatial/instances/courtyard.env \
-f deploy/spatial/compose.yaml exec -T livekit \
spatial-node token --room spatial-courtyard-main --identity player-1 \
--url ws://192.168.22.100:17880
```
Для доверенного сервера локации добавить `--controller`, задать identity
`scene-controller-courtyard`. Он получит hidden RoomAdmin, canPublishData=true,
canPublish=false и canSubscribe=false. Вывод — JSON с url, room и token.
Контроллер занимает participant-slot: при лимите 32 и одном контроллере доступны
31 игрок. Этот CLI предназначен для операторов/бэкенда, а не публичного token endpoint.
RoomAdmin-токен нельзя передавать обычному игроку. Процедура не публикует стены
сама — сервер локации подключается SDK и отправляет сцену.
## Опции и ресурсы
SPATIAL_HRTF, SPATIAL_OCCLUSION и SPATIAL_ADAPTIVE независимо принимают true/false.
Это серверные разрешения: выключенную здесь функцию RoomAdmin не сможет включить.
При occlusion=false сцены должны иметь enabled=false и objects=[].
Весь spatial pipeline остаётся включён, чтобы отключение эффектов не меняло
персональные миксы на обычную SFU-рассылку.
Другие настройки: SPATIAL_HRTF_INTERPOLATION=nearest/bilinear,
SPATIAL_MAX_PARTICIPANTS, SPATIAL_NEAR_DISTANCE, SPATIAL_MAX_DISTANCE,
SPATIAL_BITRATE, SPATIAL_MAX_OBSTACLES, SPATIAL_POSE_INTERVAL_MS,
SPATIAL_DEBUG_STATS. Сглаживание 30 мс, pose timeout 500 мс, jitter 40 мс и пороги
adaptive пока берутся из дефолтов движка. Текущий список переменных виден в compose.yaml.
Отдельный volume с пользовательским YAML этот entrypoint пока не принимает.
SPATIAL_CPUS=2 и SPATIAL_MEMORY=1g — стартовые лимиты контейнера, не гарантия
числа поддерживаемых участников. Go автоматически учитывает cgroup CPU limits;
нагрузку HRTF и плотность комнат нужно измерить. Контейнер запускается от UID 10001,
с read-only filesystem и tmpfs для конфигурации, без дополнительных capabilities.
Число участников в каждой комнате ограничено отдельно, общего лимита комнат
ноды пока нет. Docker unhealthy сам по себе не вызывает restart: restart policy
реагирует на остановку процесса, а обработку unhealthy выполняет будущий оркестратор.
## Сеть и будущая инфраструктура
Для LAN с прямым ws использовать bind=0.0.0.0 и указанный port base. В браузере
микрофон вне loopback требует HTTPS. Для внешнего доступа нужен reverse proxy с
TLS и WebSocket upgrade, публичный wss URL и firewall/NAT для ICE TCP/UDP.
Reverse proxy должен иметь доступ к loopback Docker-хоста; прокси в отдельном
bridge-контейнере не видит этот loopback автоматически. TURN в пакете не включён.
Эти параметры предстоит подобрать после подготовки инфраструктуры.
Источники: [Docker host network](https://docs.docker.com/engine/network/drivers/host/),
[Compose services](https://docs.docker.com/reference/compose-file/services/),
[порты LiveKit](https://docs.livekit.io/transport/self-hosting/ports-firewall/).
## Статус подготовки
Утилита и сервер собраны для Linux amd64. Compose проверен на уровне конфигурации.
На машине разработки Docker Engine не работает: сам образ, нативная Linux-сборка
HRTF внутри него и запуск контейнера ещё не проверены. Нагрузочные/слуховые тесты
не запускались. При первом запуске на Docker-хосте сначала собрать образ и
подтвердить native initialization, bootstrap и health, затем подключить контроллер
и клиентов по документации интеграции.
+46
View File
@@ -0,0 +1,46 @@
name: ${SPATIAL_DEPLOYMENT_ID:-sverse-spatial}
services:
livekit:
image: ${SPATIAL_IMAGE:-sverse/livekit-spatial:local}
platform: linux/amd64
build:
context: ../..
dockerfile: deploy/spatial/Dockerfile
# Linux host: no port remapping. Each location uses a distinct PORT_BASE.
network_mode: host
init: true
restart: unless-stopped
stop_grace_period: 2m
read_only: true
tmpfs:
- /run/spatial:uid=10001,gid=10001,mode=0700,size=4m
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
cpus: ${SPATIAL_CPUS:-2}
mem_limit: ${SPATIAL_MEMORY:-1g}
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
environment:
LIVEKIT_API_KEY: ${LIVEKIT_API_KEY:?Set LIVEKIT_API_KEY}
LIVEKIT_API_SECRET: ${LIVEKIT_API_SECRET:?Set LIVEKIT_API_SECRET}
SPATIAL_LOCATION_ID: ${SPATIAL_LOCATION_ID:-local-location}
SPATIAL_NODE_IP: ${SPATIAL_NODE_IP:?Set reachable SPATIAL_NODE_IP}
SPATIAL_BIND_IP: ${SPATIAL_BIND_IP:-127.0.0.1}
SPATIAL_PORT_BASE: ${SPATIAL_PORT_BASE:-7880}
SPATIAL_ROOMS: ${SPATIAL_ROOMS-spatial-main}
SPATIAL_EMPTY_TIMEOUT: ${SPATIAL_EMPTY_TIMEOUT:-300}
SPATIAL_ROOM_PREFIX: ${SPATIAL_ROOM_PREFIX:-spatial-}
SPATIAL_MAX_PARTICIPANTS: ${SPATIAL_MAX_PARTICIPANTS:-32}
SPATIAL_NEAR_DISTANCE: ${SPATIAL_NEAR_DISTANCE:-1}
SPATIAL_MAX_DISTANCE: ${SPATIAL_MAX_DISTANCE:-20}
SPATIAL_BITRATE: ${SPATIAL_BITRATE:-64000}
SPATIAL_HRTF: ${SPATIAL_HRTF:-true}
SPATIAL_HRTF_INTERPOLATION: ${SPATIAL_HRTF_INTERPOLATION:-bilinear}
SPATIAL_OCCLUSION: ${SPATIAL_OCCLUSION:-true}
SPATIAL_MAX_OBSTACLES: ${SPATIAL_MAX_OBSTACLES:-64}
SPATIAL_ADAPTIVE: ${SPATIAL_ADAPTIVE:-true}
SPATIAL_POSE_INTERVAL_MS: ${SPATIAL_POSE_INTERVAL_MS:-50}
SPATIAL_DEBUG_STATS: ${SPATIAL_DEBUG_STATS:-true}
+101
View File
@@ -0,0 +1,101 @@
# Адаптивное качество пространственного аудио
Автоматика управляет эффективным качеством, сохраняя заданные настройки комнаты.
Отключённый вручную HRTF или учёт препятствий автоматически не включается.
Spatial audio, HRTF, occlusion и adaptive имеют независимые серверные `enabled`.
Контроллер комнаты с RoomAdmin может отключать/включать доступные HRTF, стены
и адаптацию через reliable-сцену. Обычные участники эти настройки не меняют.
## Уровни
Для значений по умолчанию:
| Уровень | Пересчёт пространственных параметров | HRTF, если разрешён | Учитываемые препятствия |
|---|---|---|---|
| 0 | 50 мс | настроенная интерполяция | все |
| 1 | 100 мс | nearest | все |
| 2 | 150 мс | nearest | priority >= 50 |
| 3 | 250 мс | выключен, стереопанорамирование | priority = 100 |
Периоды равны базовому `pose_interval_ms`, умноженному на 1, 2, 3, 5.
При отключении adaptive геометрия обновляется каждые 10 мс, как до внедрения
автоматики. При этом пересчёт матрицы по-прежнему происходит только для изменений.
Аудиодекодирование, микширование и сглаживание работают каждые 10 мс при всех
уровнях, а стерео Opus выдаётся блоками 20 мс. Позы поступают с прежней частотой:
на сервере объединяются изменения до следующего пересчёта. Это экономит расчёты,
но не трафик. Для HRTF используются те же отложенные координаты и поворот головы.
Удаление и истечение поз не ждут длинного интервала; сцена и смена уровня также
применяются при ближайшем тике. Ослабление и переход HRTF сглаживаются микшером.
## Приоритеты препятствий
У объекта сцены появилось необязательное целое поле `priority` от 0 до 100.
По умолчанию оно равно 100: существующая карта продолжает учитывать все стены.
Для сокращения расчётов нужно явно назначить второстепенным объектам меньший
приоритет. Пример декоративного препятствия:
```json
{"id":"partition","center":[0,2,0],"size":[12,6],"rotation":[0.7071067811865476,0,0,0.7071067811865476],"transmission":0.2,"priority":25}
```
При исключении препятствия звук за ним становится громче. Для стен, которые
обязательно должны препятствовать слышимости, оставлять priority=100.
На каждом изменении порога матрица инвалидируется и пересчитывается.
## Как определяется перегрузка
Раз в секунду каждый движок комнаты сообщает время обработки тиков и количество
пропусков. Общий для процесса реестр собирает сведения всех spatial-комнат:
- долю времени работы spatial-движков, нормированную на GOMAXPROCS;
- максимальное среднее время тика комнаты относительно бюджета 10 мс;
- максимальную долю пропущенных тиков, нормированную на 5%.
Максимум этих трёх сигналов образует pressure. Он сглаживается EMA с коэффициентом
0.25. Это индикатор доступного аудиобюджета, а не общий CPU сервера. Нагрузка
прочих подсистем проявится здесь, если увеличит задержки аудиопотоков. Закрытые
комнаты удаляются из реестра, записи старше трёх секунд не учитываются.
Очень длительную блокировку ещё работающего потока нельзя измерить до его возврата.
По умолчанию pressure >= 0.7 в течение двух секунд повышает уровень деградации
на одну ступень. Pressure <= 0.4 в течение десяти секунд снижает его на одну.
Между переходами выдерживается минимум три секунды. Диапазон 0.4–0.7 сбрасывает
таймеры устойчивого превышения/восстановления. Сглаживание добавляет задержку
реакции; автоматика не является защитой от мгновенной остановки процесса.
```yaml
room:
spatial_audio:
adaptive:
enabled: true
pose_interval_ms: 50
overload_ratio: 0.7
recovery_ratio: 0.4
degrade_after_ms: 2000
recover_after_ms: 10000
cooldown_ms: 3000
```
Новая настройка reliable-сцены: `"adaptive": true` или `false`. Отсутствующее
поле сохраняет текущий режим. Включение запрещено, если серверный adaptive.enabled
выключен. Отключение сбрасывает уровень к 0 и возвращает заданное качество HRTF
и полный набор препятствий. Это делается в потоке комнаты вместе с применением
сцены, после её проверки и проверки возраста ревизии.
В HTML-клиенте переключатель «Автоматически снижать качество при перегрузке»
применяется кнопкой «Применить к комнате», состояние восстанавливается при
переподключении контроллера. Подтверждение сообщает разрешённые функции, а не
текущий уровень качества. Текущий уровень доступен в серверных логах.
## Метрики и статус
Spatial stats дополнены: `adaptive`, `quality_level`, `load_pressure`,
`pose_interval`, `active_obstacles`, `effective_hrtf`, `quality_transitions`.
`hrtf` сохраняет заданный режим, `effective_hrtf` показывает реально выбранный
off/nearest/bilinear. Во время плавного отключения HRTF фильтры могут ещё
обрабатываться короткое время и оставаться в `hrtf_pairs`.
Windows-сборка выполнена. Нагрузочные и слуховые проверки переходов в этом
проходе не запускались; пороги и интервалы требуют дальнейшей настройки по
реальной нагрузке. Ограничение числа участников остаётся необходимым:
даже уровень 3 не убирает стоимость декодирования, суммирования и Opus-кодирования.
+123
View File
@@ -0,0 +1,123 @@
# Пространственный голос: локальный стенд
Интеграция с метавселенной: [клиент, бэкенд, сервер локации и админка](spatial-integration/README.md).
Docker для локаций: [образ с HRTF, Compose и настройки](../deploy/spatial/README.md).
## Запуск на Windows
Из корня репозитория, в PowerShell:
```powershell
# Один раз: нужны Git, CMake и Visual Studio 2022 с C++ toolchain.
.\scripts\build-spatial-opus.ps1
.\scripts\build-spatial-hrtf.ps1
# Нужен Go соответствующей версии из go.mod.
.\scripts\start-spatial.ps1
# Пересобрать и перезапустить уже запущенный стенд:
.\scripts\start-spatial.ps1 -Restart
# Остановить процессы только этого checkout:
.\scripts\stop-spatial.ps1
```
Открыть **http://127.0.0.1:8899/**. Открытие `index.html` через `file://` не работает:
клиенту нужен HTTP endpoint `/token`. После изменения клиента обновить страницу
через Ctrl+F5. SDK загружается с CDN; нужен доступ к jsDelivr.
Нажать «Три тестовых актора». Первый слушатель находится между двумя источниками
с разными частотами. В списке «Слушать» можно выбрать, чей микс воспроизводить.
Один актор не слышит собственный источник. При ручном подключении первого актора
его микс выбирается автоматически; кнопка «Включить звук» возобновляет
воспроизведение и выбирает подключённого актора, если была выбрана «Тишина».
Ползунки задают координаты в метрах и поворот вокруг Z. Акторов можно таскать
по карте; флажки включают движение по кругу и поворот головы. Индикаторы L/R
показывают RMS полученного микса до выбора прослушиваемого участника.
«Пик принятого спектра» показывает наиболее сильную составляющую каждого уха
в полосе 40–4000 Гц. Это приблизительная FFT оценка, а не измеритель основного
тона речи. Для сравнения частот оставить один слышимый источник; выбранный
слушатель своего тона не слышит. Например, слушая актора 1 стандартной тройки,
получаем 880 Гц слева и 660 Гц справа, а не собственные 440 Гц.
Генератор передаётся SDK как user-provided track, чтобы reconnect не заменял
его физическим микрофоном.
Источник (тон / микрофон / тишина) переключается без выхода из комнаты.
Микрофон потребует обычного разрешения браузера при выборе этого источника.
При временном обрыве сети восстановление сначала выполняет SDK. После
окончательного разрыва клиент освобождает аудиоресурсы, получает свежий токен
и повторяет подключение с задержками 1/2/4/8 секунд. Кнопки «Отключить» и
«Удалить» прекращают повторные попытки. При восстановлении передаётся свежая
поза и восстанавливается подписка на персональный микс. Комната актора
сохраняется до явного отключения, даже если поле комнаты было изменено.
Стенд использует публичные dev credentials из `config-sample-spatial.yaml`.
HTTP endpoint и сигнализация слушают loopback. Эти credentials и token service
предназначены для локальной разработки; для deployment нужен отдельный token service.
## Серверные параметры
`room.spatial_audio` в `config-sample-spatial.yaml` включает режим для комнат
с префиксом `spatial-`. Обычные комнаты используют стандартный SFU.
Начальные параметры: 32 участника, дальность 20 м, сглаживание 30 мс,
timeout позы 500 мс, jitter buffer 40 мс и stereo Opus 64 kbit/s.
Постоянная матрица хранит целевые gain для каждой пары. Перемещение обновляет
строку и столбец участника; поворот — его строку. Пакет heartbeat с неизменной
геометрией не пересчитывает коэффициенты. За радиусом цель равна нулю;
аудиотакт плавно доводит gain до нуля, затем пропускает умножение этой пары.
`debug_stats: true` выводит статистику комнаты раз в 5 секунд:
| Поле | Значение |
| --- | --- |
| `sources`, `listeners`, `poses` | Число источников, получателей и свежих поз |
| `received`, `dropped` | Принятые пакеты и сбросы входной очереди с начала жизни комнаты |
| `concealed` | Пропуски пакетов с FEC/PLC с начала жизни комнаты, включая хвост при выходе |
| `late`, `rebuffers`, `decode_errors` | Опоздавшие пакеты, восстановление запаса jitter buffer и ошибки декодирования |
| `input_peak`, `output_peak` | Пик PCM в текущем блоке |
| `matrix_calculations` | Число расчётов пар с начала жизни комнаты |
| `tick`, `max_tick` | Последняя и максимальная длительность decode/mix/encode |
| `missed`, `output_errors` | Пропуски 10 мс такта и ошибки выходных пакетов |
`tick` измеряет обработку на сервере, а не задержку «микрофон → ухо».
После трёх последовательно продвигающихся опоздавших пакетов без будущих данных
playout восстанавливает опорный timestamp и начальный запас jitter. Это устраняет
режим, в котором все поступающие пакеты отбрасывались после задержки и decoder
продолжал выдавать только PLC. Полноценная адаптивная коррекция clock drift всё
ещё требует отдельного прохода; при rebuffer возможна короткая пауза.
Логи и двоичные файлы находятся в `.spatial-runtime/`, вне Git.
При прекращении публикации вход закрывается сразу; decoder кратковременно
формирует PLC хвост с экспоненциальным затуханием (5 постоянных сглаживания,
150 мс при стандартных 30 мс), затем освобождается. При выходе участника
его encoder удаляется сразу. При закрытии комнаты все codecs освобождаются.
Это затухание не удерживает участника в комнате и не принимает новый звук.
Входной RTP clock периодически переопределяет опорную точку без сброса decoder;
выходные Sender Reports учитывают переполнение 32-bit RTP timestamp.
## Linux
Go код собирается с `CGO_ENABLED=0`, но при запуске нужна native `libopus`.
Основной Dockerfile устанавливает Alpine package `opus`. В Linux конфигурации
заменить `library` на `libopus.so.0`. Docker image в этой реализации пока не
проверен запуском; Windows сборка использует DLL Opus 1.5.2.
## Что ещё требует отдельного прохода
Опциональные стены: [протокол и инструкция](spatial-audio-occlusion.md).
В стенде доступен редактор геометрии и отдельный контроллер с подтверждением сервера.
- Восстановление при reconnect, выход из зоны, смена микрофона и запрет чужих
подписок реализованы, но полный набор сценариев ещё нужно подтвердить.
- Длительные сессии, коррекция drift, packet loss и нагрузка 4/8/16/32 участников.
- Подбор интервала позы 25/50/75/100/150 мс по прослушиванию. 50 мс — исходная
настройка, а не измеренный оптимум.
- UE интеграция: упаковка pose packet, cm → m и stereo воспроизведение микса
без повторной пространственной обработки.
- Доступны stereo panning и опциональный серверный HRTF: [сборка и настройки](spatial-audio-hrtf.md).
- Доступна опциональная [деградация по нагрузке](spatial-audio-adaptive.md): интервалы геометрии, приоритеты препятствий и качество HRTF.
- RED извлекает primary payload; восстановление из redundant blocks пока отсутствует.
Клиентское E2EE несовместимо с серверной обработкой: зашифрованные источники
пропускаются с предупреждением в логе сервера. Обычный WebRTC DTLS/SRTP поддерживается.
+112
View File
@@ -0,0 +1,112 @@
# Серверный HRTF
В персональном миксе используется Steam Audio 4.8.1 со встроенным набором HRTF.
Каждая слышимая пара «источник → слушатель» имеет собственное состояние фильтра.
Моно PCM 48 кГц обрабатывается блоками 480 сэмплов и превращается в стерео.
Направление рассчитывается относительно quaternion головы слушателя, включая
высоту источника. Координаты приложения: вперёд +X, вправо +Y, вверх +Z.
После HRTF применяется общий коэффициент расстояния и препятствий, затем
источники суммируются, ограничиваются стереолимитером и кодируются в Opus.
Повторного стереопанорамирования внутри HRTF нет. Стены по-прежнему только
уменьшают амплитуду: отражений, дифракции и реверберации эта версия не моделирует.
## Сборка и конфигурация
Основной сценарий — контейнер на **Linux x64**, Docker Engine и Docker Compose.
Использовать `deploy/spatial/Dockerfile` на Debian/glibc. Образ сам скачивает
Steam Audio 4.8.1, проверяет SHA256 и собирает нативный адаптер. CMake и C++
компилятор нужны только внутри стадии сборки, устанавливать их на сервер не нужно.
Go вызывает адаптер через purego; CGO не требуется.
Из корня репозитория:
```bash
docker buildx build --platform linux/amd64 --load \
-f deploy/spatial/Dockerfile -t sverse/livekit-spatial:local .
mkdir -p deploy/spatial/instances
cp deploy/spatial/.env.example deploy/spatial/instances/location.env
chmod 600 deploy/spatial/instances/location.env
```
Перед запуском заполнить `location.env`: уникальное имя deployment, IP сервера,
порты, имена комнат, API key и API secret минимум 32 байта. Для включения HRTF:
```dotenv
SPATIAL_HRTF=true
SPATIAL_HRTF_INTERPOLATION=bilinear
```
Запуск после заполнения файла:
```bash
docker compose --env-file deploy/spatial/instances/location.env \
-f deploy/spatial/compose.yaml up -d --no-build
```
Утилита контейнера генерирует `/run/spatial/livekit.yaml`. HRTF-часть этой
конфигурации выглядит так; вручную подставлять Windows-пути не требуется:
```yaml
room:
spatial_audio:
hrtf:
enabled: true
interpolation: bilinear
library: /opt/sverse/hrtf/libsverse_hrtf.so
```
`enabled: false` оставляет обычное панорамирование без загрузки библиотеки.
`enabled: true` загружает HRTF при создании spatial-комнаты и включает его по
умолчанию. Ошибка загрузки не скрывается: создание движка комнаты завершится
ошибкой. `interpolation` принимает `nearest` или `bilinear`; это выбор способа
интерполяции направлений, а не изменение длины фильтра. Автоматическое управление
качеством по нагрузке описано в [адаптивном режиме](spatial-audio-adaptive.md).
В образе `libphonon.so` находится рядом с `libsverse_hrtf.so`; лицензии включены.
Корневой Alpine Dockerfile для HRTF не подходит. Настройки портов, нескольких
локаций, комнат и секретов описаны в [Docker-инструкции](../deploy/spatial/README.md).
Linux-образ ещё не собран и не проверен запуском: Docker Engine на машине
разработки не работает. Windows PowerShell-скрипты относятся только к
[локальному стенду разработки](spatial-audio-development.md), а не к Linux-деплою.
## Переключение в комнате
Контроллер с RoomAdmin отправляет reliable-сцену в `sverse.spatial.scene.v1`:
```json
{"version":1,"revision":123,"location_id":"spatial-demo","enabled":false,"objects":[],"hrtf":true}
```
Поле `hrtf` необязательно: отсутствие сохраняет текущий режим. `false` отключает
HRTF, `true` включает его, если модуль разрешён серверной конфигурацией. Ревизии
и подтверждения совпадают с протоколом препятствий. Переключение всего микса
сглаживается согласно `smoothing_ms`; публикация и кодировщик сохраняются.
После затухания эффекта состояния фильтров освобождаются. Недоступные пары
исключаются после затухания коэффициента. При ошибке обработки пары используется
обычное панорамирование и увеличивается счётчик ошибок.
В HTML-клиенте: обновить страницу, переключить «HRTF для наушников» и нажать
«Применить к комнате». Для сравнения выбрать у источника «Шум» или «Микрофон»,
менять положение источника и поворот слушателя. Лучше слушать в стереонаушниках
без дополнительной пространственной обработки ОС. Встроенный HRTF общий для всех:
различение спереди/сзади и высоты зависит от слушателя и сигнала.
## Нагрузка и ограничения
В логах spatial stats добавлены `hrtf`, `hrtf_pairs`, `hrtf_errors`; время тика
и пропуски остаются в `tick`, `max_tick`, `missed`. Вычислительная стоимость
зависит от количества слышимых направленных пар. Создание фильтра выполняется
на потоке микширования и может дать кратковременный пик при появлении новых пар.
Пределы участников и CPU для HRTF ещё не измерялись. Сборка Windows выполнена;
слуховая проверка пользователем и нагрузочные замеры остаются следующими шагами.
## Лицензии
SDK и лицензия: [Steam Audio](https://github.com/ValveSoftware/steam-audio/tree/v4.8.1).
При распространении бинарников сохранять
[лицензию SDK](third-party/steam-audio-LICENSE.md) и
[уведомления зависимостей и данных HRTF](third-party/steam-audio-THIRDPARTY.md).
Документация: [HRTF](https://valvesoftware.github.io/steam-audio/doc/capi/hrtf.html),
[binaural effect](https://valvesoftware.github.io/steam-audio/doc/capi/binaural-effect.html).
+122
View File
@@ -0,0 +1,122 @@
# Опциональное ослабление звука препятствиями
HRTF реализован отдельной опцией: [настройки](spatial-audio-hrtf.md). Этот проход добавляет
геометрическое ослабление к существующим stereo коэффициентам.
## Настройки
```yaml
room:
spatial_audio:
enabled: true
room_prefix: spatial-
occlusion:
enabled: true
max_objects: 64
```
В обычной конфигурации `occlusion.enabled` выключен. Локальный пример включает
возможность загрузки геометрии; учитывать её сервер начинает после принятия
сцены с `enabled: true`. Сцена с `enabled: false` отключает ослабление стенами,
сохраняя расстояние и панораму. Неверное обновление сохраняет предыдущую сцену.
## Передача из локации
Контроллер локации подключается к той же комнате с токеном `roomJoin`,
`canPublishData` и `roomAdmin`. Он может не публиковать микрофон и не подписываться
на аудио. Административный токен выдаёт доверенный backend; обычные участники
не должны иметь `roomAdmin`. Local token endpoint умеет выдавать такой токен
для отдельного скрытого контроллера HTML лаборатории; это только dev стенд.
Контроллер занимает один слот участника в текущем лимите комнаты.
При старте отправляется полный снимок объектов через **reliable DataChannel**,
topic `sverse.spatial.scene.v1`. Обновление можно отправить повторно при изменении
стен или после восстановления комнаты. Пакеты не рассылаются другим участникам.
```json
{
"version": 1,
"revision": 1,
"location_id": "location-01",
"enabled": true,
"objects": [
{
"id": "wall-1",
"center": [0, 2, 0],
"size": [12, 6],
"rotation": [0.7071067811865476, 0, 0, 0.7071067811865476],
"transmission": 0.2
}
]
}
```
- Центр — мировые координаты в **метрах**. В Unreal преобразовать cm → m.
- `size` — ровно два числа [ширина, высота] по локальным X/Y, в метрах.
Нормаль стены — локальная +Z; толщина отсутствует. Quaternion поворачивает
весь прямоугольник, поэтому возможны вертикальные, наклонные стены и перекрытия.
- `rotation` — нормализованный quaternion XYZW в той же системе координат,
что и pose. Единичный quaternion можно передать для объектов без поворота.
При identity rotation прямоугольник горизонтален в мировой XY. В примере
поворот +90° вокруг X ставит его вертикально в XZ, с центром Y=2 м.
- `transmission` — обязательный множитель амплитуды от 0 до 1. Это не dB:
`1` не ослабляет, `0.5` примерно −6 dB, `0.2` примерно −14 dB, `0` блокирует.
- `revision` — положительное целое меньше 2^53, строго больше предыдущей
принятой ревизии **в этой комнате**, даже при изменении `location_id`.
- `objects: []` очищает препятствия. Каждый `id` уникален в снимке.
- По умолчанию максимум 64 объекта; одновременно действует предел сообщения
**15000 байт**. Для большой локации потребуется другой протокол загрузки.
Сервер отвечает отправителю на `sverse.spatial.scene.ack.v1`:
```json
{"revision": 1, "ok": true}
```
При отказе ответ содержит `ok: false` и `error`; для ошибок до разбора сцены
ревизия может быть 0. Доставка пакета сама по себе не подтверждает применение:
контроллер должен дождаться этого ответа. Новая сцена начинает использоваться
на следующем аудиотакте. Она живёт до следующего обновления или закрытия комнаты;
отключение контроллера не удаляет стены. После пересоздания комнаты её нужно
загрузить снова. HTML контроллер повторяет загрузку принятой сцены при восстановлении.
## Расчёт
Для пары участников проверяется пересечение конечного отрезка между позициями
с каждой плоской прямоугольной стеной. Выходящие за радиус пары
не требуют проверки стен. Для пересечённых объектов:
```text
wallTransmission = product(object.transmission)
targetL = distanceAndPanL * wallTransmission
targetR = distanceAndPanR * wallTransmission
```
Два препятствия с коэффициентами 0.5 и 0.2 дают итоговый множитель 0.1.
Сначала находится пересечение отрезка с плоскостью, затем проверяются две
координаты попадания внутри прямоугольника. Одна стена учитывается один раз,
с обеих сторон одинаково. Пересечение края и конец отрезка на стене учитываются
при непараллельном отрезке. Параллельные отрезки, включая лежащие в плоскости,
не считаются пересечением. Проверка использует числовые допуски 1e-10 для
проекции направления на нормаль и 1e-8 м для границ прямоугольника.
Полная замена сцены инвалидирует матрицу; изменение поз обновляет нужные пары.
Аудиосэмплы используют готовые коэффициенты с обычным сглаживанием. Геометрия
не проверяется для каждого сэмпла. В первой версии перебор объектов линейный;
BVH/пространственная сетка для больших сцен пока отсутствует.
## HTML лаборатория
В разделе «Стены и препятствия» нажать «Пример стены», затем «Применить к комнате».
Пример располагает стену между центральным и правым актором стандартной тройки
и пропускает 20% амплитуды. Отключить флажок и повторно применить, чтобы сравнить.
JSON редактор позволяет задать несколько объектов, размеры, повороты и коэффициенты.
Карта показывает проекцию только подтверждённой сервером геометрии.
Добавлены поля диагностики `occlusion`, `obstacles`, `scene_revision`.
Это простая модель: толщина, материалы по частотам, обход края стены, отражения,
дифракция и реверберация пока не учитываются. Позиция pose пока служит одновременно
точкой источника и слушателя; отдельные mouth/ear offsets можно добавить позже.
Сборка не подтверждает корректность всех геометрических сценариев. Отдельная
проверка пересечений и прослушивание стен ещё требуются.
+205
View File
@@ -0,0 +1,205 @@
# План персонального пространственного аудио для Unreal Engine
Первый этап: участники в триггерной зоне подключаются к одной комнате LiveKit, публикуют микрофон и передают положение головы. Сервер формирует каждому слушателю собственную стереодорожку с голосами окружающих участников, учитывая расстояние и ориентацию головы. Собственный голос в микс не попадает.
Это проект реализации, а не описание готовой функции. Исходники изучены на коммите `44b791ad507d9814ee816f550df407b348d38b4b`. Предлагаемые численные настройки ниже — стартовые значения для экспериментов. Микшер должен работать как включаемый режим конкретной комнаты.
## Решение для первого этапа
На комнату создаём координатор `SpatialAudioRoom`. Он хранит участников, входящие аудиодорожки, последние позы и матрицу коэффициентов. Каждый входящий голос декодируется один раз в PCM, затем используется во всех миксах. Каждый получатель имеет собственный стереомикс и Opus encoder.
```text
Unreal: микрофон → Opus/RTP → очередь и jitter buffer источника
↓
Opus decoder источника
↓
mono PCM 48 kHz
↓
Unreal: поза → lossy data packet → матрица gainL/gainR
↓
PCM микс отдельно для каждого слушателя
↓
limiter → stereo Opus → выходная дорожка
↓
Unreal: стереовоспроизведение
```
Момент прихода пакета только добавляет данные в очередь. Сведение выполняется по общему аудиотаймеру комнаты. Это позволяет брать одинаковые по длительности блоки от источников, несмотря на разный размер пакетов и время их доставки.
На первом этапе пространственный эффект — ослабление и панорамирование между ушами. HRTF, различение переднего и заднего направления, отражения, стены и реверберация требуют дополнительной обработки. Простое стереопанорамирование их не моделирует.
## Передача положения и ориентации
Начальный транспорт — существующие LiveKit user data packets в режиме `LOSSY`, topic `sverse.spatial.pose.v1`. Для частых обновлений LiveKit предоставляет lossy доставку без гарантии порядка; topic позволяет выделить наши сообщения. Это описано в [официальной документации data packets](https://docs.livekit.io/transport/data/packets/).
В нашем форке такой пакет перехватывается в `Room.onDataMessage` и потребляется координатором комнаты до обычной рассылки. Положение не требуется пересылать каждому участнику: его использует серверный микшер. Другие topics обрабатываются штатно. Новый topic является договорённостью нашего форка; штатный LiveKit не создаёт для него отдельный обработчик.
Для прототипа достаточно компактного бинарного сообщения с фиксированным порядком байтов и версией:
| Поле | Назначение |
| --- | --- |
| version | Версия формата |
| sequence | Номер обновления в текущем подключении |
| clientTimeMs | Монотонное время клиента для диагностики |
| positionMeters x y z | Положение головы или точки излучения голоса |
| headRotation x y z w | Нормализованный quaternion ориентации головы |
| optional velocity x y z | Расширение для ограниченного предсказания движения |
Личность берём из объекта участника, переданного LiveKit обработчику, а не из payload. Сравнение sequence учитывает переполнение; после переподключения начинается новая сессия. Запоздалые пакеты отбрасываются. Сервер проверяет размер, версию, конечность чисел и корректность quaternion, а время приёма фиксирует своим монотонным таймером. Клиентское время нельзя напрямую сравнивать с серверным без синхронизации.
Передаём ориентацию камеры или головы, которую пользователь воспринимает как направление слуха. Направление корпуса может отличаться. Quaternion предпочтительнее одного вектора взгляда: он однозначно определяет правую сторону головы и при наклоне. В первом варианте используем одну точку для слушателя и источника голоса; отдельную позицию рта можно добавить позже.
В Unreal обычно используются сантиметры и оси X вперёд, Y вправо, Z вверх; соглашения по осям описаны в [документации Epic](https://dev.epicgames.com/documentation/en-us/unreal-engine/coordinate-system-and-spaces-in-unreal-engine). Протокол фиксируем в метрах с теми же осями: клиент переводит координаты в метры, а сервер получает правый вектор как поворот `(0, 1, 0)` quaternion головы. Проверяем это тестом «источник справа», чтобы исключить перестановку ушей. При world origin rebasing клиент должен передавать координаты в общем пространстве локации.
Начальная частота отправки — 50 мс. Отправляем периодически даже при неподвижности, чтобы подтверждать актуальность позы. При телепортации, входе в зону и начале публикации отправляем сразу. Если сообщений нет, сначала удерживаем последнюю позу, затем плавно выключаем звук участника; стартовый timeout 500 мс уточняем экспериментально. До первой валидной позы пространственные связи отключены.
Data tracks также доступны в этом checkout, но для первого прохода user packets дают простой договор по topic и уже существующую точку входа. Смена транспорта имеет смысл после измерения накладных расходов. HTTP и RPC для каждого обновления позы не нужны.
## Матрица ослабления и панорамирования
Строка матрицы — слушатель `i`, столбец — источник `j`. Ячейка содержит `enabled`, текущие `gainL/gainR` и целевые `targetL/targetR`. Диагональ отключена: `i == j`.
Расстояния симметричны, но стереокоэффициенты обычно различаются: участники смотрят в разные стороны. При перемещении участника обновляем его строку и столбец. При изменении только ориентации — его строку. Изменение конфигурации комнаты пересчитывает все пары.
Для пары вычисляем:
```text
delta = sourcePosition - listenerPosition
d = length(delta)
pan = clamp(dot(delta / d, listenerRight), -1, 1)
```
При почти нулевом расстоянии используем `pan = 0`, избегая деления на ноль. Близкий голос не должен бесконечно усиливаться.
Предлагаемая начальная кривая громкости с настройками `nearDistance` и `maxDistance`:
```text
t = clamp((d - nearDistance) / (maxDistance - nearDistance), 0, 1)
attenuation = 1 - (3*t*t - 2*t*t*t)
gainL = attenuation * sqrt((1 - pan) / 2)
gainR = attenuation * sqrt((1 + pan) / 2)
```
Требуем `0 <= nearDistance < maxDistance`. Это настраиваемая игровая кривая, а не утверждение о физическом распространении голоса. За пределами `maxDistance` целевые коэффициенты равны нулю. Полезная для первого теста настройка: полная громкость до 1 м, плавное ослабление до нуля на 20 м; расстояние слышимости затем выбирается по масштабу локации.
Маркер `INF` заменяем на `enabled=false` и нулевые целевые коэффициенты. Бесконечность не должна участвовать в умножении аудиосэмплов. После выхода из радиуса текущие коэффициенты доходят до нуля, и только тогда пару можно исключить из вычисления микса. При оптимизации списков соседей добавляем гистерезис, чтобы граница не вызывала частых переключений.
Переходы выполняем в аудиотракте: плавно меняем коэффициенты по сэмплам, например экспоненциально с начальной постоянной времени 30 мс. Новая цель заменяет предыдущую, не обнуляя текущее состояние. Поэтому пакет позы раз в 50 мс не создаёт ступеньку громкости раз в 50 мс. Чрезмерное сглаживание задерживает реакцию на движение и поворот головы — это отдельный измеряемый компромисс.
Для блока слушателя:
```text
mixL[n] = sum(sourcePCM[j][n] * gainL[i,j,n])
mixR[n] = sum(sourcePCM[j][n] * gainR[i,j,n])
```
Суммируем в float32 с запасом уровня и обрабатываем стереолимитером с общим управляющим коэффициентом каналов. Это сохраняет панораму и ограничивает пики при одновременной речи. Деление на меняющееся число участников даёт нежелательные скачки уровня; его не используем как автоматическую нормализацию.
## Аудиобуферы и кодеки
Для каждого опубликованного микрофона нужен собственный stateful Opus decoder. Декодируем mono 48 kHz; входное стерео для голоса приводим к согласованному mono представлению. Входящие пакеты сортируем по RTP timeline, удаляем дубликаты и обслуживаем потери по playout deadline. Существующее чтение `Buffer.ReadExtended` не принимаем автоматически за готовый jitter buffer для PCM микширования.
Opus требует последовательного декодирования пакетов одного потока; пропуски могут обрабатываться PLC. Это свойство [официального Opus decoder API](https://opus-codec.org/docs/opus_api-1.5/group__opus__decoder.html). RED, если он согласован, необходимо разобрать до подачи primary Opus в decoder. Учитываем in-band FEC, DTX, разный размер кадров и перезапуск RTP источника.
Первый прототип кодеков строим через небольшой собственный интерфейс к native libopus, с явной сборкой для целевого серверного Linux. Конкретный Go adapter выбираем после проверки encode/decode и сборки; это новая зависимость, её нет в текущем go.mod. Pure Go вариант рассматриваем только при подтверждённой поддержке обоих направлений и нужного качества.
Стартовые значения: PCM блок 10 мс, выходной Opus пакет 20 мс, начальный jitter buffer 40 мс с ограниченной адаптацией. При 48 kHz это 480 сэмплов в блоке на канал и 960 в выходном пакете. Входные RTP timestamps разных источников независимы: для каждого создаём отображение на серверный playout clock и корректируем drift. Размер сетевого пакета не задаёт размер блока микшера.
На каждом тике берём следующий блок всех источников, формируем миксы и передаём их в отдельные выходные encoder. Сетевые задержки получателя не должны блокировать весь таймер комнаты. Входные и выходные очереди ограничены; политика перегрузки сохраняет свежесть аудио, не накапливая бесконечную задержку. При пропуске encoder учитываем реальное прошедшее время в RTP timestamp.
Один decoder источника обслуживает все его пары, а один encoder обслуживает только одного получателя. Для первого этапа декодирование подключённого источника продолжается даже при отсутствии слышащих его соседей: простое отбрасывание Opus пакетов нарушает состояние decoder. Оптимизацию сна источников делаем отдельно.
Обычное шифрование WebRTC DTLS/SRTP совместимо с обработкой сервером. Для режима с клиентским E2EE микшер не имеет открытого аудио; первый этап требует аудиодорожек без такого E2EE. Режим комнаты проверяет это при подключении/публикации и сообщает несовместимость явно.
## Выдача персональной дорожки
Каждому слушателю выдаём одну постоянную stereo Opus дорожку `spatial_mix`. Когда меняются источники и расстояния, меняется её содержимое; пересоздавать дорожку при каждом движении не нужно. Для неё ведём собственные sequence, SSRC, RTP timestamp, RTCP Sender Reports и состояние повторной передачи, используя существующий SFU механизм там, где это применимо.
Важный первый технический проход — серверная синтетическая публикация. Предлагаемый вариант: внутренний логический publisher комнаты и отдельная `SpatialAudioPublication` с receiver для каждого слушателя. Публикация должна быть представлена через штатные TrackInfo и сигнальные сообщения, а подписка разрешена сервером только её получателю. Дальше можно использовать существующие SubscribedTrack/DownTrack/pacer/RTCP. В текущем коде такого publisher и PCM receiver нет; необходимо реализовать их жизненный цикл и проверить соответствие интерфейсам.
Один вызов `ParticipantImpl.AddTrackLocal` ещё не гарантирует, что SDK распознает дорожку: нужен корректный publisher ID, track ID, сведения о публикации и подписке. Точную реализацию виртуальной публикации фиксируем после первого сквозного теста. Если повторное использование DownTrack требует нарушения его модели источника, делаем отдельный sender с теми же требованиями к сигнализации, pacing и RTCP.
Сервер запрещает участнику подписываться на чужие персональные миксы. В пространственном режиме исходные микрофоны не отправляются слушателям параллельно с миксом; это обеспечивается политикой комнаты и subscription manager, включая ручные запросы подписки и reconnect. Иначе возникнут дублирующиеся голоса и обход радиуса слышимости. Video и другие разрешённые треки продолжают проходить по обычной политике комнаты.
Для выходной дорожки выставляем признак стерео и проверяем согласование Opus. В checkout уже есть `configureSenderAudio` в `pkg/rtc/transport.go`; он управляет `sprop-stereo`. В [RFC 7587](https://www.rfc-editor.org/rfc/rfc7587.html) различаются `stereo` получателя и `sprop-stereo` отправителя. Нужна сквозная проверка: левый тестовый сигнал должен оставаться слева после кодирования, передачи, декодирования SDK и воспроизведения Unreal.
В Unreal готовый микс воспроизводим как двухканальный звук слушателя без повторной пространственной обработки и downmix в mono. Профиль микрофона и выходного микса разделяем: микрофон может использовать echo cancellation и noise suppression, готовый микс должен сохранять стереопанораму. Проверка выбранного клиентского SDK и способа передачи PCM в Unreal Audio Mixer входит в первый проход. В изученном Source клиента готовая интеграция LiveKit не обнаружена.
## Жизненный цикл зоны
Предположение этапа: одна зона соответствует одной комнате; участник состоит в одной такой зоне одновременно. Пересекающиеся зоны и объединение нескольких комнат потребуют отдельных правил.
При входе получаем токен, подключаемся, передаём первую позу, создаём/получаем персональную дорожку и публикуем микрофон. До наличия позы голос не включается в пространственный микс. Время подключения измеряем отдельно: первый вход может задерживаться из-за сигнализации и ICE.
При выходе прекращаем передачу микрофона, сервер плавно выключает его из остальных миксов, останавливаем локальное воспроизведение и отключаемся. При колебании на границе зоны нужна небольшая задержка отключения транспорта или гистерезис триггера, при этом право передавать голос прекращается сразу по согласованному событию выхода. Если позже потребуется мгновенный вход, можно заранее подключать транспорт в более широкой зоне.
Room ID и доступ к зоне подтверждает игровой backend при выдаче токена. Клиентская поза достаточна для прототипа; при необходимости авторитетных координат позднее можно обновлять тот же PoseStore из игрового сервера. На первом этапе это не отдельный канал для аудио.
## Точки интеграции в текущем коде
| Файл и функция | Изменение |
| --- | --- |
| `pkg/rtc/room.go`, `Room.onDataMessage`, около строки 1292 | Потребление pose topic с привязкой к реальному участнику |
| `pkg/rtc/room.go`, `Room.onTrackPublished`, около строки 1076 | Регистрация микрофона в микшере и политика подписок |
| `pkg/rtc/room.go`, join/remove/close lifecycle | Создание и остановка координатора и персональных выходов |
| `pkg/rtc/mediatrack.go`, создание WebRTCReceiver около строки 408 | Подключение входящего аудио к очереди микшера |
| `pkg/sfu/receiver_base.go`, `ReceiverBase.forwardRTP`, строки 877, 929, 968 | Возможная точка захвата RTP до fanout; payload нужно копировать до повторного использования буфера |
| `pkg/rtc/mediatracksubscriptions.go`, `AddSubscriber`, около строки 94 | Штатное создание подписки на синтетическую выходную публикацию |
| `pkg/rtc/subscriptionmanager.go` | Ограничение доступа к исходным голосам и чужим миксам |
| `pkg/rtc/subscribedtrack.go`, `NewSubscribedTrack`, около строки 86 | Проверка совместимости synthetic receiver с DownTrack |
| `pkg/sfu/downtrack.go`, `WriteRTP`, около строки 1025 | Существующая отправка одного RTP источника; источник здесь должен быть уже готовым персональным миксом |
| `pkg/rtc/transport.go`, `configureSenderAudio`, около строки 3188 | Согласование стерео выхода |
DSP не выполняем под блокировкой Room и в сетевом callback. Callback складывает копию нужных данных в ограниченную очередь. Тяжёлые decode/mix/encode выполняются рабочими задачами с определённым владельцем состояния кодека. Аудиотакт читает подготовленный снимок поз и целей коэффициентов.
Новые компоненты: `pkg/spatialaudio` для pose protocol, матрицы, DSP, clock, очередей и codec adapter; адаптеры `SpatialAudioRoom`, `SpatialAudioPublication` и `SpatialOutputReceiver` — в rtc/sfu там, где нужны интерфейсы LiveKit. DSP пакет не должен зависеть от всей структуры ParticipantImpl, чтобы проверять его отдельно.
## Проходы реализации и критерии готовности
### Состояние реализации на 5 октября 2026
Добавлена вторая часть: опциональное ослабление ориентированными прямоугольными
плоскими стенами. Снимок сцены отправляет административный контроллер по reliable
DataChannel; каждое пересечение умножает stereo gain на коэффициент объекта.
HRTF реализован как опция отдельного прохода: [сборка и настройки](spatial-audio-hrtf.md). Подробности и ограничения:
[spatial-audio-occlusion.md](spatial-audio-occlusion.md).
Сквозной прототип для HTML клиента работает и подтверждён прослушиванием:
Opus вход → mono PCM → отдельный stereo микс → Opus → браузер. Реализованы
публикации `spatial_mix`, ограничения подписки, pose protocol, постоянная матрица
с обновлением строк/столбцов, сглаживание, limiter и ограниченные входные очереди.
Неподвижные heartbeat не пересчитывают пары. Добавлены показатели времени аудиотакта.
Повторное открытие комнаты использует уже загруженную библиотеку Opus.
Проходы 1–4 реализованы для браузерного прототипа; Unreal ещё не подключён.
Проход 5 требует проверки сценариев восстановления; проход 6 остаётся впереди.
В следующем проходе добавлены автоматическое переподключение HTML клиента с
обновлением токена, очистка аудиоресурсов после разрыва и переключение источника
без выхода из комнаты. На сервере удаление источника включает короткий PLC хвост
с затуханием; поздние callbacks удалённого участника игнорируются. Для длинных
сессий обработано переполнение RTP timestamp. Изменения требуют проверки
сценариев разрыва и смены источника; нагрузочные испытания ещё не проводились.
Пределы нагрузки и качество при потерях пока не измерены. Инструкция запуска
и текущие ограничения: [spatial-audio-development.md](spatial-audio-development.md).
1. **Сквозная стереодорожка.** Флаг комнаты, synthetic publication, ограничение подписки, сигнал только в левом/правом канале, согласование stereo и воспроизведение в выбранном Unreal SDK. Проверить reconnect и отсутствие доступа к чужому миксу. Зафиксировать механизм публикации и сборку libopus. Этот проход снимает главный риск интеграции до разработки полноценного микшера.
2. **Pose protocol и матрица.** Передача из Unreal каждые 50 мс, приём сервером, latest state, расчёт расстояний/панорамы, сглаживание, нулевая диагональ. Детерминированные проверки справа/слева, одинаковых координат, невалидных и устаревших пакетов, teleport, timeout и границы радиуса.
3. **Один входящий голос.** RTP queue, jitter buffer, decoder, общий PCM clock, потери/PLC, Opus/RED/DTX и выходной encoder. Проверить, что UDP/RTP jitter не превращается в скачки длительности блоков и очередь не растёт без ограничения.
4. **Несколько голосов и персональные миксы.** Общие PCM источники, отдельные цели gain и encoder на получателя, limiter. Сценарий трёх участников с разными ориентациями: каждый получает собственную панораму, не слышит себя, дальний участник исключён.
5. **Зона и восстановление.** Вход/выход, прекращение публикации, reconnect, смена микрофона, истечение позы и закрытие комнаты. Удалённый источник и участник должны освобождать decoder/encoder, очереди и матрицу. Активные worker не остаются после закрытия.
6. **Подбор частот и нагрузка.** Испытания интервалов позы 25/50/75/100/150 мс при одинаковом аудиотракте; подобрать максимально редкие обновления с приемлемой реакцией и без слышимых ступенек. Проверять отдельно быстрое вращение головы, бег, проход вблизи источника и телепортацию. Затем испытания с packet loss и задержками, измерение ресурсов при 4/8/16/32 участниках.
Готовность первого этапа означает подтверждённую передачу уникального stereo микса каждому клиенту, плавное движение/вращение, отсутствие своего голоса и дублей, устойчивое восстановление после потерь и reconnect, а также измеренный предел нагрузки на выбранном сервере. Число участников, допустимая задержка и критерий субъективного качества утверждаются по результатам прототипа, а не предполагаются заранее.
## Измерения и дальнейшее масштабирование
Для испытаний записываем интервалы фактического приёма позы, возраст позы, цели и сглаженные gain, входной jitter, PLC/FEC, задержку очередей, время decode/mix/encode и пропуски deadline. Измеряем задержку «микрофон → ухо» и отдельно реакцию на поворот головы. Метрики строим без label для каждой пары участников; подробную матрицу выводим только в диагностике выбранной комнаты.
Полная матрица и микширование всех пар имеют квадратичную стоимость; декодирование и число encoder растут линейно с числом участников. Первую реализацию делаем с ограниченным размером комнаты, чтобы получить профиль. Затем добавляем пространственную сетку и списки слышимых соседей: для `K` соседей на слушателя DSP работает примерно по `N*K`, сохраняя плавное выключение пар.
20 обновлений позы в секунду создают для каждого движущегося участника работу по его строке и столбцу, а не пересчёт всех `N*N` ячеек. При повороте пересчитывается только строка слушателя. Неподвижные позы можно обновлять как heartbeat без повторного расчёта одинаковых целей.
Первый этап предполагает обработку комнаты на одном узле. Миграция, распределённые комнаты, перенос состояния decoder/encoder и репликация PoseStore — отдельный этап; режим должен явно отвергать неподдерживаемую конфигурацию. Дальность слышимости не позволяет просто останавливать все декодеры: непрерывность кодеков и прогрев после возобновления требуют отдельного решения.
При достаточном качестве первой версии следующим шагом может стать HRTF на сервере или клиентская обработка отдельных голосов. Последний вариант сохраняет клиенту информацию об источниках и уменьшает серверное перекодирование, но меняет выбранную модель единственного персонального микса. Для текущего этапа придерживаемся серверного микширования.
+97
View File
@@ -0,0 +1,97 @@
# Интеграция пространственного LiveKit в метавселенную
Статус на 5 октября 2026: документация текущего форка и проект недостающего
управления нодой. Примеры API метавселенной и API управления нодой, помеченные
«проект», ещё не реализованы в LiveKit. Существующий протокол описан по коду
`pkg/rtc/spatialaudio.go` и `pkg/spatialaudio`.
## Документы по ролям
- [Клиент HTML / Unreal Engine](client.md): вход в зону, получение доступа,
публикация голоса, позы, приём персонального микса и переподключение.
- [Бэкенд и сервер локации](backend.md): развёртывание, комнаты, токены,
передача геометрии и жизненный цикл.
- [Админка и управление нодой](admin.md): действующие переключатели,
принудительные запреты, приоритеты политик и проект управляющего API.
- [Протокол spatial v1](protocol.md): бинарная поза, JSON-сцена, ACK и ограничения.
## Рекомендуемая схема первого развёртывания
Единица запуска — **экземпляр локации**. Бэкенд создаёт сервер локации и отдельный
контейнер нашего LiveKit. В контейнере могут жить несколько комнат этой локации.
Для одной общей акустической зоны достаточно одной комнаты. Комнаты изолированы:
между участниками разных комнат микс не рассчитывается. Стена, этаж или дистанция
внутри общей зоны моделируются координатами и препятствиями в одной комнате.
```mermaid
sequenceDiagram
participant B as Бэкенд метавселенной
participant L as Сервер локации
participant K as LiveKit контейнер
participant C as Клиент
participant A as Админка
B->>K: Запуск с профилем звука и ключами
B->>K: RoomService.CreateRoom
B->>L: room, URL, доступ контроллера, стены
L->>K: WebRTC контроллер, RoomAdmin
L->>K: Reliable scene v1
K-->>L: Scene ACK
L->>B: Аудиосцена готова
C->>L: Вход в голосовую зону
L->>B: Запрос доступа игрока
B-->>L: URL и JWT на конкретную комнату
L-->>C: Параметры подключения
C->>K: WebRTC голос и lossy позы
K-->>C: Персональный stereo spatial_mix
A->>B: Изменить политику ноды
B->>L: Сейчас: обновить полные сцены комнат
L->>K: Reliable scene, новые флаги
K-->>L: ACK
Note over B,K: Жёсткий runtime-запрет на всей ноде требует нового API
```
Клиенту сообщается публичный `wss://` URL сигналинга и JWT. Адрес внутренней
Docker-сети передаётся только серверным компонентам. WebRTC-медиа соединяется
с LiveKit по ICE-кандидатам; прокси WebSocket сам по себе не обеспечивает
доступность UDP/TCP-медиа.
## Контейнер или отдельная комната
| Вариант | Когда выбирать | Следствия |
|---|---|---|
| Один контейнер на экземпляр локации, несколько комнат | Первый этап, независимый запуск/остановка локаций | Простая привязка ноды и политики; расход памяти и запуск SDK на каждый контейнер |
| Один контейнер на каждую комнату | Нужна строгая изоляция ресурса или разные серверные профили | Больше контейнеров и портов; отдельные ключи и маршруты |
| Пул нод, много локаций/комнат на ноде | После замеров плотности и подготовки управления нодами | Лучше утилизация; общая нагрузка и область действия запрета функций |
Отдельный контейнер на каждую комнату не является требованием LiveKit. В этом
форке у каждой spatial-комнаты свой движок, сцена и миксы; базовая конфигурация
берётся с ноды. Для запуска локаций с разными расстояниями, битрейтом или лимитами
пока нужны разные профили нод. Scene v1 меняет флаги функций, но не эти значения.
В распределённом LiveKit Redis обеспечивает маршрутизацию, одна комната
обслуживается одной нодой. URL сигналинга кластера может вести на другую ноду,
поэтому адрес URL нельзя использовать как идентификатор владельца комнаты.
Это описано в [официальной архитектуре](https://docs.livekit.io/transport/self-hosting/distributed/).
Для текущего форка распределённая работа spatial-миксов не проверялась:
первый этап разворачивать без общего Redis между независимо управляемыми нодами.
## Что существует и что требуется
| Возможность | Статус |
|---|---|
| Spatial-режим по серверному enabled и префиксу комнаты | Реализовано |
| Координаты игрока и персональный стереомикс | Реализовано |
| Полная сцена стен по reliable DataChannel от RoomAdmin | Реализовано |
| Переключение HRTF, occlusion и adaptive в отдельной комнате | Реализовано в пределах серверных разрешений |
| Приоритеты стен и автоматическая деградация | Реализовано |
| Профиль локации из БД → YAML запуска | Задача бэкенда; формат профиля предложен здесь |
| REST API чтения spatial-сцены/метрик | Отсутствует; сейчас ACK и логи |
| Жёсткая политика ноды без рестарта для всех текущих и будущих комнат | Отсутствует; [проект API](admin.md) |
| Изменение расстояний/битрейта на работающей комнате | Отсутствует |
| Docker-пакет с HRTF | [Подготовлены образ и Compose](../../deploy/spatial/README.md); сборка/запуск образа на Docker-хосте ещё не проверены; корневой Alpine Dockerfile не подходит для Steam Audio |
| Голосовой E2EE при серверном микшировании | Не поддерживается текущим обработчиком |
Технические детали: [HRTF](../spatial-audio-hrtf.md),
[препятствия](../spatial-audio-occlusion.md),
[деградация](../spatial-audio-adaptive.md),
[локальная лаборатория](../spatial-audio-development.md).
+176
View File
@@ -0,0 +1,176 @@
# Админка: управление звуком на конкретной ноде
[Обзор](README.md) · [Бэкенд](backend.md) · [Протокол](protocol.md)
## Доступные механизмы
| Действие | Механизм | Область действия |
|---|---|---|
| Отключить HRTF | Полная scene v1 с hrtf=false | Одна комната; другой RoomAdmin может включить обратно |
| Отключить стены | Полная scene v1 с enabled=false | Одна комната; объекты можно сохранить |
| Отключить адаптацию | Полная scene v1 с adaptive=false | Одна комната; деградация сбрасывается |
| Изменить приоритеты стен | Полная сцена с priority | Одна комната |
| Запретить функцию конфигурацией | YAML и restart | Все комнаты процесса после перезапуска |
| Изменить distances, bitrate, лимиты, пороги | YAML и restart | Сейчас нет runtime API |
| Жёстко запретить опцию на всей живой ноде | Интерфейс отсутствует | Требуется новый API и слой политики в движке |
Редактирование файла внутри работающего контейнера не обновляет движки:
hot reload spatial-конфигурации не реализован. Docker exec сам по себе не является
API управления звуком. Админка обращается к бэкенду, который хранит решение
и применяет его к выбранному deployment. API secrets и права оркестратора
остаются на серверной стороне.
**Общий spatial_audio.enabled=false не означает тишину:** новые комнаты становятся
обычными SFU-комнатами с доставкой исходного аудио. Для сохранения персональных
миксов оставить spatial=true и отключать отдельные эффекты. Полная остановка
голоса требует закрытия допуска/публикаций/комнат через бэкенд.
## Путь управления существующим кодом
1. Администратор выбирает deployment_id. Бэкенд сохраняет запреты в БД с ревизией
и аудитом, находит все комнаты этого deployment.
2. Единый writer каждой локации получает ограничения, объединяет их с полной
desired-сценой, выделяет новую room revision и отправляет снимок контроллером.
3. По каждой комнате ожидается ACK. Админка показывает applied/pending/failed;
отсутствие ответа не является подтверждением изменения всей ноды.
4. Новые комнаты получают сохранённую политику до выдачи доступа игрокам.
Пример scene v1 для запрета HRTF при сохранении стены:
```json
{
"version": 1,
"revision": 102,
"location_id": "loc-courtyard-session-7",
"enabled": true,
"hrtf": false,
"adaptive": true,
"objects": [
{"id":"wall-east","center":[0,2,0],"size":[12,6],"rotation":[0.7071067811865476,0,0,0.7071067811865476],"transmission":0.2,"priority":100}
]
}
```
Это согласованное управление через доверенный бэкенд, **не жёсткий запрет внутри
LiveKit**. Допущенный RoomAdmin может прислать более новую сцену с hrtf=true,
если функция разрешена YAML. Такое состояние не называть enforced. Жёсткий запрет
с текущим кодом требует сохранения запрета в YAML и согласованного restart,
повторной отправки сцен и восстановления клиентов. При YAML occlusion.enabled=false
из сцен исключить все objects и enabled=true, иначе отклонится весь снимок.
## Целевой порядок политик — проект
```text
effective = capability_allowed_by_node_config
AND location_room_requested
AND NOT node_force_disabled
AND allowed_at_current_adaptive_level
```
Для adaptive первые три условия определяют работу контроллера качества. Его
отключение восстанавливает только функции, разрешённые остальными условиями.
Принудительный запрет не удаляет профиль локации и стены: снятие запрета
возвращает желаемое состояние с учётом нагрузки. Runtime-политика может ужесточить
YAML, но не загрузить отсутствующий HRTF и не повысить конфигурационные лимиты.
У политики deployment, сцены комнаты и временного качества разные состояния
и ревизии. Требуется реализовать их приоритет внутри LiveKit, чтобы повторная
сцена контроллера и восстановление после перегрузки не обходили запрет админки.
## Внутренний API ноды — НЕ РЕАЛИЗОВАН
Предлагается отдельный управляющий listener, доступный бэкенду по mTLS/сервисной
авторизации. Чтение требует проектного права spatial.node.read, запись —
spatial.node.write; это не текущие grants JWT LiveKit. RoomAdmin не разрешает
изменение политики ноды. Бэкенд маршрутизирует запрос в процесс-владелец
deployment; публичный балансировщик LiveKit не гарантирует выбор нужной ноды.
### GET /internal/spatial/v1/node
Предлагаемый ответ:
```json
{
"deployment_id": "audio-node-17",
"generation": 3,
"livekit_node_id": "ND_example",
"policy_revision": 8,
"capabilities": {"hrtf":true,"occlusion":true,"adaptive":true},
"force_disabled": {"hrtf":true,"occlusion":false,"adaptive":false},
"rooms": [
{
"name": "spatial-courtyard-session-7-main",
"scene_revision": 102,
"requested": {"hrtf":true,"occlusion":true,"adaptive":true},
"effective": {"hrtf":"off","occlusion":true,"adaptive":true},
"quality_level": 0,
"active_obstacles": 1,
"load_pressure": 0.18,
"applied_policy_revision": 8
}
]
}
```
### PUT /internal/spatial/v1/node/policy
Полная замена административной политики:
```json
{
"deployment_id": "audio-node-17",
"generation": 3,
"expected_policy_revision": 8,
"request_id": "49efa360-e892-4b80-9572-8465c60f4200",
"force_disabled": {"hrtf":true,"occlusion":false,"adaptive":false},
"reason": "Снижение вычислительной нагрузки"
}
```
Требования к реализации:
- Проверить deployment/generation и expected revision; при несовпадении 409.
Исключить применение старого запроса к новому поколению контейнера.
- Повтор request_id с тем же телом возвращает исходный результат; с другим — 409.
Новая policy_revision выделяется нодой; срок хранения request_id ограничен.
Durable desired-policy и аудит хранятся в бэкенде.
- Опубликовать маску запретов до допуска новых комнат, передать команды всем
живым движкам. Проверять маску при каждой новой сцене и изменении качества.
- HTTP 200 возвращать после подтверждения текущих движков с applied_revision.
При таймауте вернуть pending и operation_id; предусмотреть
GET `/internal/spatial/v1/operations/{operation_id}` для проверки завершения.
Ошибки авторизации — 401/403, неверные значения — 400, отсутствие нужного
deployment — 404. Ответы не должны раскрывать секреты.
- Для каждой комнаты хранить applied_policy_revision. Применение запрета HRTF
предшествует завершению плавного затухания фильтров. Одновременное изменение
слышимого звука во всех комнатах не гарантируется.
- При запуске не выдавать admission-ready до восстановления сохранённой политики.
При ошибке восстановления допуск новых игроков закрыт.
Будущий room API может читать сцену и менять requested-флаги. Node API не
подменяет геометрию и не переписывает room revision. Изменение distances/bitrate
и качества фильтра сверх nearest/bilinear/off требует отдельного контракта.
## Представление в админке
Карточка deployment: поколение, образ/digest, LiveKit node_id, связанные комнаты,
допустимые функции, force-disabled, desired/applied ревизии, причина/автор запрета
и ошибки применения. Карточка комнаты: requested и effective-флаги, quality_level,
период геометрии, число активных/всех стен, load_pressure и ошибки аудиотиков.
Запрет админки и временное отключение HRTF адаптацией показывать отдельно.
До реализации нового API данные берутся из БД и spatial-логов:
hrtf, effective_hrtf, adaptive, quality_level, pose_interval, active_obstacles,
obstacles, load_pressure, quality_transitions, missed, decode_errors,
output_errors, hrtf_errors. Spatial JSON endpoint и отдельные Prometheus-метрики
пока отсутствуют. Load pressure характеризует spatial-бюджет, не общий CPU.
## Следующие этапы реализации
1. Production glibc-образ с HRTF и библиотеками, измерение ресурса.
2. Реестр deployment/комнат, профили, JWT и единый writer сцен в бэкенде.
3. Node policy store, protected API, применение запретов к живым и новым движкам
и чтение эффективного состояния в LiveKit.
4. Карточки, force-disable, подтверждение результата и аудит в админке.
Эти endpoints и слой hard policy в рамках документации не добавлялись.
+175
View File
@@ -0,0 +1,175 @@
# Бэкенд метавселенной и сервер локации
[Обзор](README.md) · [Протокол сцены и поз](protocol.md) · [Админка](admin.md)
## Владение состоянием
| Компонент | Ответственность |
|---|---|
| Бэкенд | Профиль локации, размещение контейнера, ключи/JWT, назначение комнаты, desired-состояние, ревизии и административные ограничения |
| Сервер локации | Геометрия зоны, контроль членства игроков, WebRTC-контроллер сцены, отправка полных снимков и ожидание ACK |
| LiveKit | Авторизация участников, транспорт, хранение принятой сцены в памяти, микширование и адаптация |
| Оркестратор | Запуск/остановка контейнера, сеть, ресурсные лимиты и версии образа |
Бэкенд хранит `deployment_id` (идентификатор развёртывания оркестратора), поколение
запуска, location_instance_id, zone_id → room, публичный signaling URL, внутренний
API URL, ссылки на секреты, профиль и последнюю desired-сцену. Не путать
deployment_id с внутренним LiveKit node_id: node_id относится к текущему процессу
и при новом запуске может измениться.
## Профиль запуска локации — проект схемы БД
```json
{
"profile_id": "courtyard-audio-v1",
"spatial_enabled": true,
"hrtf_requested": true,
"occlusion_requested": true,
"adaptive_requested": true,
"near_distance_m": 1,
"max_distance_m": 20,
"max_players": 31,
"pose_timeout_ms": 500,
"pose_interval_ms": 50,
"opus_bitrate": 64000,
"hrtf_interpolation": "bilinear"
}
```
Это не JSON, который можно отправить в LiveKit. Бэкенд преобразует базовый профиль
в YAML `room.spatial_audio`, а requested-флаги — в scene v1. Предпочтительно
разделять разрешённые возможности образа/ноды и желаемое состояние локации:
например, hrtf.enabled=true в YAML разрешает функцию, а scene.hrtf=false отключает
её для конкретной комнаты. Движок кратковременно стартует с YAML-флагами, поэтому
клиентские подключения открывать только после scene ACK.
Параметры distances, bitrate, smoothing, лимиты и adaptive-пороги сейчас общие
для комнат ноды. `CreateRoom.metadata` или metadata участника сами по себе
не меняют spatial-конфигурацию. Требуется настройка запуска или будущий room API.
## Развёртывание контейнера
Использовать образ **нашего форка** с нужной версией протокола. Обычный
`livekit/livekit-server` не содержит персонального микшера и обработчиков сцен.
Подключить YAML через read-only mount, хранить реальные API secrets в защищённой
конфигурации. Образ фиксировать по digest. Ключи лаборатории не использовать.
Пример spatial-части YAML для Linux с установленным HRTF-адаптером:
```yaml
room:
spatial_audio:
enabled: true
room_prefix: spatial-
max_participants: 32
near_distance: 1
max_distance: 20
smoothing_ms: 30
pose_timeout_ms: 500
jitter_ms: 40
bitrate: 64000
library: libopus.so.0
debug_stats: true
hrtf:
enabled: true
interpolation: bilinear
library: /opt/sverse/hrtf/libsverse_hrtf.so
occlusion:
enabled: true
max_objects: 64
adaptive:
enabled: true
pose_interval_ms: 50
overload_ratio: 0.7
recovery_ratio: 0.4
degrade_after_ms: 2000
recover_after_ms: 10000
cooldown_ms: 3000
```
Пути относятся к файловой системе контейнера. Для HRTF нужен Linux x64 с glibc,
собранный `native/hrtf`, `libphonon.so` рядом с адаптером, libopus и лицензии SDK.
Текущий корневой Dockerfile использует Alpine и поддерживает вариант с Opus
без Steam Audio. Отдельный [Dockerfile и Compose с HRTF](../../deploy/spatial/README.md)
подготовлены на Debian/glibc. HRTF Linux/Docker ещё не проверялся запуском:
до production-развёртывания требуется собрать образ на Docker-хосте.
Снаружи нужны TLS-сигналинг и доступные ICE-адреса: типично 443 → 7880,
UDP mux 7882 и fallback TCP 7881, либо настроенный UDP-диапазон. Настроить
advertised IP, NAT и TURN для выбранной инфраструктуры. При нескольких контейнерах
на одном хосте исключить конфликты медиапортов и проверить соответствие объявленных
кандидатов пробросу портов. Local sample с bind 127.0.0.1 в production не переносить.
См. [порты LiveKit](https://docs.livekit.io/transport/self-hosting/ports-firewall/).
## Запуск экземпляра локации
1. Бэкенд выделяет deployment и room имена с префиксом `spatial-`. Если общий
spatial enabled выключен или имя не соответствует префиксу, комната будет
обычной SFU-комнатой, без нашего персонального микса.
2. Запускает контейнер, проверяет доступность штатного RoomService API. Отдельно
ожидает готовности серверного spatial-движка: успешный старт процесса ещё
не доказывает загрузку Opus/HRTF, она происходит при создании spatial-комнаты.
3. Создаёт комнаты через стандартный `RoomService.CreateRoom`; настраивает
время жизни пустой комнаты и учёт служебных участников.
4. Передаёт серверу локации геометрию и room-specific JWT контроллера. Он
подключается к каждой комнате через **WebRTC SDK**, даже если не передаёт голос.
5. Контроллер отправляет полный snapshot, получает ACK. Лишь после этого бэкенд
открывает выдачу доступа игрокам.
6. При вступлении игрока бэкенд проверяет членство и формирует player JWT; сервер
локации возвращает публичные URL, token и параметры позы из [контракта клиента](client.md).
Идентичный scene snapshot может отправляться разным комнатам, но ревизия и ACK
учитываются по каждой отдельно. Максимум участников 32 включает контроллера:
при одном постоянно подключённом контроллере максимум игроков — 31. Служебный
участник с hidden=true всё равно занимает слот. Постоянный контроллер также
удерживает комнату непустой; закрытие локации должно явно отключать его.
## Токены
JWT подписывает доверенный сервис бэкенда. Сервер локации может получать короткие
JWT без API secret; для длительной жизни контроллера предусмотреть обновление
или повторную выдачу доступа. Конкретное TTL задаёт политика бэкенда.
| Grant | Игрок | Контроллер сцены |
|---|---|---|
| roomJoin | true | true |
| room | Только назначенная комната | Только управляемая комната |
| canPublish | true, по возможности ограничить источником Microphone | false |
| canSubscribe | true | false |
| canPublishData | true | true |
| roomAdmin | false | true |
| hidden | false | true |
RoomAdmin — широкое стандартное право комнаты, не отдельное право «редактор стен».
Контроллер — доверенный серверный компонент. Нельзя выдавать его JWT браузеру
обычного пользователя или использовать laboratory token endpoint.
Стандартный [RoomService](https://docs.livekit.io/reference/other/roomservice-api/)
доступен через POST `/twirp/livekit.RoomService/<MethodName>` и server SDK.
CreateRoom/ListRooms/DeleteRoom и управление участниками остаются штатными.
Для scene v1 требуется WebRTC-участник; SendData рассылает обычные topics,
но spatial.scene topic перехватывается и игнорируется без участника-отправителя.
Тело JWT/grants для управляющих server API отличается от roomJoin JWT; использовать
серверный SDK для подписи нужных полномочий.
## Изменение стен, опций и восстановление
Контроллер получает новую геометрию/политику через доверенный канал бэкенда.
Все писатели используют одного координатора, который объединяет полную сцену
с административными ограничениями, выделяет ревизию и отправляет снимок.
Не создавать независимого второго writer из админки: ревизии и флаги будут
конкурировать. Время Date.now не является надёжным координатором ревизий между
серверами; использовать возрастающий счётчик в транзакции/одном writer.
Состояния запуска: provisioning → scene_pending → ready → draining → stopped;
ошибка загрузки библиотеки/сцены переводит аудио в failed, а не в ready.
При ACK-timeout использовать правила [протокола](protocol.md). При полном
перезапуске LiveKit снова отправить сцены, затем обновить клиентский доступ.
Текущий контроллер и desired-состояние должны переживать сбой отдельного контейнера.
При остановке локации прекратить новые JWT, уведомить клиентов о выходе из зоны,
отключить контроллеры, удалить комнаты RoomService.DeleteRoom и завершить контейнер.
В пуле удалять комнаты локации, сохраняя ноду с другими комнатами. Для планового
вывода ноды учитывать штатное draining LiveKit; принудительный restart прерывает
активные сессии. Self-hosted JWT нельзя считать мгновенно отозванным одной
записью в БД: прекращение доступа требует управления участником и повторной выдачей.
+124
View File
@@ -0,0 +1,124 @@
# Контракт клиента: HTML и Unreal Engine
[Обзор](README.md) · [Точный протокол](protocol.md)
## Доступ к комнате
При входе в голосовую зону клиент запрашивает доступ через авторизованное
соединение с сервером локации. Сервер локации получает JWT у бэкенда и возвращает
подключение. Клиент не выбирает произвольный room или identity и не получает
API secret. Бэкенд проверяет, что игрок допущен в эту локацию и зону.
Предлагаемый ответ сервера локации — **контракт метавселенной, ещё не API LiveKit**:
```json
{
"audio": {
"enabled": true,
"deployment_id": "audio-node-17",
"deployment_generation": 3,
"location_instance_id": "loc-courtyard-session-7",
"zone_id": "main",
"room": "spatial-courtyard-session-7-main",
"url": "wss://audio.example.org",
"token": "<participant JWT>",
"token_expires_at": "2026-10-05T15:15:00Z",
"protocol_version": 1,
"pose_interval_ms": 50,
"pose_timeout_ms": 500
}
}
```
`audio.enabled=false` означает не подключать WebRTC. deployment_generation
позволяет отличить новое развёртывание от старого при задержанных ответах.
Публичный URL доступен игроку; localhost применим только к лаборатории.
Токен имеет roomJoin, canPublish, canSubscribe и canPublishData, привязан к room
и identity игрока. RoomAdmin игроку не выдаётся. TTL JWT относится к допуску при
подключении и не заменяет отдельную команду удаления участника.
См. [официальные grants](https://docs.livekit.io/frontends/reference/tokens-grants/).
## Последовательность подключения
1. Получить актуальные параметры и подключить LiveKit SDK по URL/JWT.
2. После Connected сразу отправить позу, затем heartbeat примерно каждые 50 мс.
3. Опубликовать **один моно аудиотрек с source=Microphone**, Opus. Это относится
и к процедурно сгенерированному звуку. Поддержка нескольких голосовых входов
одного участника не предусмотрена: новый вход заменяет предыдущий.
4. Подписываться на доступную аудиопубликацию с именем `spatial_mix` и воспроизводить
её как обычный стереосигнал. Сервер выдаёт каждому свой трек и запрещает
подписку на чужой микс и исходные аудиотреки пространственной комнаты.
5. При выходе из зоны остановить публикацию и heartbeat, отключиться, освободить
аудиотреки. При смене комнаты завершить старую сессию и запросить новый доступ.
Персональный микс не включает собственный голос. В нём уже учтены расстояние,
поворот головы, стены и доступный HRTF. В UE не помещать этот стереовыход снова
в пространственный AudioComponent с HRTF/расстоянием: воспроизводить как 2D stereo.
Локальный регулятор громкости допускается. Список синтетических участников
`__spatial_...` не использовать как игровой roster; он служит выдаче микса.
SID трека и ParticipantID могут измениться при новом подключении: не хранить их
как постоянные идентификаторы игрока.
В браузере нужен HTTPS вне loopback для микрофона; начало воспроизведения может
потребовать действие пользователя. Использовать attach аудиотрека к audio-элементу
или полноценный аудиовыход SDK. Клиент должен корректно обрабатывать mute/unmute,
TrackSubscribed/TrackUnsubscribed и восстановление подписки.
E2EE входного аудиотрека текущим серверным микшером не поддерживается: сервер
должен иметь возможность декодировать звук. Это не отменяет WebRTC транспортное
шифрование. Видеотреки находятся вне контракта пространственного аудио.
## Поза и координаты
Получить локальные координаты в едином пространстве локации: UE centimeters / 100
→ metres; X вперёд, Y вправо, Z вверх. Отправлять quaternion XYZW головы/камеры.
Не использовать экранный yaw или преобразованные координаты карты HTML.
Одинаковый origin необходим для стен и участников, включая World Origin Rebasing:
переводить в согласованную локальную систему до сериализации.
Пример кодирования для браузера, протокол полностью совпадает с UE:
```js
function encodePose(sequence, position, rotation) {
const bytes = new Uint8Array(44);
const view = new DataView(bytes.buffer);
view.setUint8(0, 1);
view.setUint32(4, sequence >>> 0, true);
view.setFloat64(8, performance.now(), true);
position.forEach((value, i) => view.setFloat32(16 + 4*i, value, true));
rotation.forEach((value, i) => view.setFloat32(28 + 4*i, value, true));
return bytes;
}
await room.localParticipant.publishData(
encodePose(++sequence, [x, y, z], [qx, qy, qz, qw]),
{ reliable: false, topic: "sverse.spatial.pose.v1" }
);
```
При незавершённой отправке хранить последнюю позу, не накапливать очередь старых
пакетов. Heartbeat нужен даже без движения: после 500 мс без принятой позы голос
затухает. Клиент получает координаты персонажа из игровой системы, но передаёт
позу в LiveKit сам; пересылка поз всех игроков сервером локации пока отсутствует.
## Восстановление и ошибки
- Во время SDK Reconnecting приостановить новые pose-send, сохранить выбранный
микрофон и пользовательское mute. После Reconnected отправить свежую позу,
проверить публикацию и восстановить вывод микса.
- При окончательном Disconnected запросить новый доступ через сервер локации,
выполнить backoff с ограничением и не пытаться войти в уже завершённую локацию.
- Sequence сохранять в живой сессии. Сбрасывать его можно при создании нового
участника, а не просто при возобновлении транспорта той же сессии.
- Отказ доступа/лимит участников/ошибка spatial initialization отображаются как
недоступность голосового подключения; игровой клиент остаётся подключён к локации.
- Отсутствие слышимого голоса само по себе нормально: нет соседей, позы устарели,
источник за пределом дистанции, стены блокируют или источники muted.
Не отправлять scene v1 от игрока и не показывать состояние HRTF как гарантированно
активное на основании галочки профиля: адаптация может временно снизить качество.
Текущий эффективный уровень сейчас доступен в серверных логах; клиентского события
с эффективным quality_level пока нет.
Рабочий пример транспорта: `cmd/spatial-test/web/app.js`. Локальный `/token`
из лаборатории не является production-сервисом авторизации.
+154
View File
@@ -0,0 +1,154 @@
# Протокол spatial v1: реализованный контракт
## Участники и каналы
| Назначение | Транспорт / topic | Отправитель | Ответ |
|---|---|---|---|
| Голос | WebRTC audio, Opus, Microphone | Игрок | `spatial_mix` в WebRTC |
| Поза | lossy DataChannel, `sverse.spatial.pose.v1` | Игрок | Нет |
| Стены и флаги | reliable DataChannel, `sverse.spatial.scene.v1` | Контроллер с RoomAdmin | `sverse.spatial.scene.ack.v1` |
Spatial-топики перехватываются сервером и не рассылаются как обычные данные
игрокам. Их обработчик действует только в spatial-комнате. `RoomService.SendData`
не заменяет подключение контроллера: у такого пакета source=nil, поэтому обработчик
scene перехватывает topic, но не применяет сцену и не выдаёт ACK. Остальные
обычные topics могут рассылаться штатным API. Новый HTTP spatial API отсутствует.
## Поза: ровно 44 байта
Little endian, без JSON и без выравнивания полей:
| Смещение | Размер | Тип | Значение |
|---|---|---|---|
| 0 | 1 | uint8 | Версия = 1 |
| 1 | 3 | bytes | Нули |
| 4 | 4 | uint32 | sequence |
| 8 | 8 | float64 | clientTimeMs, монотонное время клиента |
| 16 | 12 | 3 × float32 | X, Y, Z, метры |
| 28 | 16 | 4 × float32 | Quaternion X, Y, Z, W |
Оси: вперёд +X, вправо +Y, вверх +Z. Начало координат одинаковое для всех
участников и стен одной комнаты. В UE переводить сантиметры в метры. Передавать
ориентацию головы/камеры, если взгляд отличается от поворота тела. Quaternion
должен соответствовать этим осям; поворот yaw 90° переводит вперёд +X в +Y.
Валидация: все числа конечные; модуль каждой координаты < 10^7 м; квадрат нормы
quaternion строго между 0.5 и 1.5, после приёма quaternion нормализуется.
Некорректная или устаревшая поза молча игнорируется. Sequence сравнивается как
знаковая разность uint32: допускается переполнение, скачки >= 2^31 не допускаются.
Сервер связывает позу с ParticipantID фактического отправителя: пакет не содержит
identity другого игрока. Контроллер локации пока не может отправлять позы игроков
от своего имени. Если позже потребуется авторитетная геометрия игроков со стороны
сервера локации, нужен отдельный доверенный протокол.
Отправлять heartbeat и в неподвижном состоянии. Рекомендованный стартовый период
50 мс, timeout по умолчанию 500 мс по времени получения на сервере. clientTimeMs
не используется для синхронизации часов или вычисления возраста позы. При потере
актуальной позы вклад в миксы затухает. Деградация объединяет изменения координат
на сервере; период отправки клиента сама не меняет.
## Полная сцена
```json
{
"version": 1,
"revision": 101,
"location_id": "loc-courtyard-session-7",
"enabled": true,
"hrtf": true,
"adaptive": true,
"objects": [
{
"id": "wall-east",
"center": [0, 2, 0],
"size": [12, 6],
"rotation": [0.7071067811865476, 0, 0, 0.7071067811865476],
"transmission": 0.2,
"priority": 100
}
]
}
```
| Поле | Правило |
|---|---|
| version | Только 1 |
| revision | Целое 1 ≤ revision < 2^53; строго больше принятой ревизии комнаты |
| location_id | Непустая строка после TrimSpace, длина ≤ 100 байт |
| enabled | Учёт препятствий; отсутствие даёт false |
| hrtf, adaptive | Необязательные bool; отсутствие сохраняет текущий режим |
| objects | Полная замена списка; отсутствие/null трактуется как пустой список |
| id объекта | Непустой, уникальный, длина ≤ 64 байт |
| center | Три конечных координаты, модуль каждой < 10^7 м |
| size | Ровно [ширина, высота] по локальным X/Y, каждый от 0.0001 до 10^6 м; толщина отсутствует |
| rotation | Quaternion XYZW, та же проверка нормы и нормализация, что у позы |
| transmission | Обязательное число 0..1, множитель амплитуды; 0 блокирует, 1 пропускает |
| priority | Необязательное целое 0..100, по умолчанию 100 |
Payload ≤ 15000 байт UTF-8; число объектов ≤ серверного `occlusion.max_objects`
(по умолчанию 64, конфигурационный максимум 512). Увеличение лимита объектов
не увеличивает лимит байт. Разбиение сцены на чанки, delta-обновления, произвольные
mesh и пользовательские наборы HRTF не реализованы. Неизвестные поля JSON сейчас
игнорируются; это не означает поддержки новых возможностей.
Стена — двусторонний плоский прямоугольник в локальной XY с нормалью +Z. Quaternion
поворачивает локальные оси в координаты локации. Отрезок проверяется на пересечение
плоскости и попадание в ограниченный прямоугольник. Край и конец отрезка на стене
учитываются для непараллельного отрезка; параллельные/копланарные отрезки не
ослабляются. Стена учитывается один раз; одинаково в обоих направлениях.
Изменение геометрии в текущем spatial v1: старый массив size=[X,Y,Z] отклоняется
полностью. Для миграции прежней стены в локальной XZ (толщина по Y) использовать
size=[X,Z] и rotation_new = rotation_old * quaternion(+90° вокруг локальной X).
Этот дополнительный quaternion равен [sqrt(0.5),0,0,sqrt(0.5)]. Для уже плоской
стены XZ size и center сохраняются, rotation меняется тем же умножением справа.
Прежняя +Y-нормаль станет -Y: для двустороннего ослабления знак несущественен.
При иной исходной плоскости преобразовать ориентацию так, чтобы размеры шли
по локальным X/Y. Identity rotation теперь задаёт горизонтальный прямоугольник
в мировой XY. Обновить persisted-сцены и контроллеры до отправки.
`location_id` пока проверяется только как строка: он не сопоставляется с комнатой
и не задаёт маршрутизацию. Целевой room определяется JWT контроллера. Привязку
location_id ↔ room должен проверять бэкенд. При нескольких комнатах отправлять
сцену и получать ACK в каждой отдельно.
Если occlusion выключена конфигурацией ноды, сервер отклоняет сцену с enabled=true
или непустыми objects даже при enabled=false. Для изменения только HRTF/adaptive
на такой ноде отправлять enabled=false и objects=[]. HRTF/adaptive можно включить
сценой только при разрешении в YAML. Невалидная сцена полностью отклоняется;
предыдущая сцена и флаги остаются действующими. Отключённые стены валидируются
так же, как включённые.
## Подтверждение
Сервер отправляет reliable ACK напрямую контроллеру, не всей комнате:
```json
{"revision":101,"ok":true}
```
```json
{"revision":101,"ok":false,"error":"scene revision must increase"}
```
При ошибке проверки доступа/транспорта/формата revision может быть 0.
ACK означает принятие команды движком, а не подтверждение того, что клиент
уже услышал результат. Матрица обновляется на ближайшем аудиотике, коэффициенты
и включение/выключение HRTF сглаживаются. Клиенту контроллера следует отличать
серверный ACK от сообщений других участников: серверный пакет не имеет участника-
отправителя; один лишь topic не доказывает происхождение сообщения.
Применяется полная сцена, не PATCH: изменение флага с objects=[] удаляет стены.
Для переключения функции сохранять текущий полный список объектов и enabled.
Нет API чтения последней ревизии или сцены. Один логический writer должен
сериализовать изменения локации и админки, хранить полный desired snapshot
и выделять возрастающие ревизии. Повтор той же ревизии не идемпотентен: будет
отклонён даже после успешно применённой сцены с потерянным ACK. После таймаута
отправлять новый полный snapshot с большей ревизией. При смене желаемого состояния
не повторять устаревший snapshot.
При уничтожении комнаты/перезапуске процесса состояние и ревизия в памяти исчезают.
При кратком отключении контроллера живая комната сохраняет сцену; начальное состояние
после перезапуска — пустые стены, HRTF/adaptive согласно YAML. Контроллер повторно
отправляет desired snapshot и ждёт ACK, прежде чем объявить аудиосцену готовой.
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+628
View File
@@ -0,0 +1,628 @@
# Steam Audio Third-Party Licenses
## Intel Integrated Performance Primitives (IPP)
Intel Simplified Software License (Version October 2022)
Use and Redistribution. You may use and redistribute the software, which is provided in binary form only, (the “Software”), without modification, provided the following conditions are met:
Redistributions must reproduce the above copyright notice and these terms of use in the Software and in the documentation and/or other materials provided with the distribution.
Neither the name of Intel nor the names of its suppliers may be used to endorse or promote products derived from this Software without specific prior written permission.
No reverse engineering, decompilation, or disassembly of the Software is permitted, nor any modification or alteration of the Software or its operation at any time, including during execution.
No other licenses. Except as provided in the preceding section, Intel grants no licenses or other rights by implication, estoppel or otherwise to, patent, copyright, trademark, trade name, service mark or other intellectual property licenses or rights of Intel.
Third party software. “Third Party Software” means the files (if any) listed in the “third-party-software.txt” or other similarly-named text file that may be included with the Software. Third Party Software, even if included with the distribution of the Software, may be governed by separate license terms, including without limitation, third party license terms, open source software notices and terms, and/or other Intel software license terms. These separate license terms solely govern Your use of the Third Party Software.
DISCLAIMER. THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. THIS SOFTWARE IS NOT INTENDED FOR USE IN SYSTEMS OR APPLICATIONS WHERE FAILURE OF THE SOFTWARE MAY CAUSE PERSONAL INJURY OR DEATH AND YOU AGREE THAT YOU ARE FULLY RESPONSIBLE FOR ANY CLAIMS, COSTS, DAMAGES, EXPENSES, AND ATTORNEYS’ FEES ARISING OUT OF ANY SUCH USE, EVEN IF ANY CLAIM ALLEGES THAT INTEL WAS NEGLIGENT REGARDING THE DESIGN OR MANUFACTURE OF THE SOFTWARE.
LIMITATION OF LIABILITY. IN NO EVENT WILL INTEL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
No support. Intel may make changes to the Software, at any time without notice, and is not obligated to support, update or provide training for the Software.
Termination. Your right to use the Software is terminated in the event of your breach of this license.
Feedback. Should you provide Intel with comments, modifications, corrections, enhancements or other input (“Feedback”) related to the Software, Intel will be free to use, disclose, reproduce, license or otherwise distribute or exploit the Feedback in its sole discretion without any obligations or restrictions of any kind, including without limitation, intellectual property rights or licensing obligations.
Compliance with laws. You agree to comply with all relevant laws and regulations governing your use, transfer, import or export (or prohibition thereof) of the Software.
Governing law. All disputes will be governed by the laws of the United States of America and the State of Delaware without reference to conflict of law principles and subject to the exclusive jurisdiction of the state or federal courts sitting in the State of Delaware, and each party agrees that it submits to the personal jurisdiction and venue of those courts and waives any objections. THE UNITED NATIONS CONVENTION ON CONTRACTS FOR THE INTERNATIONAL SALE OF GOODS (1980) IS SPECIFICALLY EXCLUDED AND WILL NOT APPLY TO THE SOFTWARE.
## FFTS
This file is part of FFTS -- The Fastest Fourier Transform in the South
Copyright (c) 2012, 2013 Anthony M. Blake <amb@anthonix.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the organization nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ANTHONY M. BLAKE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
## PFFFT
Copyright (c) 2020 Dario Mambro ( dario.mambro@gmail.com )
Copyright (c) 2019 Hayati Ayguen ( h_ayguen@web.de )
Copyright (c) 2013 Julien Pommier ( pommier@modartt.com )
Copyright (c) 2004 the University Corporation for Atmospheric
Research ("UCAR"). All rights reserved. Developed by NCAR's
Computational and Information Systems Laboratory, UCAR,
www.cisl.ucar.edu.
Redistribution and use of the Software in source and binary forms,
with or without modification, is permitted provided that the
following conditions are met:
- Neither the names of NCAR's Computational and Information Systems
Laboratory, the University Corporation for Atmospheric Research,
nor the names of its sponsors or contributors may be used to
endorse or promote products derived from this Software without
specific prior written permission.
- Redistributions of source code must retain the above copyright
notices, this list of conditions, and the disclaimer below.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the disclaimer below in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
SOFTWARE.
## MySOFA
Copyright (c) 2016-2017, Symonics GmbH, Christian Hoene
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
(1) Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
(2) Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
(3)The name of the author may not be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
## Intel Embree
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## AMD RadeonRays
Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## AMD TrueAudio Next
MIT license
Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## CIPIC HRTF Database
Sponsorship
This work was supported by the National Science Foundation under Grants
IRI-9619339 and ITR-0086075. Any opinions, findings and conclusions or
recommendations expressed in this material are those of the authors, and
do not necessarily reflect the views of the National Science Foundation.
Copyright
Copyright (c) 2001 The Regents of the University of California. All Rights Reserved
Disclaimer
THE REGENTS OF THE UNIVERSITY OF CALIFORNIA MAKE NO REPRESENTATION OR
WARRANTIES WITH RESPECT TO THE CONTENTS HEREOF AND SPECIFICALLY DISCLAIM ANY
IMPLIED WARRANTIES OR MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE.
Further, the Regents of the University of California reserve the right to
revise this software and/or documentation and to make changes from time to
time in the content hereof without obligation of the Regents of the University
of California to notify any person of such revision or change.
Use of Materials
The Regents of the University of California hereby grant users permission to
reproduce and/or use materials available therein for any purpose- educational,
research or commercial. However, each reproduction of any part of the
materials must include the copyright notice, if it is present.
In addition, as a courtesy, if these materials are used in published research,
this use should be acknowledged in the publication. If these materials are
used in the development of commercial products, the Regents of the University
of California request that written acknowledgment of such use be sent to:
CIPIC- Center for Image Processing and Integrated Computing
University of California
1 Shields Avenue
Davis, CA 95616-8553
## Google Spherical Harmonics Library
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+1
View File
@@ -69,6 +69,7 @@ require (
github.com/containerd/errdefs v1.0.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/distribution/reference v0.6.0 // indirect
github.com/ebitengine/purego v0.11.1
github.com/fatih/color v1.19.0 // indirect
github.com/felixge/httpsnoop v1.1.0 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
+2
View File
@@ -56,6 +56,8 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/ebitengine/purego v0.11.1 h1:2zpWRSQNVKN4eKsKO9eM1ILDgWfYMY9GwqRmK6XeQ/0=
github.com/ebitengine/purego v0.11.1/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
github.com/elliotchance/orderedmap/v3 v3.1.1 h1:eV7lfZ5fVL8d36b8Wogqi/eqm7R/kZcftA9Yiyj+63M=
github.com/elliotchance/orderedmap/v3 v3.1.1/go.mod h1:G+Hc2RwaZvJMcS4JpGCOyViCnGeKf0bTYCGTO4uhjSo=
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
+19
View File
@@ -0,0 +1,19 @@
cmake_minimum_required(VERSION 3.20)
project(sverse_hrtf LANGUAGES CXX)
set(STEAMAUDIO_ROOT "" CACHE PATH "Steam Audio 4.8.1 SDK root")
if(NOT EXISTS "${STEAMAUDIO_ROOT}/include/phonon.h")
message(FATAL_ERROR "Set STEAMAUDIO_ROOT to the extracted steamaudio directory")
endif()
add_library(sverse_hrtf SHARED bridge.cpp)
target_compile_features(sverse_hrtf PRIVATE cxx_std_17)
target_include_directories(sverse_hrtf PRIVATE "${STEAMAUDIO_ROOT}/include")
if(WIN32)
target_link_libraries(sverse_hrtf PRIVATE "${STEAMAUDIO_ROOT}/lib/windows-x64/phonon.lib")
add_custom_command(TARGET sverse_hrtf POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${STEAMAUDIO_ROOT}/lib/windows-x64/phonon.dll" "$<TARGET_FILE_DIR:sverse_hrtf>")
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR MATCHES "x86_64|AMD64")
target_link_libraries(sverse_hrtf PRIVATE "${STEAMAUDIO_ROOT}/lib/linux-x64/libphonon.so")
set_target_properties(sverse_hrtf PROPERTIES BUILD_RPATH "$ORIGIN" INSTALL_RPATH "$ORIGIN" BUILD_WITH_INSTALL_RPATH TRUE)
add_custom_command(TARGET sverse_hrtf POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${STEAMAUDIO_ROOT}/lib/linux-x64/libphonon.so" "$<TARGET_FILE_DIR:sverse_hrtf>")
else()
message(FATAL_ERROR "This bridge currently supports Windows x64 and Linux x64")
endif()
+84
View File
@@ -0,0 +1,84 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
#include <phonon.h>
#include <phonon_version.h>
#include <cmath>
#include <memory>
#include <vector>
#ifdef _WIN32
#define EXPORT extern "C" __declspec(dllexport)
#else
#define EXPORT extern "C" __attribute__((visibility("default")))
#endif
struct Renderer {
IPLContext context = nullptr;
IPLHRTF hrtf = nullptr;
IPLAudioSettings audio{};
~Renderer() { iplHRTFRelease(&hrtf); iplContextRelease(&context); }
};
struct Pair {
Renderer* renderer;
IPLBinauralEffect effect = nullptr;
std::vector<float> left, right;
explicit Pair(Renderer* r) : renderer(r), left(r->audio.frameSize), right(r->audio.frameSize) {}
~Pair() { iplBinauralEffectRelease(&effect); }
};
EXPORT int sverse_hrtf_create(int sampleRate, int frameSize, void** output) {
if (!output || sampleRate != 48000 || frameSize != 480) return -1;
*output = nullptr;
try {
auto renderer = std::make_unique<Renderer>();
IPLContextSettings context{};
context.version = STEAMAUDIO_VERSION;
context.simdLevel = IPL_SIMDLEVEL_SSE2;
auto error = iplContextCreate(&context, &renderer->context);
if (error != IPL_STATUS_SUCCESS) return static_cast<int>(error);
renderer->audio = {sampleRate, frameSize};
IPLHRTFSettings settings{};
settings.type = IPL_HRTFTYPE_DEFAULT;
settings.volume = 1.0f;
settings.normType = IPL_HRTFNORMTYPE_RMS;
error = iplHRTFCreate(renderer->context, &renderer->audio, &settings, &renderer->hrtf);
if (error != IPL_STATUS_SUCCESS) return static_cast<int>(error);
*output = renderer.release();
return 0;
} catch (...) { return -2; }
}
EXPORT void sverse_hrtf_destroy(void* renderer) { delete static_cast<Renderer*>(renderer); }
EXPORT int sverse_hrtf_pair_create(void* renderer, void** output) {
if (!renderer || !output) return -1;
*output = nullptr;
try {
auto pair = std::make_unique<Pair>(static_cast<Renderer*>(renderer));
IPLBinauralEffectSettings settings{pair->renderer->hrtf};
auto error = iplBinauralEffectCreate(pair->renderer->context, &pair->renderer->audio, &settings, &pair->effect);
if (error != IPL_STATUS_SUCCESS) return static_cast<int>(error);
*output = pair.release();
return 0;
} catch (...) { return -2; }
}
EXPORT void sverse_hrtf_pair_destroy(void* pair) { delete static_cast<Pair*>(pair); }
// Borrowed Go buffers are only accessed during this call, never retained.
// The bridge keeps all C API structures and channel-pointer arrays in native code.
EXPORT int sverse_hrtf_apply(void* handle, const float* mono, float* stereo, const float* direction, int interpolation) {
if (!handle || !mono || !stereo || !direction) return -1;
try {
auto* pair = static_cast<Pair*>(handle);
IPLBinauralEffectParams params{};
const float length = std::sqrt(direction[0]*direction[0] + direction[1]*direction[1] + direction[2]*direction[2]);
params.direction = length > 1e-6f ? IPLVector3{direction[0]/length, direction[1]/length, direction[2]/length} : IPLVector3{0,0,-1};
params.interpolation = interpolation ? IPL_HRTFINTERPOLATION_BILINEAR : IPL_HRTFINTERPOLATION_NEAREST;
params.spatialBlend = 1.0f;
params.hrtf = pair->renderer->hrtf;
float* inChannels[] = {const_cast<float*>(mono)};
float* outChannels[] = {pair->left.data(), pair->right.data()};
const int samples = pair->renderer->audio.frameSize;
IPLAudioBuffer input{1,samples,inChannels}, output{2,samples,outChannels};
iplBinauralEffectApply(pair->effect,&params,&input,&output);
for (int n = 0; n < samples; ++n) { stereo[2*n] = pair->left[n]; stereo[2*n+1] = pair->right[n]; }
return 0;
} catch (...) { return -2; }
}
+39 -5
View File
@@ -27,6 +27,7 @@ import (
"github.com/urfave/cli/v3"
"gopkg.in/yaml.v3"
"github.com/livekit/livekit-server/pkg/spatialaudio"
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
"github.com/livekit/protocol/codecs/mime"
"github.com/livekit/protocol/livekit"
@@ -220,6 +221,22 @@ type CongestionControlConfig struct {
SendSideBWE sendsidebwe.SendSideBWEConfig `yaml:"send_side_bwe,omitempty"`
}
// Validate reports configuration that would otherwise be ignored at runtime.
func (c CongestionControlConfig) Validate() error {
switch pacer.PacerBehavior(c.SendSideBWEPacer) {
case "", pacer.PacerBehaviorPassThrough, pacer.PacerBehaviorNoQueue, pacer.PacerBehaviorLeakybucket:
return nil
default:
return fmt.Errorf(
"invalid send_side_bwe_pacer %q, must be one of %q, %q, %q",
c.SendSideBWEPacer,
pacer.PacerBehaviorPassThrough,
pacer.PacerBehaviorNoQueue,
pacer.PacerBehaviorLeakybucket,
)
}
}
type PlayoutDelayConfig struct {
Enabled bool `yaml:"enabled,omitempty"`
Min int `yaml:"min,omitempty"`
@@ -234,6 +251,7 @@ type VideoConfig struct {
}
type RoomConfig struct {
SpatialAudio spatialaudio.Config `yaml:"spatial_audio,omitempty"`
// enable rooms to be automatically created
AutoCreate bool `yaml:"auto_create,omitempty"`
EnabledCodecs []CodecSpec `yaml:"enabled_codecs,omitempty"`
@@ -399,8 +417,20 @@ func (l LimitConfig) CheckAttributesSize(attributes map[string]string) bool {
return uint32(total) <= l.MaxAttributesSize
}
func (l LimitConfig) CheckDataBlobKeyLength(key string) bool {
return l.MaxDataBlobKeyLength == 0 || len(key) <= l.MaxDataBlobKeyLength
// DataBlobKeyLength returns the length of the identifying content of a data blob key.
// The text form of the key message is not used, as it adds field names and quotes.
func DataBlobKeyLength(key *livekit.DataBlobKey) int {
switch k := key.GetKey().(type) {
case *livekit.DataBlobKey_Generic:
return len(k.Generic)
case *livekit.DataBlobKey_SchemaId:
return len(k.SchemaId.GetName()) + len(k.SchemaId.GetEncoding().GetCustom())
}
return 0
}
func (l LimitConfig) CheckDataBlobKeyLength(key *livekit.DataBlobKey) bool {
return l.MaxDataBlobKeyLength == 0 || DataBlobKeyLength(key) <= l.MaxDataBlobKeyLength
}
func (l LimitConfig) CheckDataTrackCustomEncodingLength(identifier string) bool {
@@ -430,7 +460,7 @@ func (l LimitConfig) CheckDataBlobsSize(dataBlobs []*livekit.DataBlob) bool {
total := 0
for _, dataBlob := range dataBlobs {
total += len(dataBlob.GetKey().String()) + len(dataBlob.Contents)
total += DataBlobKeyLength(dataBlob.GetKey()) + len(dataBlob.Contents)
}
return uint32(total) <= l.MaxDataBlobSize
}
@@ -442,9 +472,9 @@ func (l LimitConfig) CanAddDataBlob(dataBlobs []*livekit.DataBlob, toAdd *liveki
total := 0
for _, dataBlob := range dataBlobs {
total += len(dataBlob.Key.String()) + len(dataBlob.Contents)
total += DataBlobKeyLength(dataBlob.GetKey()) + len(dataBlob.Contents)
}
return uint32(total+len(toAdd.GetKey().String())+len(toAdd.Contents)) <= l.MaxDataBlobSize
return uint32(total+DataBlobKeyLength(toAdd.GetKey())+len(toAdd.Contents)) <= l.MaxDataBlobSize
}
// ---------------------------------
@@ -659,6 +689,10 @@ func NewConfig(confString string, strictMode bool, c *cli.Command, baseFlags []c
return nil, fmt.Errorf("could not validate RTC config: %v", err)
}
if err := conf.RTC.CongestionControl.Validate(); err != nil {
return nil, fmt.Errorf("could not validate congestion control config: %v", err)
}
conf.NormalizeTURNTTLs()
// expand env vars in filenames
+35
View File
@@ -23,6 +23,7 @@ import (
"github.com/urfave/cli/v3"
"github.com/livekit/livekit-server/pkg/config/configtest"
"github.com/livekit/livekit-server/pkg/sfu/pacer"
)
func TestConfig_UnmarshalKeys(t *testing.T) {
@@ -182,6 +183,40 @@ func TestNewConfigNormalizesTURNTTL(t *testing.T) {
require.Equal(t, DefaultTURNTTLSeconds, conf.TURN.TTLSeconds)
}
func TestNewConfigValidatesSendSideBWEPacer(t *testing.T) {
cases := []struct {
name string
pacer string
wantErr bool
}{
{name: "unset keeps the default", pacer: "", wantErr: false},
{name: "pass-through", pacer: string(pacer.PacerBehaviorPassThrough), wantErr: false},
{name: "no-queue", pacer: string(pacer.PacerBehaviorNoQueue), wantErr: false},
{name: "leaky-bucket", pacer: string(pacer.PacerBehaviorLeakybucket), wantErr: false},
{name: "typo is rejected", pacer: "leakybucket", wantErr: true},
{name: "unknown value is rejected", pacer: "not-a-pacer", wantErr: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
content := "rtc:\n congestion_control:\n send_side_bwe_pacer: " + tc.pacer
conf, err := NewConfig(content, true, nil, nil)
if tc.wantErr {
require.Error(t, err)
require.Contains(t, err.Error(), tc.pacer)
return
}
require.NoError(t, err)
if tc.pacer == "" {
require.Equal(t, string(pacer.PacerBehaviorNoQueue), conf.RTC.CongestionControl.SendSideBWEPacer)
return
}
require.Equal(t, tc.pacer, conf.RTC.CongestionControl.SendSideBWEPacer)
})
}
}
func writeSecretFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "secret")
+4
View File
@@ -162,6 +162,10 @@ func isCodecEnabledWithFmtp(codecs []*livekit.Codec, cap webrtc.RTPCodecCapabili
func selectAlternativeVideoCodec(enabledCodecs []*livekit.Codec) string {
for _, c := range enabledCodecs {
// RTX and FEC are not real codecs, skip them
if mime.IsMimeTypeStringRTX(c.Mime) || mime.IsMimeTypeStringFlexFEC03(c.Mime) {
continue
}
if mime.IsMimeTypeStringVideo(c.Mime) {
return c.Mime
}
+17
View File
@@ -73,6 +73,23 @@ func TestIsCodecEnabled(t *testing.T) {
})
}
func TestSelectAlternativeVideoCodec(t *testing.T) {
// RTX and FEC have the video/ prefix but are not real codecs. The fallback must skip them.
t.Run("skips rtx and fec, picks real codec", func(t *testing.T) {
enabled := []*livekit.Codec{
{Mime: mime.MimeTypeRTX.String()},
{Mime: mime.MimeTypeFlexFEC03.String()},
{Mime: mime.MimeTypeH264.String()},
}
require.Equal(t, mime.MimeTypeH264.String(), selectAlternativeVideoCodec(enabled))
})
t.Run("falls back to vp8 when only rtx is enabled", func(t *testing.T) {
enabled := []*livekit.Codec{{Mime: mime.MimeTypeRTX.String()}}
require.Equal(t, mime.MimeTypeVP8.String(), selectAlternativeVideoCodec(enabled))
})
}
type offeredCodec struct {
payloadType webrtc.PayloadType
name string
+24
View File
@@ -144,6 +144,7 @@ type MediaTrackReceiver struct {
onMediaLossFeedback func(dt *sfu.DownTrack, report *rtcp.ReceiverReport)
onClose []func(isExpectedToResume bool)
onCodecRegression func(old, new webrtc.RTPCodecParameters)
rtpObserver func(webrtc.RTPCodecParameters, *buffer.ExtPacket)
*MediaTrackSubscriptions
}
@@ -228,6 +229,11 @@ func (t *MediaTrackReceiver) SetupReceiver(receiver sfu.TrackReceiver, priority
}
t.receivers = receivers
if observer, ok := receiver.(interface {
SetRTPObserver(func(webrtc.RTPCodecParameters, *buffer.ExtPacket))
}); ok {
observer.SetRTPObserver(t.rtpObserver)
}
onSetupReceiver := t.onSetupReceiver
t.lock.Unlock()
@@ -248,6 +254,24 @@ func (t *MediaTrackReceiver) SetupReceiver(receiver sfu.TrackReceiver, priority
}
}
// SetRTPObserver also applies to receivers added after publication (codec changes).
func (t *MediaTrackReceiver) SetRTPObserver(fn func(webrtc.RTPCodecParameters, *buffer.ExtPacket)) {
t.lock.Lock()
t.rtpObserver = fn
for _, r := range t.receivers {
receiver := r.TrackReceiver
if dummy, ok := receiver.(*DummyReceiver); ok {
receiver = dummy.Receiver()
}
if observer, ok := receiver.(interface {
SetRTPObserver(func(webrtc.RTPCodecParameters, *buffer.ExtPacket))
}); ok {
observer.SetRTPObserver(fn)
}
}
t.lock.Unlock()
}
func (t *MediaTrackReceiver) HandleReceiverCodecChange(r sfu.TrackReceiver, codec webrtc.RTPCodecParameters, state sfu.ReceiverCodecState) {
// TODO: we only support codec regress to backup codec now, so the receiver will not be available
// once fallback / regression happens.
+2 -1
View File
@@ -15,6 +15,7 @@
package rtc
import (
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
@@ -31,7 +32,7 @@ func (p *ParticipantImpl) HandleStoreDataBlobRequest(req *livekit.StoreDataBlobR
return
}
if req.Blob == nil || req.Blob.Key == nil || len(req.Blob.Key.String()) == 0 || !p.params.LimitConfig.CheckDataBlobKeyLength(req.Blob.Key.String()) {
if req.Blob == nil || req.Blob.Key == nil || config.DataBlobKeyLength(req.Blob.Key) == 0 || !p.params.LimitConfig.CheckDataBlobKeyLength(req.Blob.Key) {
p.pubLogger.Warnw("data blob is invalid", nil, "req", logger.Proto(req))
p.sendRequestResponse(&livekit.RequestResponse{
RequestId: req.RequestId,
@@ -124,6 +124,61 @@ func TestHandleStoreDataBlobRequest(t *testing.T) {
require.Equal(t, livekit.RequestResponse_INVALID_REQUEST, rr.Reason)
})
t.Run("returns INVALID_REQUEST when generic key is empty", func(t *testing.T) {
p := newParticipantWithDataBlob(t, true, 0, 0)
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
p.HandleStoreDataBlobRequest(&livekit.StoreDataBlobRequest{
Blob: &livekit.DataBlob{
Key: genericKey(""),
Contents: []byte("def"),
},
})
require.Equal(t, 1, sink.WriteMessageCallCount())
rr := lastRequestResponse(t, sink, 0)
require.Equal(t, livekit.RequestResponse_INVALID_REQUEST, rr.Reason)
require.Empty(t, p.dataBlob.GetAll())
})
t.Run("accepts a key exactly at the length limit", func(t *testing.T) {
p := newParticipantWithDataBlob(t, true, 5, 0)
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
key := genericKey("abcde")
p.HandleStoreDataBlobRequest(&livekit.StoreDataBlobRequest{
Blob: &livekit.DataBlob{
Key: key,
Contents: []byte("def"),
},
})
require.Equal(t, 1, sink.WriteMessageCallCount())
msg := sink.WriteMessageArgsForCall(0).(*livekit.SignalResponse)
_, ok := msg.Message.(*livekit.SignalResponse_StoreDataBlobResponse)
require.True(t, ok, "expected SignalResponse_StoreDataBlobResponse, got %T", msg.Message)
require.NotNil(t, p.dataBlob.Get(key))
})
t.Run("counts only key and contents bytes against the size limit", func(t *testing.T) {
p := newParticipantWithDataBlob(t, true, 0, 9)
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
key := genericKey("abc")
p.HandleStoreDataBlobRequest(&livekit.StoreDataBlobRequest{
Blob: &livekit.DataBlob{
Key: key,
Contents: []byte("defghi"),
},
})
require.Equal(t, 1, sink.WriteMessageCallCount())
msg := sink.WriteMessageArgsForCall(0).(*livekit.SignalResponse)
_, ok := msg.Message.(*livekit.SignalResponse_StoreDataBlobResponse)
require.True(t, ok, "expected SignalResponse_StoreDataBlobResponse, got %T", msg.Message)
require.NotNil(t, p.dataBlob.Get(key))
})
t.Run("returns INVALID_REQUEST when contents is empty", func(t *testing.T) {
p := newParticipantWithDataBlob(t, true, 0, 0)
sink := p.params.Sink.(*routingfakes.FakeMessageSink)
+32
View File
@@ -79,6 +79,38 @@ func TestIsReady(t *testing.T) {
}
}
// Disabling a codec can leave the publish list with only RTX and FEC. The
// fallback must still pick a real codec, or the track registers as RTX and
// subscribers see a blank tile.
func TestPublishCodecFallbackSkipsRTX(t *testing.T) {
h264 := &livekit.Codec{Mime: mime.MimeTypeH264.String()}
rtx := &livekit.Codec{Mime: mime.MimeTypeRTX.String()}
newParticipant := func() *ParticipantImpl {
return &ParticipantImpl{params: ParticipantParams{Logger: logger.GetLogger()}}
}
t.Run("h264 enabled, rtx is last and not chosen", func(t *testing.T) {
p := newParticipant()
p.setupEnabledCodecs([]*livekit.Codec{h264, rtx}, nil, nil)
require.Equal(t, mime.MimeTypeH264.String(), selectAlternativeVideoCodec(p.enabledPublishCodecs))
})
t.Run("h264 disabled leaves rtx only, fallback avoids rtx", func(t *testing.T) {
p := newParticipant()
disabled := &livekit.DisabledCodecs{Publish: []*livekit.Codec{{Mime: mime.MimeTypeH264.String()}}}
p.setupEnabledCodecs([]*livekit.Codec{h264, rtx}, nil, disabled)
require.Len(t, p.enabledPublishCodecs, 1)
require.True(t, mime.IsMimeTypeStringRTX(p.enabledPublishCodecs[0].Mime))
alt := selectAlternativeVideoCodec(p.enabledPublishCodecs)
require.False(t, mime.IsMimeTypeStringRTX(alt), "fallback must not be rtx, got %q", alt)
require.Equal(t, mime.MimeTypeVP8.String(), alt)
})
}
func TestSupportsMoving(t *testing.T) {
t.Run("current protocol version", func(t *testing.T) {
p := newParticipantForTestWithOpts("test", &participantOpts{protocolVersion: types.CurrentProtocol})
+46
View File
@@ -152,6 +152,8 @@ type Room struct {
onStateChangeMu sync.Mutex
localParticipantListener types.LocalParticipantListener
participantTelemetryListener types.ParticipantTelemetryListener
spatial *spatialAudioRoom
spatialErr error
}
type ParticipantOptions struct {
@@ -289,6 +291,10 @@ func NewRoom(
}),
}
r.trackManager = NewRoomTrackManager(r.logger)
r.spatial, r.spatialErr = newSpatialAudioRoom(r)
if r.spatialErr != nil {
r.logger.Errorw("spatial audio initialization failed", r.spatialErr)
}
r.localParticipantListener = &localParticipantListener{room: r}
r.participantTelemetryListener = &participantTelemetryListener{room: r}
@@ -451,6 +457,12 @@ func (r *Room) Join(
if r.IsClosed() {
return ErrRoomClosed
}
if r.spatialErr != nil {
return spatialJoinError(r.spatialErr)
}
if r.spatial != nil && len(r.participants) >= r.spatial.config.MaxParticipants {
return ErrMaxParticipantsExceeded
}
if r.participants[participant.Identity()] != nil {
return ErrAlreadyJoined
@@ -595,6 +607,9 @@ func (r *Room) ResumeParticipant(
if err := p.SendParticipantUpdate(updates); err != nil {
return err
}
if r.spatial != nil {
go r.attachSpatial(p)
}
_ = p.SendRoomUpdate(r.ToProto())
p.ICERestart(iceConfig)
@@ -727,6 +742,13 @@ func (r *Room) ResolveMediaTrackForSubscriber(sub types.LocalParticipant, trackI
res.TrackRemovedNotifier = r.trackManager.GetOrCreateTrackRemoveNotifier(trackID)
res.PublisherIdentity = info.PublisherIdentity
res.PublisherID = info.PublisherID
if output, ok := info.Track.(*spatialPublication); ok {
res.HasPermission = output.target == sub.ID()
return res
}
if r.spatial != nil && info.Track.Kind() == livekit.TrackType_AUDIO {
return res
}
pub := r.GetParticipantByID(info.PublisherID)
// when publisher is not found, we will assume it doesn't have permission to access
@@ -820,6 +842,9 @@ func (r *Room) Close(reason types.RoomCloseReason) {
r.lock.Unlock()
r.logger.Infow("closing room", "reason", reason)
if r.spatial != nil {
r.spatial.close()
}
participantCloseReason := reason.ToParticipantCloseReason()
for _, p := range r.GetParticipants() {
_ = p.Close(true, participantCloseReason, false)
@@ -1075,6 +1100,9 @@ func (r *Room) createJoinResponseLocked(
// a ParticipantImpl in the room added a new track, subscribe other participants to it
func (r *Room) onTrackPublished(participant types.Participant, track types.MediaTrack) {
r.trackManager.AddTrack(track, participant.Identity(), participant.ID())
if r.spatial != nil {
r.spatial.published(participant, track)
}
// publish participant update, since track state is changed
r.broadcastParticipantState(participant, broadcastOptions{skipSource: true})
@@ -1082,6 +1110,9 @@ func (r *Room) onTrackPublished(participant types.Participant, track types.Media
r.lock.RLock()
// subscribe all existing participants to this MediaTrack
for _, existingParticipant := range r.participants {
if r.spatial != nil && track.Kind() == livekit.TrackType_AUDIO {
continue
}
if existingParticipant == participant {
// skip publishing participant
continue
@@ -1245,6 +1276,9 @@ func (r *Room) onStateChange(p types.LocalParticipant) {
switch p.State() {
case livekit.ParticipantInfo_ACTIVE:
if r.spatial != nil {
go r.attachSpatial(p)
}
// subscribe participant to existing published tracks
r.subscribeToExistingTracks(p, false)
@@ -1290,6 +1324,12 @@ func (r *Room) onStateChange(p types.LocalParticipant) {
}
func (r *Room) onDataMessage(source types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket) {
if r.spatial != nil && r.spatial.scene(source, kind, dp) {
return
}
if r.spatial != nil && r.spatial.pose(source, dp) {
return
}
if kind == livekit.DataPacket_RELIABLE && source != nil && dp.GetSequence() > 0 {
data, err := proto.Marshal(dp)
if err != nil {
@@ -1455,6 +1495,9 @@ func (r *Room) RemoveParticipant(
}
r.lock.Unlock()
r.protoProxy.MarkDirty(immediateChange)
if r.spatial != nil {
r.spatial.remove(p)
}
if !p.HasConnected() {
fields := append(
@@ -1518,6 +1561,9 @@ func (r *Room) subscribeToExistingTracks(p types.LocalParticipant, isSync bool)
// subscribe to all
if autoSubscribe {
for _, track := range op.GetPublishedTracks() {
if r.spatial != nil && track.Kind() == livekit.TrackType_AUDIO {
continue
}
trackIDs = append(trackIDs, track.ID())
p.SubscribeToTrack(track.ID(), isSync)
}
+1
View File
@@ -906,6 +906,7 @@ func newRoomWithParticipants(t *testing.T, opts testRoomOpts) *Room {
telemetry.NewTelemetryService(n, &telemetryfakes.FakeAnalyticsService{}),
nil, nil, nil,
)
t.Cleanup(func() { rm.Close(types.RoomCloseReasonUnknown) })
for i := 0; i < opts.num+opts.numHidden; i++ {
identity := livekit.ParticipantIdentity(fmt.Sprintf("p%d", i))
participant := NewMockParticipant(identity, opts.protocol, i >= opts.num, true, rm.LocalParticipantListener())
+301
View File
@@ -0,0 +1,301 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package rtc
import (
"crypto/rand"
"encoding/binary"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/spatialaudio"
"github.com/livekit/mediatransportutil"
"github.com/livekit/protocol/codecs/mime"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/guid"
"github.com/livekit/protocol/utils/mono"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
"google.golang.org/protobuf/proto"
)
type spatialPublication struct {
*MediaTrackReceiver
target livekit.ParticipantID
receiver *sfu.ReceiverBase
buffer *buffer.Buffer
ssrc uint32
sequence uint16
packets uint32
octets uint64
lastSR time.Time
lastTimestamp uint32
timestampCycles uint64
}
var _ types.MediaTrack = (*spatialPublication)(nil)
func (t *spatialPublication) Logger() logger.Logger { return t.MediaTrackReceiver.params.Logger }
func (t *spatialPublication) ToProto() *livekit.TrackInfo { return t.TrackInfoClone() }
func (t *spatialPublication) OnTrackSubscribed() {}
func (t *spatialPublication) GetTemporalLayerForSpatialFps(mime.MimeType, int32, uint32) int32 {
return 0
}
func (t *spatialPublication) AddSubscriber(p types.LocalParticipant) (types.SubscribedTrack, error) {
if p.ID() != t.target {
return nil, ErrNoTrackPermission
}
return t.MediaTrackReceiver.AddSubscriber(p)
}
func (t *spatialPublication) Close(resume bool) {
t.receiver.Close("spatial output closed", true)
t.MediaTrackReceiver.Close(resume)
}
func (t *spatialPublication) Write(payload []byte, timestamp uint32) error {
p := rtp.Packet{Header: rtp.Header{Version: 2, PayloadType: 111, SequenceNumber: t.sequence, Timestamp: timestamp, SSRC: t.ssrc}, Payload: payload}
b, err := p.Marshal()
if err != nil {
return err
}
t.sequence++
if _, err = t.buffer.Write(b); err != nil {
return err
}
t.packets++
t.octets += uint64(len(payload))
if timestamp < t.lastTimestamp {
t.timestampCycles += 1 << 32
}
t.lastTimestamp = timestamp
now := time.Now()
if now.Sub(t.lastSR) >= time.Second {
t.lastSR = now
at := mono.UnixNano()
t.buffer.SetSenderReportData(&livekit.RTCPSenderReportState{RtpTimestamp: timestamp, RtpTimestampExt: t.timestampCycles + uint64(timestamp), NtpTimestamp: uint64(mediatransportutil.ToNtpTime(now)), At: at, AtAdjusted: at, Packets: t.packets, Octets: t.octets})
}
return nil
}
func newSpatialPublication(r *Room, p types.LocalParticipant) (*spatialPublication, error) {
var seed [6]byte
if _, err := rand.Read(seed[:]); err != nil {
return nil, err
}
t := &spatialPublication{target: p.ID(), ssrc: binary.LittleEndian.Uint32(seed[:4]), sequence: binary.LittleEndian.Uint16(seed[4:])}
pubID := livekit.ParticipantID(guid.New("PA_"))
trackID := guid.New("TR_")
info := &livekit.TrackInfo{Sid: trackID, Name: "spatial_mix", Type: livekit.TrackType_AUDIO, Source: livekit.TrackSource_UNKNOWN, MimeType: webrtc.MimeTypeOpus, Stereo: true, DisableDtx: true, DisableRed: true, AudioFeatures: []livekit.AudioTrackFeature{livekit.AudioTrackFeature_TF_STEREO, livekit.AudioTrackFeature_TF_NO_DTX}, Codecs: []*livekit.SimulcastCodecInfo{{MimeType: webrtc.MimeTypeOpus}}}
codec := webrtc.RTPCodecParameters{RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48000, Channels: 2, SDPFmtpLine: "minptime=10;stereo=1;sprop-stereo=1;useinbandfec=1"}, PayloadType: 111}
t.MediaTrackReceiver = NewMediaTrackReceiver(MediaTrackReceiverParams{MediaTrack: t, ParticipantID: func() livekit.ParticipantID { return pubID }, ParticipantIdentity: livekit.ParticipantIdentity("__spatial_" + string(p.ID())), ParticipantVersion: 1, ReceiverConfig: r.config.Receiver, SubscriberConfig: r.config.Subscriber, AudioConfig: *r.audioConfig, TelemetryListener: func() types.ParticipantTelemetryListener { return types.NullParticipantTelemetryListener{} }, Logger: r.logger}, info)
t.receiver = sfu.NewReceiverBase(sfu.ReceiverBaseParams{TrackID: livekit.TrackID(trackID), StreamID: string(pubID), Kind: webrtc.RTPCodecTypeAudio, Codec: codec, Logger: r.logger}, info, sfu.ReceiverCodecStateNormal)
t.buffer = buffer.NewBuffer(t.ssrc, r.config.Receiver.PacketBufferSizeVideo, r.config.Receiver.PacketBufferSizeAudio)
t.receiver.AddBuffer(t.buffer, 0)
if err := t.buffer.Bind(webrtc.RTPParameters{Codecs: []webrtc.RTPCodecParameters{codec}}, codec.RTPCodecCapability, 64000); err != nil {
t.Close(false)
return nil, err
}
t.MediaTrackReceiver.SetupReceiver(t.receiver, 0, "")
t.receiver.StartBuffer(t.buffer, 0)
return t, nil
}
func (t *spatialPublication) ParticipantInfo() *livekit.ParticipantInfo {
return &livekit.ParticipantInfo{Sid: string(t.PublisherID()), Identity: string(t.PublisherIdentity()), Name: "Spatial audio", State: livekit.ParticipantInfo_ACTIVE, Version: 1, Tracks: []*livekit.TrackInfo{t.ToProto()}}
}
type spatialAudioRoom struct {
room *Room
engine *spatialaudio.Engine
config spatialaudio.Config
mu sync.Mutex
outputs map[livekit.ParticipantID]*spatialPublication
closed bool
}
func newSpatialAudioRoom(r *Room) (*spatialAudioRoom, error) {
c := r.roomConfig.SpatialAudio.Defaults()
if !c.Enabled || !strings.HasPrefix(string(r.Name()), c.RoomPrefix) {
return nil, nil
}
engine, err := spatialaudio.NewEngine(c)
if err != nil {
return nil, err
}
s := &spatialAudioRoom{room: r, engine: engine, config: c, outputs: make(map[livekit.ParticipantID]*spatialPublication)}
if c.DebugStats {
go func() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-r.closed:
return
case <-ticker.C:
r.logger.Infow("spatial audio stats", "stats", engine.String())
}
}
}()
}
return s, nil
}
func (s *spatialAudioRoom) attach(p types.LocalParticipant) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed || p.IsDisconnected() || s.room.GetParticipantByID(p.ID()) != p {
return nil
}
if !p.CanSubscribe() {
return nil
}
out := s.outputs[p.ID()]
if out == nil {
var err error
out, err = newSpatialPublication(s.room, p)
if err != nil {
return err
}
if err = s.engine.AddListener(string(p.ID()), out.Write); err != nil {
out.Close(false)
return err
}
s.outputs[p.ID()] = out
s.room.trackManager.AddTrack(out, out.PublisherIdentity(), out.PublisherID())
}
if err := p.SendParticipantUpdate([]*livekit.ParticipantInfo{out.ParticipantInfo()}); err != nil {
return err
}
p.SubscribeToTrack(out.ID(), false)
return nil
}
func (s *spatialAudioRoom) pose(p types.LocalParticipant, dp *livekit.DataPacket) bool {
u := dp.GetUser()
if u == nil || u.GetTopic() != spatialaudio.PoseTopic {
return false
}
if p != nil {
if pose, err := spatialaudio.ParsePose(u.Payload); err == nil {
s.engine.Poses.Update(string(p.ID()), pose, time.Now())
}
}
return true
}
func (s *spatialAudioRoom) scene(p types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket) bool {
u := dp.GetUser()
if u == nil || u.GetTopic() != spatialaudio.SceneTopic {
return false
}
if p == nil {
return true
}
var revision uint64
var err error
grants := p.ClaimGrants()
if grants == nil || grants.Video == nil || !grants.Video.RoomAdmin {
err = fmt.Errorf("scene updates require roomAdmin permission")
} else if kind != livekit.DataPacket_RELIABLE {
err = fmt.Errorf("scene updates require reliable data")
} else if s.room.GetParticipantByID(p.ID()) != p {
err = fmt.Errorf("scene publisher has left the room")
} else {
revision, err = s.engine.ApplyScene(u.Payload)
}
ack := struct {
Revision uint64 `json:"revision"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}{Revision: revision, OK: err == nil}
if err != nil {
ack.Error = err.Error()
}
payload, _ := json.Marshal(ack)
topic := spatialaudio.SceneAckTopic
data, marshalErr := proto.Marshal(&livekit.DataPacket{Kind: livekit.DataPacket_RELIABLE, Value: &livekit.DataPacket_User{User: &livekit.UserPacket{Payload: payload, Topic: &topic}}})
if marshalErr == nil {
_ = p.SendDataMessage(livekit.DataPacket_RELIABLE, data, "", 0)
}
if err == nil {
s.room.logger.Infow("spatial scene updated", "revision", revision, "publisher", p.Identity())
}
return true
}
func (s *spatialAudioRoom) published(p types.Participant, track types.MediaTrack) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed || s.room.GetParticipantByID(p.ID()) == nil {
return
}
if track.Kind() != livekit.TrackType_AUDIO || track.Source() != livekit.TrackSource_MICROPHONE {
return
}
if track.IsEncrypted() {
s.room.logger.Warnw("spatial audio requires unencrypted application audio", nil, "track", track.ID())
return
}
observer, ok := track.(interface {
SetRTPObserver(func(webrtc.RTPCodecParameters, *buffer.ExtPacket))
})
if !ok {
return
}
input, err := s.engine.AddSource(string(p.ID()), string(track.ID()))
if err != nil {
s.room.logger.Errorw("add spatial audio input", err)
return
}
observer.SetRTPObserver(func(codec webrtc.RTPCodecParameters, packet *buffer.ExtPacket) {
if track.IsMuted() {
return
}
payload := packet.Packet.Payload
if mime.IsMimeTypeStringRED(codec.MimeType) {
var err error
payload, err = spatialaudio.PrimaryRED(payload)
if err != nil {
return
}
} else if !mime.IsMimeTypeStringOpus(codec.MimeType) {
return
}
input.Push(spatialaudio.RTPInput{Sequence: packet.Packet.SequenceNumber, Timestamp: packet.Packet.Timestamp, SSRC: packet.Packet.SSRC, Payload: payload})
})
track.AddOnClose(func(bool) { observer.SetRTPObserver(nil); s.engine.RemoveSource(string(p.ID()), string(track.ID())) })
}
func (s *spatialAudioRoom) remove(p types.LocalParticipant) {
s.mu.Lock()
defer s.mu.Unlock()
s.engine.RemoveParticipant(string(p.ID()))
if out := s.outputs[p.ID()]; out != nil {
delete(s.outputs, p.ID())
s.room.trackManager.RemoveTrack(out)
out.Close(false)
}
}
func (s *spatialAudioRoom) close() {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
s.closed = true
s.engine.Close()
for _, out := range s.outputs {
s.room.trackManager.RemoveTrack(out)
out.Close(false)
}
clear(s.outputs)
}
func (r *Room) attachSpatial(p types.LocalParticipant) {
if r.spatial != nil {
if err := r.spatial.attach(p); err != nil {
r.logger.Errorw("attach spatial audio output", err, "participant", p.ID())
}
}
}
func spatialJoinError(err error) error { return fmt.Errorf("spatial audio room unavailable: %w", err) }
+6
View File
@@ -23,6 +23,7 @@ import (
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/pkg/sfu/connectionquality"
)
func NewMockParticipant(
@@ -54,6 +55,11 @@ func NewMockParticipant(
State: livekit.ParticipantInfo_JOINED,
IsPublisher: publisher,
}, utils.TimedVersion(0))
p.GetConnectionQualityReturns(&livekit.ConnectionQualityInfo{
ParticipantSid: sid,
Quality: livekit.ConnectionQuality_EXCELLENT,
Score: connectionquality.MaxMOS,
})
p.SetMetadataCalls(func(m string) {
participantListener.OnParticipantUpdate(p)
+14 -1
View File
@@ -582,12 +582,25 @@ func NewPCTransport(params TransportParams) (*PCTransport, error) {
Config: params.CongestionControlConfig.SendSideBWE,
Logger: params.Logger,
})
switch pacer.PacerBehavior(params.CongestionControlConfig.SendSideBWEPacer) {
switch behavior := pacer.PacerBehavior(params.CongestionControlConfig.SendSideBWEPacer); behavior {
case pacer.PacerBehaviorPassThrough:
t.pacer = pacer.NewPassThrough(params.Logger, t.bwe)
case pacer.PacerBehaviorNoQueue:
t.pacer = pacer.NewNoQueue(params.Logger, t.bwe)
default:
// leaky-bucket lands here: it is a recognized value, but LeakyBucket paces
// to a bitrate set through Pacer.SetBitrate and nothing drives that from
// the bandwidth estimate, so it would pace at a fixed rate and ignore
// congestion. Unknown values are rejected by CongestionControlConfig.
// Validate, so they only reach here from callers building TransportParams
// directly.
if behavior != "" {
params.Logger.Warnw(
"send side BWE pacer unavailable, falling back", nil,
"pacerBehavior", behavior,
"fallback", pacer.PacerBehaviorNoQueue,
)
}
t.pacer = pacer.NewNoQueue(params.Logger, t.bwe)
}
} else {
+19 -10
View File
@@ -60,8 +60,8 @@ func TestMissingAnswerDuringICERestart(t *testing.T) {
handleICEExchange(t, transportA, transportB, handlerA, handlerB)
connectTransports(t, transportA, transportB, handlerA, handlerB, false, 1, 1)
require.Equal(t, webrtc.ICEConnectionStateConnected, transportA.pc.ICEConnectionState())
require.Equal(t, webrtc.ICEConnectionStateConnected, transportB.pc.ICEConnectionState())
require.True(t, iceConnected(transportA.pc))
require.True(t, iceConnected(transportB.pc))
var negotiationState atomic.Value
transportA.OnNegotiationStateChanged(func(state transport.NegotiationState) {
@@ -82,8 +82,8 @@ func TestMissingAnswerDuringICERestart(t *testing.T) {
}, 10*time.Second, time.Millisecond*10, "transportA offer not received")
connectTransports(t, transportA, transportB, handlerA, handlerB, true, 1, 1)
require.Equal(t, webrtc.ICEConnectionStateConnected, transportA.pc.ICEConnectionState())
require.Equal(t, webrtc.ICEConnectionStateConnected, transportB.pc.ICEConnectionState())
require.True(t, iceConnected(transportA.pc))
require.True(t, iceConnected(transportB.pc))
transportA.Close()
transportB.Close()
@@ -270,8 +270,8 @@ func TestFirstOfferMissedDuringICERestart(t *testing.T) {
// ensure we are connected
require.Eventually(t, func() bool {
return transportA.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
transportB.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
return iceConnected(transportA.pc) &&
iceConnected(transportB.pc) &&
offerCount.Load() == 2
}, testutils.ConnectTimeout, 10*time.Millisecond, "transport did not connect")
@@ -347,8 +347,8 @@ func TestFirstAnswerMissedDuringICERestart(t *testing.T) {
// ensure we are connected
require.Eventually(t, func() bool {
return transportA.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
transportB.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected &&
return iceConnected(transportA.pc) &&
iceConnected(transportB.pc) &&
offerCount.Load() == 2
}, testutils.ConnectTimeout, 10*time.Millisecond, "transport did not connect")
@@ -518,6 +518,15 @@ func TestFilteringCandidates(t *testing.T) {
transport.Close()
}
// iceConnected reports whether a peer connection's ICE has established. The
// controlling agent (the offerer) advances Connected -> Completed once its
// connectivity checks finish, so asserting exactly Connected races the poll
// against that transition; both states mean the transport is up.
func iceConnected(pc *webrtc.PeerConnection) bool {
s := pc.ICEConnectionState()
return s == webrtc.ICEConnectionStateConnected || s == webrtc.ICEConnectionStateCompleted
}
func handleICEExchange(t *testing.T, a, b *PCTransport, ah, bh *transportfakes.FakeHandler) {
ah.OnICECandidateCalls(func(candidate *webrtc.ICECandidate, target livekit.SignalTarget) error {
if candidate == nil {
@@ -563,7 +572,7 @@ func connectTransports(t *testing.T, offerer, answerer *PCTransport, offererHand
}, 10*time.Second, time.Millisecond*10, fmt.Sprintf("offer count mismatch, expected: %d, actual: %d", expectedOfferCount, offerCount.Load()))
require.Eventually(t, func() bool {
return offerer.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected
return iceConnected(offerer.pc)
}, 10*time.Second, time.Millisecond*10, "offerer did not become connected")
require.Eventually(t, func() bool {
@@ -571,7 +580,7 @@ func connectTransports(t *testing.T, offerer, answerer *PCTransport, offererHand
}, 10*time.Second, time.Millisecond*10, fmt.Sprintf("answer count mismatch, expected: %d, actual: %d", expectedAnswerCount, answerCount.Load()))
require.Eventually(t, func() bool {
return answerer.pc.ICEConnectionState() == webrtc.ICEConnectionStateConnected
return iceConnected(answerer.pc)
}, 10*time.Second, time.Millisecond*10, "answerer did not become connected")
transportsConnected := untilTransportsConnected(offererHandler, answererHandler)
+3 -1
View File
@@ -81,7 +81,9 @@ type IngressStore interface {
type RoomAllocator interface {
AutoCreateEnabled(ctx context.Context) bool
SelectRoomNode(ctx context.Context, roomName livekit.RoomName, nodeID livekit.NodeID) error
CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, bool, error)
// CreateRoom also returns the request with its room preset applied,
// or req unchanged when the implementation does not resolve presets
CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error)
ValidateCreateRoom(ctx context.Context, roomName livekit.RoomName) error
}
+1 -1
View File
@@ -113,7 +113,7 @@ func (s *IOInfoService) EvaluateSIPDispatchRules(ctx context.Context, req *rpc.E
if e := (*sip.ErrNoDispatchMatched)(nil); errors.As(err, &e) {
return &rpc.EvaluateSIPDispatchRulesResponse{
SipTrunkId: trunkID,
Result: rpc.SIPDispatchResult_DROP,
Result: rpc.SIPDispatchResult_REJECT,
}, nil
}
return nil, err
+16
View File
@@ -24,6 +24,7 @@ import (
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/rpc"
"github.com/livekit/psrpc/pkg/bus/redisbus"
)
@@ -121,3 +122,18 @@ func TestSIPRuleSelect(t *testing.T) {
})
}
}
func TestSIPDispatchNoRuleRejects(t *testing.T) {
ctx := context.Background()
s, rs := ioStoreDocker(t)
require.NoError(t, rs.StoreSIPInboundTrunk(ctx, &livekit.SIPInboundTrunkInfo{SipTrunkId: "A", Numbers: []string{"+1000"}}))
for number, trunk := range map[string]string{"+1000": "A", "+2000": ""} {
resp, err := s.EvaluateSIPDispatchRules(ctx, &rpc.EvaluateSIPDispatchRulesRequest{
Call: &rpc.SIPCall{SourceIp: "1.1.1.1", From: &livekit.SIPUri{User: "+3000"}, To: &livekit.SIPUri{User: number}},
})
require.NoError(t, err)
require.Equal(t, rpc.SIPDispatchResult_REJECT, resp.Result, number)
require.Equal(t, trunk, resp.SipTrunkId)
}
}
+6 -6
View File
@@ -59,10 +59,10 @@ func (r *StandardRoomAllocator) AutoCreateEnabled(context.Context) bool {
// CreateRoom creates a new room from a request and allocates it to a node to handle
// it'll also monitor its state, and cleans it up when appropriate
func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, bool, error) {
func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.CreateRoomRequest, isExplicit bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error) {
token, err := r.roomStore.LockRoom(ctx, livekit.RoomName(req.Name), 5*time.Second)
if err != nil {
return nil, nil, false, err
return nil, nil, nil, false, err
}
defer func() {
_ = r.roomStore.UnlockRoom(ctx, livekit.RoomName(req.Name), token)
@@ -84,12 +84,12 @@ func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.Cre
internal = &livekit.RoomInternal{}
applyDefaultRoomConfig(rm, internal, &r.config.Room)
} else if err != nil {
return nil, nil, false, err
return nil, nil, nil, false, err
}
req, err = r.applyNamedRoomConfiguration(req)
if err != nil {
return nil, nil, false, err
return nil, nil, nil, false, err
}
if req.EmptyTimeout > 0 {
@@ -127,10 +127,10 @@ func (r *StandardRoomAllocator) CreateRoom(ctx context.Context, req *livekit.Cre
}
if err = r.roomStore.StoreRoom(ctx, rm, internal); err != nil {
return nil, nil, false, err
return nil, nil, nil, false, err
}
return rm, internal, created, nil
return rm, internal, req, created, nil
}
func (r *StandardRoomAllocator) SelectRoomNode(ctx context.Context, roomName livekit.RoomName, nodeID livekit.NodeID) error {
+33 -1
View File
@@ -39,12 +39,44 @@ func TestCreateRoom(t *testing.T) {
ra, conf := newTestRoomAllocator(t, conf, node.Clone())
room, _, _, err := ra.CreateRoom(context.Background(), &livekit.CreateRoomRequest{Name: "myroom"}, true)
room, _, _, _, err := ra.CreateRoom(context.Background(), &livekit.CreateRoomRequest{Name: "myroom"}, true)
require.NoError(t, err)
require.Equal(t, conf.Room.EmptyTimeout, room.EmptyTimeout)
require.Equal(t, conf.Room.DepartureTimeout, room.DepartureTimeout)
require.NotEmpty(t, room.EnabledCodecs)
})
t.Run("return the request with the room preset applied", func(t *testing.T) {
conf, err := config.NewConfig(`
room:
room_configurations:
record:
egress:
room:
layout: grid
`, true, nil, nil)
require.NoError(t, err)
node, err := routing.NewLocalNode(conf)
require.NoError(t, err)
ra, conf := newTestRoomAllocator(t, conf, node.Clone())
// without a preset, the request itself is returned
req := &livekit.CreateRoomRequest{Name: "myroom"}
_, _, applied, _, err := ra.CreateRoom(context.Background(), req, true)
require.NoError(t, err)
require.Same(t, req, applied)
// with a preset, a copy with the preset applied is returned,
// leaving both the request and the preset unchanged
req = &livekit.CreateRoomRequest{Name: "myroom", RoomPreset: "record"}
_, _, applied, _, err = ra.CreateRoom(context.Background(), req, true)
require.NoError(t, err)
require.Nil(t, req.Egress)
require.Equal(t, "grid", applied.GetEgress().GetRoom().GetLayout())
require.NotSame(t, conf.Room.RoomConfigurations["record"].Egress.Room, applied.Egress.Room)
})
}
func SelectRoomNode(t *testing.T) {
+8 -1
View File
@@ -656,7 +656,9 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.C
}
// create new room, get details first
ri, internal, created, err := r.roomAllocator.CreateRoom(ctx, createRoom, true)
// createRoom is reassigned to the request with the room preset applied, so that a room
// composite egress from the preset, which RoomInternal has no field for, is started
ri, internal, createRoom, created, err := r.roomAllocator.CreateRoom(ctx, createRoom, true)
if err != nil {
return nil, err
}
@@ -733,6 +735,11 @@ func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.C
prometheus.RoomStarted()
if created && createRoom.GetEgress().GetRoom() != nil {
if r.egressLauncher == nil {
newRoom.Release()
return nil, ErrEgressNotConnected
}
// ensure room name matches
createRoom.Egress.Room.RoomName = createRoom.Name
_, err = r.egressLauncher.StartEgress(ctx, &rpc.StartEgressRequest{
+181
View File
@@ -0,0 +1,181 @@
// Copyright 2026 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service_test
import (
"context"
"sync"
"testing"
"github.com/stretchr/testify/require"
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/rpc"
"github.com/livekit/protocol/utils"
"github.com/livekit/psrpc"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/routing/routingfakes"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/livekit-server/pkg/telemetry/telemetryfakes"
)
// fakeEgressLauncher records the egress start requests it receives.
type fakeEgressLauncher struct {
mu sync.Mutex
started []*rpc.StartEgressRequest
}
func (f *fakeEgressLauncher) StartEgress(_ context.Context, req *rpc.StartEgressRequest) (*livekit.EgressInfo, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.started = append(f.started, req)
return &livekit.EgressInfo{}, nil
}
func (f *fakeEgressLauncher) StopEgress(context.Context, *livekit.StopEgressRequest) (*livekit.EgressInfo, error) {
return &livekit.EgressInfo{}, nil
}
func (f *fakeEgressLauncher) roomCompositeRoomNames() []string {
f.mu.Lock()
defer f.mu.Unlock()
var names []string
for _, req := range f.started {
if rc := req.GetRoomComposite(); rc != nil {
names = append(names, rc.RoomName)
}
}
return names
}
func newTestRoomManager(t *testing.T, conf *config.Config, egressLauncher rtc.EgressLauncher) *service.RoomManager {
// no fixed RTC ports, so that the test does not bind the defaults
conf.RTC.TCPPort = 0
conf.RTC.UDPPort = rtcconfig.PortRange{}
node, err := routing.NewLocalNode(conf)
require.NoError(t, err)
router := &routingfakes.FakeRouter{}
router.GetNodeForRoomReturns(node.Clone(), nil)
store := service.NewLocalStore()
ra, err := service.NewRoomAllocator(conf, router, store)
require.NoError(t, err)
rm, err := service.NewLocalRoomManager(
conf,
store,
node,
router,
ra,
&telemetryfakes.FakeTelemetryService{},
nil,
store,
egressLauncher,
utils.NewDefaultTimedVersionGenerator(),
nil,
psrpc.NewLocalMessageBus(),
nil,
)
require.NoError(t, err)
t.Cleanup(rm.Stop)
return rm
}
func TestRoomCompositeEgressOnCreateRoom(t *testing.T) {
t.Run("from request", func(t *testing.T) {
conf, err := config.NewConfig("", true, nil, nil)
require.NoError(t, err)
launcher := &fakeEgressLauncher{}
rm := newTestRoomManager(t, conf, launcher)
_, err = rm.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
Name: "room-a",
Egress: &livekit.RoomEgress{
Room: &livekit.RoomCompositeEgressRequest{
Layout: "grid",
FileOutputs: []*livekit.EncodedFileOutput{{Filepath: "recordings/{room_name}.mp4"}},
},
},
})
require.NoError(t, err)
require.Equal(t, []string{"room-a"}, launcher.roomCompositeRoomNames())
})
t.Run("from room preset", func(t *testing.T) {
conf, err := config.NewConfig(roomPresetConfig, true, nil, nil)
require.NoError(t, err)
launcher := &fakeEgressLauncher{}
rm := newTestRoomManager(t, conf, launcher)
for _, name := range []string{"room-a", "room-b"} {
_, err = rm.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
Name: name,
RoomPreset: "record",
})
require.NoError(t, err)
}
// each room records itself, and the preset is left as configured
require.Equal(t, []string{"room-a", "room-b"}, launcher.roomCompositeRoomNames())
require.Empty(t, conf.Room.RoomConfigurations["record"].GetEgress().GetRoom().GetRoomName())
})
t.Run("from room preset when a session starts", func(t *testing.T) {
conf, err := config.NewConfig(roomPresetConfig, true, nil, nil)
require.NoError(t, err)
launcher := &fakeEgressLauncher{}
rm := newTestRoomManager(t, conf, launcher)
// the join and WHIP paths create the room through StartSession, with the
// token's room preset; without an identity only the room is created
err = rm.StartSession(context.Background(), routing.ParticipantInit{
CreateRoom: &livekit.CreateRoomRequest{
Name: "room-a",
RoomPreset: "record",
},
}, nil, nil, false)
require.NoError(t, err)
require.Equal(t, []string{"room-a"}, launcher.roomCompositeRoomNames())
})
t.Run("from room preset without an egress launcher", func(t *testing.T) {
conf, err := config.NewConfig(roomPresetConfig, true, nil, nil)
require.NoError(t, err)
rm := newTestRoomManager(t, conf, nil)
_, err = rm.CreateRoom(context.Background(), &livekit.CreateRoomRequest{
Name: "room-a",
RoomPreset: "record",
})
require.ErrorIs(t, err, service.ErrEgressNotConnected)
})
}
const roomPresetConfig = `
room:
room_configurations:
record:
egress:
room:
layout: grid
file_outputs:
- filepath: recordings/{room_name}.mp4
`
+24 -19
View File
@@ -21,7 +21,7 @@ type FakeRoomAllocator struct {
autoCreateEnabledReturnsOnCall map[int]struct {
result1 bool
}
CreateRoomStub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, bool, error)
CreateRoomStub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error)
createRoomMutex sync.RWMutex
createRoomArgsForCall []struct {
arg1 context.Context
@@ -31,14 +31,16 @@ type FakeRoomAllocator struct {
createRoomReturns struct {
result1 *livekit.Room
result2 *livekit.RoomInternal
result3 bool
result4 error
result3 *livekit.CreateRoomRequest
result4 bool
result5 error
}
createRoomReturnsOnCall map[int]struct {
result1 *livekit.Room
result2 *livekit.RoomInternal
result3 bool
result4 error
result3 *livekit.CreateRoomRequest
result4 bool
result5 error
}
SelectRoomNodeStub func(context.Context, livekit.RoomName, livekit.NodeID) error
selectRoomNodeMutex sync.RWMutex
@@ -130,7 +132,7 @@ func (fake *FakeRoomAllocator) AutoCreateEnabledReturnsOnCall(i int, result1 boo
}{result1}
}
func (fake *FakeRoomAllocator) CreateRoom(arg1 context.Context, arg2 *livekit.CreateRoomRequest, arg3 bool) (*livekit.Room, *livekit.RoomInternal, bool, error) {
func (fake *FakeRoomAllocator) CreateRoom(arg1 context.Context, arg2 *livekit.CreateRoomRequest, arg3 bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error) {
fake.createRoomMutex.Lock()
ret, specificReturn := fake.createRoomReturnsOnCall[len(fake.createRoomArgsForCall)]
fake.createRoomArgsForCall = append(fake.createRoomArgsForCall, struct {
@@ -146,9 +148,9 @@ func (fake *FakeRoomAllocator) CreateRoom(arg1 context.Context, arg2 *livekit.Cr
return stub(arg1, arg2, arg3)
}
if specificReturn {
return ret.result1, ret.result2, ret.result3, ret.result4
return ret.result1, ret.result2, ret.result3, ret.result4, ret.result5
}
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3, fakeReturns.result4
return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3, fakeReturns.result4, fakeReturns.result5
}
func (fake *FakeRoomAllocator) CreateRoomCallCount() int {
@@ -157,7 +159,7 @@ func (fake *FakeRoomAllocator) CreateRoomCallCount() int {
return len(fake.createRoomArgsForCall)
}
func (fake *FakeRoomAllocator) CreateRoomCalls(stub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, bool, error)) {
func (fake *FakeRoomAllocator) CreateRoomCalls(stub func(context.Context, *livekit.CreateRoomRequest, bool) (*livekit.Room, *livekit.RoomInternal, *livekit.CreateRoomRequest, bool, error)) {
fake.createRoomMutex.Lock()
defer fake.createRoomMutex.Unlock()
fake.CreateRoomStub = stub
@@ -170,19 +172,20 @@ func (fake *FakeRoomAllocator) CreateRoomArgsForCall(i int) (context.Context, *l
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeRoomAllocator) CreateRoomReturns(result1 *livekit.Room, result2 *livekit.RoomInternal, result3 bool, result4 error) {
func (fake *FakeRoomAllocator) CreateRoomReturns(result1 *livekit.Room, result2 *livekit.RoomInternal, result3 *livekit.CreateRoomRequest, result4 bool, result5 error) {
fake.createRoomMutex.Lock()
defer fake.createRoomMutex.Unlock()
fake.CreateRoomStub = nil
fake.createRoomReturns = struct {
result1 *livekit.Room
result2 *livekit.RoomInternal
result3 bool
result4 error
}{result1, result2, result3, result4}
result3 *livekit.CreateRoomRequest
result4 bool
result5 error
}{result1, result2, result3, result4, result5}
}
func (fake *FakeRoomAllocator) CreateRoomReturnsOnCall(i int, result1 *livekit.Room, result2 *livekit.RoomInternal, result3 bool, result4 error) {
func (fake *FakeRoomAllocator) CreateRoomReturnsOnCall(i int, result1 *livekit.Room, result2 *livekit.RoomInternal, result3 *livekit.CreateRoomRequest, result4 bool, result5 error) {
fake.createRoomMutex.Lock()
defer fake.createRoomMutex.Unlock()
fake.CreateRoomStub = nil
@@ -190,16 +193,18 @@ func (fake *FakeRoomAllocator) CreateRoomReturnsOnCall(i int, result1 *livekit.R
fake.createRoomReturnsOnCall = make(map[int]struct {
result1 *livekit.Room
result2 *livekit.RoomInternal
result3 bool
result4 error
result3 *livekit.CreateRoomRequest
result4 bool
result5 error
})
}
fake.createRoomReturnsOnCall[i] = struct {
result1 *livekit.Room
result2 *livekit.RoomInternal
result3 bool
result4 error
}{result1, result2, result3, result4}
result3 *livekit.CreateRoomRequest
result4 bool
result5 error
}{result1, result2, result3, result4, result5}
}
func (fake *FakeRoomAllocator) SelectRoomNode(arg1 context.Context, arg2 livekit.RoomName, arg3 livekit.NodeID) error {
+3 -2
View File
@@ -68,13 +68,14 @@ func (s *DataStats) ToProtoActive() *livekit.RTPStats {
if duration > s.params.WindowDuration.Nanoseconds() {
return &livekit.RTPStats{}
}
seconds := float64(duration) / 1e9
return &livekit.RTPStats{
StartTime: timestamppb.New(time.Unix(s.windowStart/1e9, s.windowStart%1e9)),
EndTime: timestamppb.New(time.Unix(0, now)),
Duration: float64(duration / 1e9),
Duration: seconds,
Bytes: uint64(s.windowBytes),
Bitrate: float64(s.windowBytes) * 8 / float64(duration) / 1e9,
Bitrate: float64(s.windowBytes) * 8 / seconds,
}
}
+13
View File
@@ -51,3 +51,16 @@ func TestDataStats(t *testing.T) {
require.EqualValues(t, 100, r.Bytes)
require.NotZero(t, r.Bitrate)
}
func TestDataStatsActiveBitrateAndDuration(t *testing.T) {
stats := NewDataStats(DataStatsParam{WindowDuration: 10 * time.Second})
// 1000 bytes over a 1.5 second window is 8000 bits / 1.5 s
stats.windowStart = time.Now().Add(-1500 * time.Millisecond).UnixNano()
stats.windowBytes = 1000
r := stats.ToProtoActive()
require.EqualValues(t, 1000, r.Bytes)
require.InDelta(t, 1.5, r.Duration, 0.1)
require.InDelta(t, 8000/1.5, r.Bitrate, 0.1*8000/1.5)
}
+24 -16
View File
@@ -1079,9 +1079,28 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
SSRC: d.ssrc,
})
pacerPacket := pacer.PacketFactory.Get().(*pacer.Packet)
*pacerPacket = pacer.Packet{
Header: hdr,
HeaderPool: RTPHeaderFactory,
Payload: payload,
ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()),
AbsSendTimeExtID: uint8(d.absSendTimeExtID),
TransportWideExtID: uint8(d.transportWideExtID),
WriteStream: d.writeStream,
Pool: PacketFactory,
PoolEntity: poolEntity,
}
// add extensions
if d.dependencyDescriptorExtID != 0 && tp.ddBytes != nil {
hdr.SetExtension(uint8(d.dependencyDescriptorExtID), tp.ddBytes)
//
// the header refers to the descriptor until the pacer marshals it, so hold it in the pacer packet, which one send owns
ddBytes := tp.ddBytesSpill
if inline := tp.ddInline(); ddBytes == nil && len(inline) != 0 {
ddBytes = pacerPacket.HoldExtension(inline)
}
if d.dependencyDescriptorExtID != 0 && len(ddBytes) != 0 {
hdr.SetExtension(uint8(d.dependencyDescriptorExtID), ddBytes)
}
if d.playoutDelayExtID != 0 && d.playoutDelay != nil {
if val := d.playoutDelay.GetDelayExtension(hdr.SequenceNumber); val != nil {
@@ -1128,6 +1147,7 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
}
d.addDummyExtensions(hdr)
// the sequencer copies the descriptor, which has to happen before Enqueue frees the scratch
if d.sequencer != nil {
d.sequencer.push(
extPkt.Arrival,
@@ -1138,13 +1158,14 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
int8(layer),
payload[:len(codecBytes)],
tp.incomingHeaderSize,
tp.ddBytes,
ddBytes,
actBytes,
trailerStripped,
)
}
headerSize := hdr.MarshalSize()
pacerPacket.HeaderSize = headerSize
d.rtpStats.Update(
extPkt.Arrival,
tp.rtp.extSequenceNumber,
@@ -1155,19 +1176,6 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
0,
extPkt.IsOutOfOrder,
)
pacerPacket := pacer.PacketFactory.Get().(*pacer.Packet)
*pacerPacket = pacer.Packet{
Header: hdr,
HeaderPool: RTPHeaderFactory,
HeaderSize: headerSize,
Payload: payload,
ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()),
AbsSendTimeExtID: uint8(d.absSendTimeExtID),
TransportWideExtID: uint8(d.transportWideExtID),
WriteStream: d.writeStream,
Pool: PacketFactory,
PoolEntity: poolEntity,
}
d.pacer.Enqueue(pacerPacket)
if extPkt.IsKeyFrame {
+11 -2
View File
@@ -199,7 +199,9 @@ type TranslationParams struct {
isResuming bool
isSwitching bool
rtp TranslationParamsRTP
ddBytes []byte
ddBytes [dd.MaxInlineExtensionSize]byte
ddBytesLen int
ddBytesSpill []byte
incomingHeaderSize int
codecBytes [codecmunger.MaxHeaderSize]byte
codecBytesLen int
@@ -213,6 +215,13 @@ func (tp *TranslationParams) codecHeader() []byte {
return tp.codecBytes[:tp.codecBytesLen]
}
// ddInline returns the dependency descriptor extension held inline. It points
// into tp, so it has to be copied before it is attached to anything that
// outlives the write.
func (tp *TranslationParams) ddInline() []byte {
return tp.ddBytes[:tp.ddBytesLen]
}
// -------------------------------------------------------------------
type refInfo struct {
@@ -2190,7 +2199,7 @@ func (f *Forwarder) getTranslationParamsVideo(extPkt *buffer.ExtPacket, layer in
}
tp.isResuming = result.IsResuming
tp.isSwitching = result.IsSwitching
tp.ddBytes = result.DependencyDescriptorExtension
tp.ddBytes, tp.ddBytesLen, tp.ddBytesSpill = result.DDBytes, result.DDBytesLen, result.DDBytesSpill
tp.marker = result.RTPMarker
tp.isEndOfLayerFrame = f.isEndOfLayerFrame(extPkt)
+11
View File
@@ -28,6 +28,7 @@ import (
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/sfu/codecmunger"
"github.com/livekit/livekit-server/pkg/sfu/pacer"
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
"github.com/livekit/livekit-server/pkg/sfu/testutils"
)
@@ -2261,3 +2262,13 @@ func codecHeaderOf(b []byte) [codecmunger.MaxHeaderSize]byte {
copy(hdr[:], b)
return hdr
}
// WriteRTP holds the dependency descriptor in pacer scratch sized to pion's one
// byte extension profile payload cap, which has to be the inline size
// TranslationParams carries, or descriptors would take the heap copy fallback
func TestPacerScratchFitsInlineDependencyDescriptor(t *testing.T) {
p := &pacer.Packet{}
require.Len(t, p.HoldExtension(make([]byte, dd.MaxInlineExtensionSize)), dd.MaxInlineExtensionSize)
require.Nil(t, p.HoldExtension(make([]byte, dd.MaxInlineExtensionSize+1)))
}
+118 -57
View File
@@ -1,7 +1,7 @@
package sfu
import (
"math"
"math/bits"
"sync"
"time"
@@ -13,6 +13,12 @@ import (
const (
cHighForwardingLatency = 20 * time.Millisecond
cSkewFactor = 10
// forwardLatencyPercentile is the transit quantile reported as the node's
// forwarding latency and read by the overload controller. p90 tracks a broad
// slowdown but ignores the sparse tail (a few packets stalled on goroutine
// scheduling), which shedding cannot fix.
forwardLatencyPercentile = 0.90
)
const (
@@ -94,32 +100,86 @@ func (b *forwardSampleBuffer) takeDropped() uint64 {
return b.dropped.Swap(0)
}
// forwardSummary is a mergeable summary of forwarding transit over an interval.
// The sum of squares is kept in microseconds so it does not overflow int64.
type forwardSummary struct {
// forwardSummary is a mergeable histogram of forwarding transit over an
// interval. Each power-of-two octave [2^e, 2^(e+1)) us is split into
// forwardHistSub linear sub-buckets, and each bucket keeps the observed
// [min, max] of the samples in it. A percentile interpolates within the
// crossing bucket's observed range rather than its nominal edges, so the
// estimate never leaves the samples and is exact when a bucket's samples
// cluster -- which keeps it accurate near an overload threshold that falls
// mid-bucket, without needing threshold-aware boundaries. Two summaries merge
// by adding their buckets, so the percentile covers the whole report window,
// and a few stalled packets (e.g. from goroutine scheduling latency) cannot
// drag it the way a mean does.
const (
forwardHistSub = 8 // linear sub-buckets per octave
forwardHistOctaves = 27 // up to 2^27 us (~134 s)
forwardHistBuckets = forwardHistOctaves * forwardHistSub // 216
)
// bucketStat is one bucket: how many samples fell in it and their observed
// transit range in nanoseconds.
type bucketStat struct {
count int64
sumUs int64
sumSqUs int64
minNs int64
maxNs int64
}
func (s forwardSummary) addSample(transitNs int64) forwardSummary {
us := transitNs / 1000
if s.count == 0 {
return forwardSummary{count: 1, sumUs: us, sumSqUs: us * us, minNs: transitNs, maxNs: transitNs}
func (b *bucketStat) add(transitNs int64) {
if b.count == 0 {
b.minNs, b.maxNs = transitNs, transitNs
} else {
b.minNs = min(b.minNs, transitNs)
b.maxNs = max(b.maxNs, transitNs)
}
b.count++
}
func (b *bucketStat) mergeIn(o bucketStat) {
if o.count == 0 {
return
}
if b.count == 0 {
*b = o
return
}
b.count += o.count
b.minNs = min(b.minNs, o.minNs)
b.maxNs = max(b.maxNs, o.maxNs)
}
type forwardSummary struct {
count int64
minNs int64
maxNs int64
buckets [forwardHistBuckets]bucketStat
}
// forwardBucket returns the bucket index for a transit in nanoseconds: the
// octave floor(log2(us)) times forwardHistSub, plus the linear sub-bucket
// within the octave.
func forwardBucket(transitNs int64) int {
us := transitNs / 1000
if us <= 0 {
return 0
}
e := bits.Len64(uint64(us)) - 1 // floor(log2(us)), us >= 1 so e >= 0
if e >= forwardHistOctaves {
return forwardHistBuckets - 1
}
octave := int64(1) << e
return e*forwardHistSub + int((us-octave)*forwardHistSub/octave)
}
func (s *forwardSummary) addSample(transitNs int64) {
if s.count == 0 {
s.minNs, s.maxNs = transitNs, transitNs
} else {
s.minNs = min(s.minNs, transitNs)
s.maxNs = max(s.maxNs, transitNs)
}
s.count++
s.sumUs += us
s.sumSqUs += us * us
if transitNs < s.minNs {
s.minNs = transitNs
}
if transitNs > s.maxNs {
s.maxNs = transitNs
}
return s
s.buckets[forwardBucket(transitNs)].add(transitNs)
}
func (s forwardSummary) merge(o forwardSummary) forwardSummary {
@@ -129,35 +189,36 @@ func (s forwardSummary) merge(o forwardSummary) forwardSummary {
if s.count == 0 {
return o
}
return forwardSummary{
count: s.count + o.count,
sumUs: s.sumUs + o.sumUs,
sumSqUs: s.sumSqUs + o.sumSqUs,
minNs: min(s.minNs, o.minNs),
maxNs: max(s.maxNs, o.maxNs),
s.count += o.count
s.minNs = min(s.minNs, o.minNs)
s.maxNs = max(s.maxNs, o.maxNs)
for i := range s.buckets {
s.buckets[i].mergeIn(o.buckets[i])
}
return s
}
func (s forwardSummary) meanStdDev() (mean, stdDev time.Duration) {
// percentile returns the p-quantile (0..1) of transit, interpolated within the
// observed [min, max] of the bucket the quantile falls in.
func (s forwardSummary) percentile(p float64) time.Duration {
if s.count == 0 {
return 0, 0
return 0
}
meanUs := float64(s.sumUs) / float64(s.count)
mean = time.Duration(meanUs * float64(time.Microsecond))
if s.count < 2 {
return mean, 0
target := p * float64(s.count)
var cum float64
for i := range s.buckets {
b := s.buckets[i]
c := float64(b.count)
if c == 0 {
continue
}
// sample variance (divisor count-1)
m2 := float64(s.sumSqUs) - float64(s.sumUs)*meanUs
varUs2 := m2 / float64(s.count-1)
if varUs2 < 0 {
// floating point rounding can push a (near-zero) variance slightly negative
varUs2 = 0
if cum+c >= target {
lo, hi := float64(b.minNs), float64(b.maxNs)
return time.Duration(lo + (hi-lo)*(target-cum)/c)
}
stdDev = time.Duration(math.Sqrt(varUs2) * float64(time.Microsecond))
return mean, stdDev
cum += c
}
return time.Duration(s.maxNs)
}
type ForwardStats struct {
@@ -231,12 +292,12 @@ func (s *ForwardStats) run() {
// flush drains the buffered samples, observes each into the Prometheus
// histogram, and folds the interval summary into the window ring used for the
// latency/jitter gauges.
// latency gauge.
func (s *ForwardStats) flush() {
var summ forwardSummary
s.samples.drain(func(transitNs int64) {
prometheus.RecordForwardLatencySample(transitNs)
summ = summ.addSample(transitNs)
summ.addSample(transitNs)
})
s.lock.Lock()
@@ -274,33 +335,33 @@ func (s *ForwardStats) summarize(window time.Duration) forwardSummary {
return w
}
// GetStats returns the mean latency and jitter (std dev) of the forwarding
// transit over the most recent duration. The duration is rounded up to a whole
// number of summary intervals (the smallest bucket span that covers it). A
// duration <= 0, or one that meets/exceeds the report window, covers the full
// window.
func (s *ForwardStats) GetStats(duration time.Duration) (time.Duration, time.Duration) {
return s.summarize(duration).meanStdDev()
// GetStats returns the reported forwarding-latency percentile
// (forwardLatencyPercentile) over the most recent duration. The duration is
// rounded up to a whole number of summary intervals (the smallest bucket span
// that covers it). A duration <= 0, or one that meets/exceeds the report window,
// covers the full window.
func (s *ForwardStats) GetStats(duration time.Duration) time.Duration {
return s.summarize(duration).percentile(forwardLatencyPercentile)
}
func (s *ForwardStats) report() {
w := s.summarize(0)
latency, jitter := w.meanStdDev()
p90 := w.percentile(forwardLatencyPercentile)
if dropped := s.samples.takeDropped(); dropped > 0 {
logger.Warnw("forward stats sample buffer overflow", nil, "dropped", dropped)
}
if w.count > 0 && jitter > latency*cSkewFactor {
// a max far above p90 means a few packets stalled (e.g. goroutine scheduling
// latency) rather than a broad forwarding slowdown; p90 rides through it.
if w.count > 0 && w.maxNs > p90.Nanoseconds()*cSkewFactor {
logger.Infow(
"high jitter in forwarding path",
"high spread in forwarding path",
"lowest", time.Duration(w.minNs),
"highest", time.Duration(w.maxNs),
"count", w.count,
"latency", latency,
"jitter", jitter,
"p90", p90,
)
}
prometheus.RecordForwardJitter(uint32(jitter.Nanoseconds()))
prometheus.RecordForwardLatency(uint32(latency.Nanoseconds()))
prometheus.RecordForwardLatency(uint32(p90.Nanoseconds()))
}
+89 -44
View File
@@ -24,28 +24,39 @@ func initPrometheus(t *testing.T) {
// forwardSummary
// ---------------------------------------------------------------------------
// bucketSum totals a summary's per-bucket counts, independent of the bucketing
// scheme, so tests can assert samples landed without hard-coding bucket indices.
func bucketSum(s forwardSummary) int64 {
var n int64
for _, b := range s.buckets {
n += b.count
}
return n
}
func TestForwardSummary_AddSample(t *testing.T) {
var s forwardSummary
// empty summary
require.Equal(t, int64(0), s.count)
// microsecond-aligned transits so the /1000 truncation is exact
s = s.addSample(3000) // 3us
s = s.addSample(1000) // 1us
s = s.addSample(2000) // 2us
s.addSample(3000) // 3us
s.addSample(1000) // 1us
s.addSample(2000) // 2us
require.Equal(t, int64(3), s.count)
require.Equal(t, int64(1+2+3), s.sumUs)
require.Equal(t, int64(1+4+9), s.sumSqUs)
require.Equal(t, int64(1000), s.minNs)
require.Equal(t, int64(3000), s.maxNs)
require.Equal(t, s.count, bucketSum(s)) // every sample landed in a bucket
}
func TestForwardSummary_Merge(t *testing.T) {
var empty forwardSummary
a := forwardSummary{}.addSample(1000).addSample(2000)
b := forwardSummary{}.addSample(5000).addSample(3000)
var a, b forwardSummary
a.addSample(1000)
a.addSample(2000)
b.addSample(5000)
b.addSample(3000)
// merging with empty is identity, in both directions
require.Equal(t, a, a.merge(empty))
@@ -53,34 +64,72 @@ func TestForwardSummary_Merge(t *testing.T) {
m := a.merge(b)
require.Equal(t, int64(4), m.count)
require.Equal(t, a.sumUs+b.sumUs, m.sumUs)
require.Equal(t, a.sumSqUs+b.sumSqUs, m.sumSqUs)
require.Equal(t, int64(1000), m.minNs)
require.Equal(t, int64(5000), m.maxNs)
// merge sums the per-bucket counts
require.Equal(t, bucketSum(a)+bucketSum(b), bucketSum(m))
require.Equal(t, m.count, bucketSum(m))
}
func TestForwardSummary_MeanStdDev(t *testing.T) {
func TestForwardSummary_Percentile(t *testing.T) {
// empty -> zero
mean, stdDev := forwardSummary{}.meanStdDev()
require.Zero(t, mean)
require.Zero(t, stdDev)
require.Zero(t, forwardSummary{}.percentile(0.5))
// single sample -> mean set, stddev zero (needs >= 2 for variance)
mean, stdDev = forwardSummary{}.addSample(4000).meanStdDev()
require.Equal(t, 4*time.Microsecond, mean)
require.Zero(t, stdDev)
// half the samples fast (1us), half a slow tail (100us). A percentile is not
// dragged toward the tail the way the mean is -- why the reported metric is
// p90, not the mean.
var s forwardSummary
for i := 0; i < 5; i++ {
s.addSample(1000) // 1us
}
for i := 0; i < 5; i++ {
s.addSample(100_000) // 100us
}
require.Equal(t, int64(10), s.count)
// identical samples -> zero variance
s := forwardSummary{}.addSample(2000).addSample(2000).addSample(2000)
mean, stdDev = s.meanStdDev()
require.Equal(t, 2*time.Microsecond, mean)
require.Zero(t, stdDev)
// p50 lands in the fast cluster, unmoved by the 100us tail.
require.Equal(t, 1*time.Microsecond, s.percentile(0.5))
// p90 crosses into the slow cluster.
require.Equal(t, 100*time.Microsecond, s.percentile(0.9))
// known dataset [1us, 2us, 3us]: mean 2us, sample variance 1us^2 -> stddev 1us
s = forwardSummary{}.addSample(1000).addSample(2000).addSample(3000)
mean, stdDev = s.meanStdDev()
require.Equal(t, 2*time.Microsecond, mean)
require.InDelta(t, float64(time.Microsecond), float64(stdDev), float64(50*time.Nanosecond))
// a single sample reports exactly its latency, not the top edge of its bucket
// (nominal-edge interpolation would report the bucket's upper reach instead).
var single forwardSummary
single.addSample(int64(20 * time.Millisecond))
require.Equal(t, 20*time.Millisecond, single.percentile(0.9))
// identical samples share a bucket but must not invent intra-bucket spread.
var u forwardSummary
for i := 0; i < 8; i++ {
u.addSample(int64(2 * time.Millisecond))
}
require.Equal(t, 2*time.Millisecond, u.percentile(0.5))
require.Equal(t, 2*time.Millisecond, u.percentile(0.99))
}
func TestForwardSummary_ThresholdResolution(t *testing.T) {
// Nodes whose p90 packets cluster near a 300us overload threshold.
// Interpolating within each bucket's observed range reports a tight tail
// exactly, so each cluster lands on the correct side of 300us.
build := func(tailUs int64) forwardSummary {
var s forwardSummary
for i := 0; i < 850; i++ {
s.addSample(50 * int64(time.Microsecond))
}
for i := 0; i < 150; i++ {
s.addSample(tailUs * int64(time.Microsecond))
}
return s
}
require.Less(t, build(265).percentile(0.9), 300*time.Microsecond) // below -> no trip
require.Greater(t, build(310).percentile(0.9), 300*time.Microsecond) // just above -> trips
require.Greater(t, build(500).percentile(0.9), 300*time.Microsecond) // well above -> trips
// a tight tail is reported exactly, regardless of where it sits in the bucket.
require.Equal(t, 265*time.Microsecond, build(265).percentile(0.9))
require.Equal(t, 310*time.Microsecond, build(310).percentile(0.9))
require.Equal(t, 500*time.Microsecond, build(500).percentile(0.9))
}
// ---------------------------------------------------------------------------
@@ -284,29 +333,25 @@ func TestForwardStats_GetStats(t *testing.T) {
// 5 buckets, each covering one 100ms summary interval.
s := &ForwardStats{ring: make([]forwardSummary, 5), summaryInterval: 100 * time.Millisecond}
// fold five 100ms buckets, one sample each: 1ms, 2ms, 3ms, 4ms, 5ms.
for i := 1; i <= 5; i++ {
// fold five 100ms buckets, one sample each, descending 5ms..1ms so trailing
// windows have distinct maxima.
for i := 5; i >= 1; i-- {
s.Update(0, int64(i)*int64(time.Millisecond))
s.flush()
}
require.Equal(t, 5, s.ringLen)
// a duration <= 0 covers the whole window: mean of 1..5ms == 3ms.
latency, jitter := s.GetStats(0)
require.InDelta(t, float64(3*time.Millisecond), float64(latency), float64(50*time.Microsecond))
require.Greater(t, jitter, time.Duration(0))
// whole window {1..5ms}: p90 clamps to the observed max, 5ms.
require.Equal(t, 5*time.Millisecond, s.GetStats(0))
require.Equal(t, 5*time.Millisecond, s.GetStats(time.Second))
// a duration meeting/exceeding the window also covers it.
fullLatency, _ := s.GetStats(time.Second)
require.InDelta(t, float64(3*time.Millisecond), float64(fullLatency), float64(50*time.Microsecond))
// ~200ms covers only the two most recent buckets {2ms, 1ms}: a lower window
// than the full one, and above the single most-recent bucket.
require.Less(t, s.GetStats(200*time.Millisecond), 3*time.Millisecond)
require.Greater(t, s.GetStats(200*time.Millisecond), s.GetStats(time.Nanosecond))
// ~200ms rounds up to the two most recent buckets (4ms, 5ms): mean == 4.5ms.
shortLatency, _ := s.GetStats(200 * time.Millisecond)
require.InDelta(t, float64(4500*time.Microsecond), float64(shortLatency), float64(50*time.Microsecond))
// a sub-interval duration still yields at least the most recent bucket (5ms).
lastLatency, _ := s.GetStats(time.Nanosecond)
require.InDelta(t, float64(5*time.Millisecond), float64(lastLatency), float64(50*time.Microsecond))
// a sub-interval yields only the most recent bucket, ~1ms.
require.Equal(t, 1*time.Millisecond, s.GetStats(time.Nanosecond))
}
func TestForwardStats_Lifecycle(t *testing.T) {
+22
View File
@@ -15,6 +15,7 @@
package pacer
import (
"bytes"
"sync"
"testing"
@@ -24,6 +25,7 @@ import (
"github.com/livekit/protocol/logger"
"github.com/livekit/livekit-server/pkg/sfu/bwe"
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
"github.com/livekit/livekit-server/pkg/sfu/utils"
)
@@ -85,3 +87,23 @@ func TestSendPacketHeaderExtensionsNoAlloc(t *testing.T) {
require.Equal(t, 0.0, allocs, "allocations per SendPacket")
}
}
func TestHoldExtension(t *testing.T) {
p := &Packet{}
ext := []byte{1, 2, 3}
held := p.HoldExtension(ext)
require.Equal(t, ext, held)
require.Same(t, &p.extBuf[0], &held[0], "the extension has to be held in the packet's scratch")
ext[0] = 9
require.EqualValues(t, 1, held[0], "the held copy has to be independent of the caller's slice")
// exactly the one byte extension profile payload cap
exact := bytes.Repeat([]byte{7}, dd.MaxInlineExtensionSize)
held = p.HoldExtension(exact)
require.Equal(t, exact, held)
// one byte more does not fit
require.Nil(t, p.HoldExtension(bytes.Repeat([]byte{7}, dd.MaxInlineExtensionSize+1)))
}
+10
View File
@@ -19,6 +19,7 @@ import (
"time"
"github.com/livekit/livekit-server/pkg/sfu/ccutils"
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
)
@@ -59,6 +60,15 @@ type Packet struct {
// the Packet is owned by one send until SendPacket returns
absSendTimeBuf [3]byte
twccBuf [2]byte
extBuf [dd.MaxInlineExtensionSize]byte
}
// HoldExtension copies ext into scratch the header can point at until SendPacket returns, nil if it does not fit
func (p *Packet) HoldExtension(ext []byte) []byte {
if len(ext) > len(p.extBuf) {
return nil
}
return p.extBuf[:copy(p.extBuf[:], ext)]
}
type Pacer interface {
+18
View File
@@ -158,6 +158,21 @@ type ReceiverBase struct {
isClosed atomic.Bool
dropPayloadTypeMismatchCount atomic.Uint32
rtpObserver atomic.Pointer[rtpObserver]
}
type rtpObserver struct {
fn func(webrtc.RTPCodecParameters, *buffer.ExtPacket)
}
// SetRTPObserver installs a nonblocking consumer of incoming packets. The
// callback must copy anything retained after returning, as buffers are reused.
func (r *ReceiverBase) SetRTPObserver(fn func(webrtc.RTPCodecParameters, *buffer.ExtPacket)) {
if fn == nil {
r.rtpObserver.Store(nil)
} else {
r.rtpObserver.Store(&rtpObserver{fn})
}
}
func NewReceiverBase(params ReceiverBaseParams, trackInfo *livekit.TrackInfo, codecState ReceiverCodecState) *ReceiverBase {
@@ -965,6 +980,9 @@ func (r *ReceiverBase) forwardRTP(
continue
}
if observer := r.rtpObserver.Load(); observer != nil {
observer.fn(r.params.Codec, extPkt)
}
writeCount := sfuutils.BroadcastRTP(r.downTrackSpreader, extPkt, spatialLayer)
if rt := r.loadREDTransformer(); rt != nil {
writeCount += rt.ForwardRTP(extPkt, spatialLayer)
@@ -15,6 +15,7 @@
package dependencydescriptor
import (
"errors"
"fmt"
"math"
"strconv"
@@ -23,6 +24,10 @@ import (
// DependencyDescriptorExtension is a extension payload format in
// https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension
// ErrBufferTooSmall is returned by MarshalTo when the caller's storage cannot
// hold the marshaled extension.
var ErrBufferTooSmall = errors.New("dependency descriptor buffer too small")
func formatBitmask(b *uint32) string {
if b == nil {
return "-"
@@ -42,18 +47,48 @@ func (d *DependencyDescriptorExtension) Marshal() ([]byte, error) {
}
func (d *DependencyDescriptorExtension) MarshalWithActiveChains(activeChains uint32) ([]byte, error) {
writer, err := NewDependencyDescriptorWriter(nil, d.Structure, activeChains, d.Descriptor)
writer, size, err := d.newWriter(activeChains)
if err != nil {
return nil, err
}
buf := make([]byte, int(math.Ceil(float64(writer.ValueSizeBits())/8)))
writer.ResetBuf(buf)
if err = writer.Write(); err != nil {
buf := make([]byte, size)
writer = writer.withBuf(buf)
if err := writer.Write(); err != nil {
return nil, err
}
return buf, nil
}
// MarshalTo marshals into caller owned storage and returns the number of bytes
// written, or ErrBufferTooSmall, leaving buf untouched, if the extension does not fit.
func (d *DependencyDescriptorExtension) MarshalTo(buf []byte) (int, error) {
writer, size, err := d.newWriter(^uint32(0))
if err != nil {
return 0, err
}
if len(buf) < size {
// bare sentinel, key frames take this path and formatting an error there would allocate
return 0, ErrBufferTooSmall
}
writer = writer.withBuf(buf[:size])
if err := writer.Write(); err != nil {
return 0, err
}
return size, nil
}
// newWriter returns a writer for the extension, by value so that it stays on the
// caller's stack, along with the number of bytes the marshaled extension needs.
func (d *DependencyDescriptorExtension) newWriter(activeChains uint32) (DependencyDescriptorWriter, int, error) {
writer := newDependencyDescriptorWriter(nil, d.Structure, activeChains, d.Descriptor)
if err := writer.findBestTemplate(); err != nil {
return writer, 0, err
}
return writer, int(math.Ceil(float64(writer.ValueSizeBits()) / 8)), nil
}
func (d *DependencyDescriptorExtension) Unmarshal(buf []byte) (int, error) {
reader := NewDependencyDescriptorReader(buf, d.Structure, d.Descriptor)
return reader.Parse()
@@ -67,6 +102,9 @@ const (
MaxDecodeTargets = 32
MaxTemplates = 64
// MaxInlineExtensionSize is the inline storage the forwarding path and the pacer reserve for a marshaled extension, pion's one byte profile cap
MaxInlineExtensionSize = 16
AllChainsAreActive = uint32(0)
ExtensionURI = "https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension"
@@ -0,0 +1,247 @@
// Copyright 2026 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dependencydescriptor
import (
"encoding/hex"
"testing"
"github.com/stretchr/testify/require"
"github.com/livekit/livekit-server/pkg/sfu/utils"
)
// dependencyDescriptorMarshalFixture is a dependency descriptor captured from
// traffic. The fixture helper decodes its attached structure once, then returns
// a regular per-packet descriptor that references that structure.
const dependencyDescriptorMarshalFixture = "c1017280081485214eafffaaaa863cf0430c10c302afc0aaa0063c00430010c002a000a80006000040001d954926e082b04a0941b820ac1282503157f974000ca864330e222222eca8655304224230eca877530077004200ef008601df010d"
func newDependencyDescriptorMarshalFixture(tb testing.TB) *DependencyDescriptorExtension {
tb.Helper()
buf, err := hex.DecodeString(dependencyDescriptorMarshalFixture)
require.NoError(tb, err)
descriptor := DependencyDescriptor{}
parser := DependencyDescriptorExtension{Descriptor: &descriptor}
_, err = parser.Unmarshal(buf)
require.NoError(tb, err)
require.NotNil(tb, descriptor.AttachedStructure, "fixture did not contain a dependency structure")
structure := descriptor.AttachedStructure
descriptor.AttachedStructure = nil
descriptor.ActiveDecodeTargetsBitmask = nil
return &DependencyDescriptorExtension{
Descriptor: &descriptor,
Structure: structure,
}
}
func checkDependencyDescriptorMarshal(tb testing.TB, buf []byte, structure *FrameDependencyStructure, frameNumber uint16) {
tb.Helper()
require.NotEmpty(tb, buf, "marshal returned an empty dependency descriptor")
decoded := DependencyDescriptor{}
parser := DependencyDescriptorExtension{
Descriptor: &decoded,
Structure: structure,
}
_, err := parser.Unmarshal(buf)
require.NoError(tb, err)
require.Equal(tb, frameNumber, decoded.FrameNumber)
}
func TestDependencyDescriptorMarshalRoundTrip(t *testing.T) {
extension := newDependencyDescriptorMarshalFixture(t)
first, err := extension.Marshal()
require.NoError(t, err)
firstCopy := append([]byte(nil), first...)
checkDependencyDescriptorMarshal(t, first, extension.Structure, extension.Descriptor.FrameNumber)
extension.Descriptor.FrameNumber++
second, err := extension.Marshal()
require.NoError(t, err)
checkDependencyDescriptorMarshal(t, second, extension.Structure, extension.Descriptor.FrameNumber)
require.Equal(t, firstCopy, first, "a later marshal modified a previously returned buffer")
require.NotEqual(t, first, second, "different frame numbers produced identical descriptors")
}
func TestDependencyDescriptorMarshalTo(t *testing.T) {
extension := newDependencyDescriptorMarshalFixture(t)
// every template of the fixture structure, i. e. the per-packet descriptors
// the forwarding path marshals, has to match Marshal byte for byte and fit
// the inline size the forwarding path reserves
for i, template := range extension.Structure.Templates {
extension.Descriptor.FrameDependencies = template
extension.Descriptor.FrameNumber = uint16(i)
want, err := extension.Marshal()
require.NoError(t, err)
require.LessOrEqual(t, len(want), MaxInlineExtensionSize)
var scratch [MaxInlineExtensionSize]byte
n, err := extension.MarshalTo(scratch[:])
require.NoError(t, err)
require.Equal(t, want, scratch[:n])
checkDependencyDescriptorMarshal(t, scratch[:n], extension.Structure, uint16(i))
}
}
func TestDependencyDescriptorMarshalToBufferTooSmall(t *testing.T) {
extension := newDependencyDescriptorMarshalFixture(t)
want, err := extension.Marshal()
require.NoError(t, err)
_, err = extension.MarshalTo(make([]byte, len(want)-1))
require.ErrorIs(t, err, ErrBufferTooSmall)
n, err := extension.MarshalTo(make([]byte, len(want)))
require.NoError(t, err)
require.Equal(t, len(want), n)
// a descriptor carrying the full dependency structure does not fit inline
extension.Descriptor.AttachedStructure = extension.Structure
_, err = extension.MarshalTo(make([]byte, MaxInlineExtensionSize))
require.ErrorIs(t, err, ErrBufferTooSmall)
keyFrame, err := extension.Marshal()
require.NoError(t, err)
require.Greater(t, len(keyFrame), MaxInlineExtensionSize)
}
// TestDependencyDescriptorMarshalToLargerDescriptors covers the 8 to 16 byte
// band, where the active decode targets bitmask and custom frame dependencies
// land and where the sequencer's own inline copy already spills.
func TestDependencyDescriptorMarshalToLargerDescriptors(t *testing.T) {
extension := newDependencyDescriptorMarshalFixture(t)
bitmask := uint32(0x1ff)
// the widest per-packet descriptor of the fixture, with the bitmask attached
widest := 0
for _, template := range extension.Structure.Templates {
extension.Descriptor.FrameDependencies = template
extension.Descriptor.ActiveDecodeTargetsBitmask = &bitmask
want, err := extension.Marshal()
require.NoError(t, err)
widest = max(widest, len(want))
var scratch [MaxInlineExtensionSize]byte
n, err := extension.MarshalTo(scratch[:])
require.NoError(t, err)
require.Equal(t, want, scratch[:n])
}
require.GreaterOrEqual(t, widest, 8)
// custom frame diffs and chain diffs, i. e. a frame that matches no template
custom := extension.Structure.Templates[0].Clone()
custom.FrameDiffs = []int{1, 300, 4000}
for i := range custom.ChainDiffs {
custom.ChainDiffs[i] = 200 + i
}
extension.Descriptor.FrameDependencies = custom
extension.Descriptor.ActiveDecodeTargetsBitmask = nil
want, err := extension.Marshal()
require.NoError(t, err)
require.GreaterOrEqual(t, len(want), 8)
require.LessOrEqual(t, len(want), MaxInlineExtensionSize)
var scratch [MaxInlineExtensionSize]byte
n, err := extension.MarshalTo(scratch[:])
require.NoError(t, err)
require.Equal(t, want, scratch[:n])
checkDependencyDescriptorMarshal(t, scratch[:n], extension.Structure, extension.Descriptor.FrameNumber)
}
func TestDependencyDescriptorMarshalAllocs(t *testing.T) {
if utils.RaceEnabled {
// the race detector perturbs allocation counts, see #4874
t.Skip("allocation count is not meaningful under the race detector")
}
extension := newDependencyDescriptorMarshalFixture(t)
var (
scratch [MaxInlineExtensionSize]byte
n int
err error
)
allocs := testing.AllocsPerRun(100, func() {
n, err = extension.MarshalTo(scratch[:])
})
require.NoError(t, err)
require.NotZero(t, n)
require.Zero(t, allocs, "a per-packet descriptor has to marshal without allocating")
// a key frame descriptor carries the full dependency structure, does not fit
// the inline scratch and spills to exactly one allocation, the Marshal slice
extension.Descriptor.AttachedStructure = extension.Structure
var buf []byte
allocs = testing.AllocsPerRun(100, func() {
if n, err = extension.MarshalTo(scratch[:]); err != nil {
buf, err = extension.Marshal()
}
})
require.NoError(t, err)
require.Greater(t, len(buf), MaxInlineExtensionSize)
require.Equal(t, float64(1), allocs, "the spill path has to allocate only the Marshal slice")
}
func BenchmarkDependencyDescriptorMarshal(b *testing.B) {
extension := newDependencyDescriptorMarshalFixture(b)
frameNumber := extension.Descriptor.FrameNumber
b.ReportAllocs()
var buf []byte
for b.Loop() {
extension.Descriptor.FrameNumber = frameNumber
frameNumber++
var err error
buf, err = extension.Marshal()
require.NoError(b, err)
}
checkDependencyDescriptorMarshal(b, buf, extension.Structure, frameNumber-1)
}
func BenchmarkDependencyDescriptorMarshalTo(b *testing.B) {
extension := newDependencyDescriptorMarshalFixture(b)
frameNumber := extension.Descriptor.FrameNumber
b.ReportAllocs()
var (
scratch [MaxInlineExtensionSize]byte
n int
)
for b.Loop() {
extension.Descriptor.FrameNumber = frameNumber
frameNumber++
var err error
n, err = extension.MarshalTo(scratch[:])
require.NoError(b, err)
}
checkDependencyDescriptorMarshal(b, scratch[:n], extension.Structure, frameNumber-1)
}
@@ -33,23 +33,28 @@ type DependencyDescriptorWriter struct {
descriptor *DependencyDescriptor
structure *FrameDependencyStructure
activeChains uint32
writer *BitStreamWriter
writer BitStreamWriter
bestTemplate TemplateMatch
}
func NewDependencyDescriptorWriter(buf []byte, structure *FrameDependencyStructure, activeChains uint32, descriptor *DependencyDescriptor) (*DependencyDescriptorWriter, error) {
writer := NewBitStreamWriter(buf)
w := &DependencyDescriptorWriter{
func newDependencyDescriptorWriter(buf []byte, structure *FrameDependencyStructure, activeChains uint32, descriptor *DependencyDescriptor) DependencyDescriptorWriter {
return DependencyDescriptorWriter{
descriptor: descriptor,
structure: structure,
activeChains: activeChains,
writer: writer,
writer: BitStreamWriter{buf: buf},
}
return w, w.findBestTemplate()
}
func (w *DependencyDescriptorWriter) ResetBuf(buf []byte) {
w.writer = NewBitStreamWriter(buf)
func NewDependencyDescriptorWriter(buf []byte, structure *FrameDependencyStructure, activeChains uint32, descriptor *DependencyDescriptor) (*DependencyDescriptorWriter, error) {
w := newDependencyDescriptorWriter(buf, structure, activeChains, descriptor)
return &w, w.findBestTemplate()
}
// withBuf returns a copy of the writer that writes into buf, value receiver so a caller owned buffer does not escape
func (w DependencyDescriptorWriter) withBuf(buf []byte) DependencyDescriptorWriter {
w.writer = BitStreamWriter{buf: buf}
return w
}
func (w *DependencyDescriptorWriter) Write() error {
@@ -46,6 +46,10 @@ type DependencyDescriptor struct {
decodeTargets []*DecodeTarget
fnWrapper FrameNumberWrapper
// per packet copy of the descriptor when the frame number or the active
// decode targets are rewritten, owned here so it does not allocate
ddClone dede.DependencyDescriptor
restartGeneration int
}
@@ -322,8 +326,8 @@ func (d *DependencyDescriptor) Select(extPkt *buffer.ExtPacket, _layer int32) (r
unWrapFn := uint16(d.fnWrapper.UpdateAndGet(extFrameNum, ddwdt.StructureUpdated))
var ddClone *dede.DependencyDescriptor
if unWrapFn != dd.FrameNumber {
clone := *dd
ddClone = &clone
d.ddClone = *dd
ddClone = &d.ddClone
ddClone.FrameNumber = unWrapFn
ddExtension.Descriptor = ddClone
}
@@ -333,8 +337,8 @@ func (d *DependencyDescriptor) Select(extPkt *buffer.ExtPacket, _layer int32) (r
if ddClone == nil {
// clone and override activebitmask
// DD-TODO: if the packet that contains the bitmask is acknowledged by RR, then we don't need it until it changed.
clone := *dd
ddClone = &clone
d.ddClone = *dd
ddClone = &d.ddClone
ddExtension.Descriptor = ddClone
}
ddClone.ActiveDecodeTargetsBitmask = d.activeDecodeTargetsBitmask
@@ -355,11 +359,9 @@ func (d *DependencyDescriptor) Select(extPkt *buffer.ExtPacket, _layer int32) (r
"stack", string(debug.Stack()))
}
}()
bytes, err := ddExtension.Marshal()
if err != nil {
if err := result.marshalDependencyDescriptorExtension(ddExtension); err != nil {
d.logger.Warnw("error marshalling dependency descriptor extension", err)
} else {
result.DependencyDescriptorExtension = bytes
ddMarshaled = true
}
}()
@@ -15,6 +15,7 @@
package videolayerselector
import (
"encoding/hex"
"slices"
"testing"
@@ -23,6 +24,7 @@ import (
"github.com/livekit/livekit-server/pkg/sfu/buffer"
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
"github.com/livekit/livekit-server/pkg/sfu/utils"
"github.com/livekit/protocol/logger"
)
@@ -409,3 +411,71 @@ func createDDFrames(maxLayer buffer.VideoLayer, startFrameNumber uint16) []*buff
return frames
}
// same capture as the dependency descriptor package's marshal fixture, an L3T3
// key frame descriptor with the full dependency structure attached
const dependencyDescriptorFixture = "c1017280081485214eafffaaaa863cf0430c10c302afc0aaa0063c00430010c002a000a80006000040001d954926e082b04a0941b820ac1282503157f974000ca864330e222222eca8655304224230eca877530077004200ef008601df010d"
func TestVideoLayerSelectorResultDependencyDescriptor(t *testing.T) {
raw, err := hex.DecodeString(dependencyDescriptorFixture)
require.NoError(t, err)
descriptor := dd.DependencyDescriptor{}
_, err = (&dd.DependencyDescriptorExtension{Descriptor: &descriptor}).Unmarshal(raw)
require.NoError(t, err)
require.NotNil(t, descriptor.AttachedStructure)
structure := descriptor.AttachedStructure
// a key frame descriptor carries the full structure and spills to the heap
keyFrame := VideoLayerSelectorResult{}
require.NoError(t, keyFrame.marshalDependencyDescriptorExtension(&dd.DependencyDescriptorExtension{
Descriptor: &descriptor,
Structure: structure,
}))
require.Zero(t, keyFrame.DDBytesLen)
require.Greater(t, len(keyFrame.DDBytesSpill), dd.MaxInlineExtensionSize)
// a per-packet descriptor is held inline, byte for byte what Marshal returns
perPacket := descriptor
perPacket.AttachedStructure = nil
perPacket.ActiveDecodeTargetsBitmask = nil
ddExtension := &dd.DependencyDescriptorExtension{Descriptor: &perPacket, Structure: structure}
result := VideoLayerSelectorResult{}
require.NoError(t, result.marshalDependencyDescriptorExtension(ddExtension))
require.Nil(t, result.DDBytesSpill)
require.NotZero(t, result.DDBytesLen)
require.LessOrEqual(t, result.DDBytesLen, dd.MaxInlineExtensionSize)
want, err := ddExtension.Marshal()
require.NoError(t, err)
require.Equal(t, want, result.DDBytes[:result.DDBytesLen])
}
func TestDependencyDescriptorSelectAllocations(t *testing.T) {
for _, rewriteFrameNumber := range []bool{false, true} {
selector := NewDependencyDescriptor(logger.GetLogger())
selector.SetTarget(buffer.VideoLayer{Spatial: 0, Temporal: 0})
selector.SetRequestSpatial(0)
frames := createDDFrames(buffer.VideoLayer{Spatial: 0, Temporal: 0}, 100)
require.True(t, selector.Select(frames[0], 0).IsSelected)
require.NotNil(t, selector.activeDecodeTargetsBitmask)
if rewriteFrameNumber {
selector.fnWrapper.offset = 6000
}
packet := frames[1]
packet.DependencyDescriptor.ExtFrameNum--
packet.DependencyDescriptor.Descriptor.FrameNumber--
selected := true
allocs := testing.AllocsPerRun(1000, func() {
packet.DependencyDescriptor.ExtFrameNum++
packet.DependencyDescriptor.Descriptor.FrameNumber++
selected = selected && selector.Select(packet, 0).IsSelected
})
require.True(t, selected)
if !utils.RaceEnabled {
require.Equal(t, 0.0, allocs, "allocations per selected packet, rewriteFrameNumber=%v", rewriteFrameNumber)
}
}
}
@@ -15,7 +15,10 @@
package videolayerselector
import (
"errors"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
dd "github.com/livekit/livekit-server/pkg/sfu/rtpextension/dependencydescriptor"
"github.com/livekit/livekit-server/pkg/sfu/videolayerselector/temporallayerselector"
"github.com/livekit/protocol/logger"
)
@@ -26,7 +29,29 @@ type VideoLayerSelectorResult struct {
IsSwitching bool
IsResuming bool
RTPMarker bool
DependencyDescriptorExtension []byte
// marshaled dependency descriptor extension, held inline when it fits and
// spilled to the heap when it does not, the way the sequencer keeps its copy
DDBytes [dd.MaxInlineExtensionSize]byte
DDBytesLen int
DDBytesSpill []byte
}
// marshalDependencyDescriptorExtension marshals ddExtension into the result,
// inline if it fits and on the heap otherwise.
func (v *VideoLayerSelectorResult) marshalDependencyDescriptorExtension(ddExtension *dd.DependencyDescriptorExtension) error {
ddBytesLen, err := ddExtension.MarshalTo(v.DDBytes[:])
if err == nil {
v.DDBytesLen = ddBytesLen
return nil
}
if !errors.Is(err, dd.ErrBufferTooSmall) {
return err
}
// descriptors carrying the full dependency structure do not fit inline
v.DDBytesSpill, err = ddExtension.Marshal()
return err
}
type VideoLayerSelector interface {
+181
View File
@@ -0,0 +1,181 @@
// 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"
}
+636
View File
@@ -0,0 +1,636 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"errors"
"fmt"
"math"
"sort"
"sync/atomic"
"time"
)
type RTPInput struct {
Sequence uint16
Timestamp, SSRC uint32
Payload []byte
}
type Input struct {
packets chan RTPInput
closed atomic.Bool
dropped atomic.Uint64
received atomic.Uint64
}
// Push never waits for the audio worker. The SFU's packet buffer is reused, so
// the payload must be copied before returning from its observer callback.
func (i *Input) Push(p RTPInput) {
if i.closed.Load() || len(p.Payload) == 0 || len(p.Payload) > 1500 {
return
}
p.Payload = append([]byte(nil), p.Payload...)
i.received.Add(1)
select {
case i.packets <- p:
return
default:
}
select {
case <-i.packets:
i.dropped.Add(1)
default:
}
select {
case i.packets <- p:
default:
i.dropped.Add(1)
}
}
// PrimaryRED extracts the primary payload of RFC 2198. Redundant blocks are
// skipped here; Opus in-band FEC is still usable by the playout buffer.
func PrimaryRED(payload []byte) ([]byte, error) {
offset, skip := 0, 0
for {
if offset >= len(payload) {
return nil, errors.New("truncated RED header")
}
if payload[offset]&0x80 == 0 {
offset++
break
}
if offset+4 > len(payload) {
return nil, errors.New("truncated RED block")
}
skip += int(payload[offset+2]&3)<<8 | int(payload[offset+3])
offset += 4
}
if offset+skip >= len(payload) {
return nil, errors.New("truncated RED primary")
}
return payload[offset+skip:], nil
}
type source struct {
id, track string
in *Input
decoder *Decoder
opus *Opus
queue map[int64]RTPInput
anchor uint32
ssrc uint32
started bool
ready time.Time
expected int64
pcm []float32
block [BlockSamples]float32
plc uint64
retiring bool
fade float64
fadeStep float64
remaining int
latePackets uint64
rebuffers uint64
decodeErrors uint64
lateStreak int
lastLate int64
}
func (s *source) reset(p RTPInput, now time.Time, jitter time.Duration) {
s.anchor = p.Timestamp
s.ssrc = p.SSRC
s.expected = 0
s.ready = now.Add(jitter)
s.started = true
clear(s.queue)
s.pcm = nil
s.lateStreak = 0
s.decoder.Close()
var err error
s.decoder, err = s.opus.NewDecoder()
if err != nil {
s.decodeErrors++
}
}
func (s *source) read(now time.Time, jitter time.Duration) []float32 {
clear(s.block[:])
// Rebase before the signed 32-bit timestamp delta can overflow in long
// sessions. Decoder state and buffered PCM remain continuous.
if s.expected > 1<<30 {
offset := s.expected
s.anchor += uint32(offset)
s.expected = 0
s.lastLate -= offset
queue := make(map[int64]RTPInput, len(s.queue))
for timestamp, packet := range s.queue {
queue[timestamp-offset] = packet
}
s.queue = queue
}
for n := 0; n < 64; n++ {
select {
case p := <-s.in.packets:
if samples := s.opus.Samples(p.Payload); samples < 120 || samples > 5760 {
s.decodeErrors++
continue
}
if !s.started || p.SSRC != s.ssrc {
s.reset(p, now, jitter)
}
t := int64(int32(p.Timestamp - s.anchor))
if t-s.expected > SampleRate*2 || t-s.expected < -SampleRate*2 {
s.reset(p, now, jitter)
t = 0
}
if now.Before(s.ready) && t < s.expected {
s.expected = t
}
if t < s.expected {
s.latePackets++
// After a burst of delay (or clock drift), every new packet may
// be late by the same amount. Dropping them forever locks the
// decoder into PLC despite an otherwise healthy incoming stream.
// Three advancing late packets with no future data trigger a
// new playout anchor. Keep Opus state; rebuild the jitter reserve.
if len(s.queue) == 0 && (s.lateStreak == 0 || t > s.lastLate) {
s.lateStreak++
s.lastLate = t
}
if s.lateStreak < 3 {
continue
}
s.expected = t
s.ready = now.Add(jitter)
s.pcm = nil
clear(s.queue)
s.rebuffers++
}
s.lateStreak = 0
if t >= s.expected && len(s.queue) < 96 {
s.queue[t] = p
}
default:
n = 64
}
}
if !s.started || now.Before(s.ready) || s.decoder == nil {
return s.block[:]
}
for len(s.pcm) < BlockSamples {
var pcm []float32
var err error
if p, ok := s.queue[s.expected]; ok {
delete(s.queue, s.expected)
pcm, err = s.decoder.Decode(p.Payload, 5760, false)
} else {
// Attempt in-band FEC only when the following packet fits the gap.
var next int64 = -1
for t := range s.queue {
if t > s.expected && (next < 0 || t < next) {
next = t
}
}
gap := next - s.expected
if next >= 0 && gap >= 120 && gap <= 5760 && gap%120 == 0 && s.opus.Samples(s.queue[next].Payload) == int(gap) {
pcm, err = s.decoder.Decode(s.queue[next].Payload, int(gap), true)
} else {
pcm, err = s.decoder.Decode(nil, BlockSamples, false)
}
s.plc++
}
if err != nil || len(pcm) == 0 {
s.decodeErrors++
pcm = make([]float32, BlockSamples)
}
s.expected += int64(len(pcm))
s.pcm = append(s.pcm, pcm...)
for t := range s.queue {
if t < s.expected {
delete(s.queue, t)
}
}
}
copy(s.block[:], s.pcm[:BlockSamples])
s.pcm = s.pcm[BlockSamples:]
return s.block[:]
}
type OutputFunc func(payload []byte, timestamp uint32) error
type listener struct {
id string
encoder *Encoder
mixer *Mixer
output OutputFunc
pcm []float32
block [2 * BlockSamples]float32
}
type Stats struct {
AdaptiveEnabled bool
QualityLevel int
LoadPressure float64
QualityTransitions uint64
PoseInterval time.Duration
ActiveObstacles int
EffectiveHRTF string
HRTFEnabled bool
HRTFPairs int
HRTFErrors uint64
LatePackets, Rebuffers, DecodeErrors uint64
SceneRevision uint64
Obstacles int
OcclusionEnabled bool
TickDuration, MaxTickDuration time.Duration
MatrixCalculations uint64
InputPeak, OutputPeak float64
Sources, Listeners int
Poses int
ReceivedPackets uint64
QueueDrops, ConcealedFrames, MissedTicks, OutputErrors uint64
}
type Engine struct {
config Config
opus *Opus
Poses *PoseStore
commands chan func()
stop chan struct{}
done chan struct{}
stopped atomic.Bool
sources map[string]*source
listeners map[string]*listener
stats Stats
matrix *GainMatrix
scene *CompiledScene
hrtf *HRTFRenderer
hrtfEnabled bool
adaptive adaptiveController
geometryDirty bool
}
func NewEngine(c Config) (*Engine, error) {
c = c.Defaults()
if err := c.Validate(); err != nil {
return nil, err
}
opus, err := LoadOpus(c.Library)
if err != nil {
return nil, err
}
e := &Engine{config: c, opus: opus, Poses: NewPoseStore(), commands: make(chan func(), 64), stop: make(chan struct{}), done: make(chan struct{}), sources: make(map[string]*source), listeners: make(map[string]*listener), matrix: NewGainMatrix(c)}
if c.HRTF.Enabled {
e.hrtf, err = NewHRTFRenderer(c.HRTF)
if err != nil {
return nil, err
}
e.hrtfEnabled = true
}
e.adaptive = adaptiveController{config: c.Adaptive, enabled: c.Adaptive.Enabled}
go e.run()
return e, nil
}
func (e *Engine) command(f func()) error {
if e.stopped.Load() {
return errors.New("spatial audio engine closed")
}
select {
case e.commands <- f:
return nil
case <-e.done:
return errors.New("spatial audio engine closed")
}
}
// ApplyScene validates a complete immutable snapshot before queuing it. A bad
// or old revision cannot partially replace the previous room geometry.
func (e *Engine) ApplyScene(payload []byte) (uint64, error) {
scene, err := ParseScene(payload, e.config.Occlusion.MaxObjects)
if err != nil {
return 0, err
}
if !e.config.Occlusion.Enabled && (scene.Enabled || len(scene.Objects) > 0) {
return scene.Revision, errors.New("occlusion disabled in server configuration")
}
if scene.HRTF != nil && *scene.HRTF && e.hrtf == nil {
return scene.Revision, errors.New("HRTF disabled in server configuration")
}
result := make(chan error, 1)
if err = e.command(func() {
if scene.Adaptive != nil && *scene.Adaptive && !e.config.Adaptive.Enabled {
result <- errors.New("adaptive quality disabled in server configuration")
return
}
if e.scene != nil && scene.Revision <= e.scene.Revision {
result <- errors.New("scene revision must increase")
return
}
e.scene = scene
if scene.Adaptive != nil {
e.adaptive.setEnabled(*scene.Adaptive)
}
if scene.HRTF != nil {
e.hrtfEnabled = *scene.HRTF
}
e.matrix.SetScene(scene)
e.matrix.SetMinPriority(e.adaptive.minWallPriority())
e.geometryDirty = true
result <- nil
}); err != nil {
return scene.Revision, err
}
select {
case err := <-result:
return scene.Revision, err
case <-e.done:
return scene.Revision, errors.New("engine closed")
}
}
func (e *Engine) AddListener(id string, output OutputFunc) error {
result := make(chan error, 1)
if err := e.command(func() {
if _, ok := e.listeners[id]; ok {
result <- nil
return
}
if len(e.listeners) >= e.config.MaxParticipants {
result <- errors.New("spatial participant limit reached")
return
}
enc, err := e.opus.NewEncoder(2, e.config.Bitrate)
if err == nil {
mixer := NewMixer(e.config)
mixer.hrtf = e.hrtf
e.listeners[id] = &listener{id: id, encoder: enc, mixer: mixer, output: output}
}
result <- err
}); err != nil {
return err
}
select {
case err := <-result:
return err
case <-e.done:
return errors.New("engine closed")
}
}
func (e *Engine) AddSource(id, track string) (*Input, error) {
result := make(chan struct {
input *Input
err error
}, 1)
if err := e.command(func() {
if _, exists := e.sources[id]; !exists && len(e.sources) >= e.config.MaxParticipants {
// A participant may enter immediately after another has left. Do
// not let a short retiring tail consume its source capacity.
for sourceID, s := range e.sources {
if s.retiring {
e.disposeSource(s)
delete(e.sources, sourceID)
}
}
}
if _, exists := e.sources[id]; !exists && len(e.sources) >= e.config.MaxParticipants {
result <- struct {
input *Input
err error
}{nil, errors.New("spatial source limit reached")}
return
}
if old := e.sources[id]; old != nil {
e.disposeSource(old)
delete(e.sources, id)
}
dec, err := e.opus.NewDecoder()
var input *Input
if err == nil {
input = &Input{packets: make(chan RTPInput, 64)}
e.sources[id] = &source{id: id, track: track, in: input, decoder: dec, opus: e.opus, queue: make(map[int64]RTPInput)}
}
result <- struct {
input *Input
err error
}{input, err}
}); err != nil {
return nil, err
}
select {
case r := <-result:
return r.input, r.err
case <-e.done:
return nil, errors.New("engine closed")
}
}
func (e *Engine) RemoveSource(id, track string) {
_ = e.command(func() {
if s := e.sources[id]; s != nil && s.track == track {
e.retireSource(s)
}
})
}
func (e *Engine) RemoveParticipant(id string) {
e.Poses.Remove(id)
_ = e.command(func() {
if s := e.sources[id]; s != nil {
e.retireSource(s)
}
if l := e.listeners[id]; l != nil {
l.mixer.Close()
l.encoder.Close()
delete(e.listeners, id)
}
})
}
// Preserve decoder continuity briefly after unpublishing. PLC supplies the
// tail while an envelope fades it out; the input accepts no new packets.
func (e *Engine) retireSource(s *source) {
if s.retiring {
return
}
s.in.closed.Store(true)
s.retiring = true
s.fade = 1
s.fadeStep = math.Exp(-1 / (SampleRate * float64(e.config.SmoothingMs) / 1000))
s.remaining = 5 * e.config.SmoothingMs * SampleRate / 1000
clear(s.queue)
for {
select {
case <-s.in.packets:
default:
return
}
}
}
func (e *Engine) disposeSource(s *source) {
s.in.closed.Store(true)
s.decoder.Close()
e.stats.ReceivedPackets += s.in.received.Load()
e.stats.QueueDrops += s.in.dropped.Load()
e.stats.ConcealedFrames += s.plc
e.stats.LatePackets += s.latePackets
e.stats.Rebuffers += s.rebuffers
e.stats.DecodeErrors += s.decodeErrors
}
func (e *Engine) SnapshotStats() Stats {
result := make(chan Stats, 1)
if e.command(func() {
s := e.stats
s.AdaptiveEnabled = e.adaptive.enabled
s.QualityLevel = e.adaptive.level
s.LoadPressure = e.adaptive.pressure
s.QualityTransitions = e.adaptive.transitions
s.PoseInterval = e.adaptive.poseInterval()
s.ActiveObstacles = e.scene.activeObjects(e.adaptive.minWallPriority())
s.EffectiveHRTF = e.adaptive.hrtfMode(e.hrtfEnabled, e.config.HRTF.Interpolation)
s.HRTFEnabled = e.hrtfEnabled
if e.scene != nil {
s.SceneRevision = e.scene.Revision
s.Obstacles = len(e.scene.Objects)
s.OcclusionEnabled = e.scene.Enabled
}
s.MatrixCalculations = e.matrix.Calculations()
s.Sources = len(e.sources)
s.Listeners = len(e.listeners)
s.Poses = len(e.Poses.Snapshot(time.Now(), e.config.PoseTimeout()))
for _, src := range e.sources {
s.ReceivedPackets += src.in.received.Load()
s.QueueDrops += src.in.dropped.Load()
s.ConcealedFrames += src.plc
s.LatePackets += src.latePackets
s.Rebuffers += src.rebuffers
s.DecodeErrors += src.decodeErrors
for _, v := range src.block {
s.InputPeak = math.Max(s.InputPeak, math.Abs(float64(v)))
}
}
for _, l := range e.listeners {
s.HRTFPairs += len(l.mixer.pairs)
for _, v := range l.block {
s.OutputPeak = math.Max(s.OutputPeak, math.Abs(float64(v)))
}
}
result <- s
}) != nil {
return Stats{}
}
select {
case s := <-result:
return s
case <-e.done:
return Stats{}
}
}
func (e *Engine) Close() {
if !e.stopped.Swap(true) {
close(e.stop)
}
<-e.done
}
func (e *Engine) run() {
defer forgetSpatialLoad(e)
defer close(e.done)
defer func() {
for _, s := range e.sources {
s.in.closed.Store(true)
s.decoder.Close()
}
for _, l := range e.listeners {
l.mixer.Close()
l.encoder.Close()
}
e.hrtf.Close()
}()
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
start := time.Now()
var last int64
var nextGeometry time.Time
var spatialPoses map[string]Pose
for {
select {
case f := <-e.commands:
f()
case <-e.stop:
return
case now := <-ticker.C:
step := now.Sub(start).Milliseconds() / 10
if step <= last {
continue
}
if step-last > 1 {
e.stats.MissedTicks += uint64(step - last - 1)
for _, l := range e.listeners {
l.pcm = nil
}
}
missed := uint64(max(step-last-1, 0))
last = step
tickStarted := time.Now()
// Pose expiration must not wait for the next geometry update.
fresh := e.Poses.Snapshot(time.Now(), e.config.PoseTimeout())
for id := range spatialPoses {
if _, exists := fresh[id]; !exists {
e.geometryDirty = true
}
}
if e.geometryDirty || !now.Before(nextGeometry) {
spatialPoses = fresh
e.matrix.Update(spatialPoses)
e.geometryDirty = false
nextGeometry = now.Add(e.adaptive.poseInterval())
}
hrtfMode := e.adaptive.hrtfMode(e.hrtfEnabled, e.config.HRTF.Interpolation)
pcm := make(map[string][]float32, len(e.sources))
ids := make([]string, 0, len(e.sources))
for id := range e.sources {
if s := e.sources[id]; s.retiring && s.remaining <= 0 {
e.disposeSource(s)
delete(e.sources, id)
continue
}
ids = append(ids, id)
}
sort.Strings(ids)
for _, id := range ids {
s := e.sources[id]
block := s.read(now, time.Duration(e.config.JitterMs)*time.Millisecond)
if s.retiring {
for n := range block {
s.fade *= s.fadeStep
block[n] *= float32(s.fade)
}
s.remaining -= BlockSamples
}
pcm[id] = block
}
for _, l := range e.listeners {
l.mixer.hrtfNearest = hrtfMode == "nearest"
e.stats.HRTFErrors += l.mixer.MixSpatial(l.id, spatialPoses, e.matrix.Row(l.id), pcm, l.block[:], hrtfMode != "off")
l.pcm = append(l.pcm, l.block[:]...)
if len(l.pcm) < 2*PacketSamples {
continue
}
packet, err := l.encoder.Encode(l.pcm[:2*PacketSamples])
l.pcm = l.pcm[2*PacketSamples:]
if err == nil {
err = l.output(packet, uint32((step-2)*BlockSamples))
}
if err != nil {
e.stats.OutputErrors++
}
}
e.stats.TickDuration = time.Since(tickStarted)
if e.stats.TickDuration > e.stats.MaxTickDuration {
e.stats.MaxTickDuration = e.stats.TickDuration
}
if e.adaptive.observe(e, time.Now(), e.stats.TickDuration, missed) {
e.matrix.SetMinPriority(e.adaptive.minWallPriority())
e.geometryDirty = true
}
}
}
}
func (e *Engine) String() string {
s := e.SnapshotStats()
return fmt.Sprintf("sources=%d listeners=%d poses=%d received=%d input_peak=%.4f output_peak=%.4f dropped=%d concealed=%d late=%d rebuffers=%d decode_errors=%d missed=%d output_errors=%d matrix_calculations=%d tick=%s max_tick=%s occlusion=%t obstacles=%d scene_revision=%d hrtf=%t hrtf_pairs=%d hrtf_errors=%d adaptive=%t quality_level=%d load_pressure=%.3f pose_interval=%s active_obstacles=%d effective_hrtf=%s quality_transitions=%d", s.Sources, s.Listeners, s.Poses, s.ReceivedPackets, s.InputPeak, s.OutputPeak, s.QueueDrops, s.ConcealedFrames, s.LatePackets, s.Rebuffers, s.DecodeErrors, s.MissedTicks, s.OutputErrors, s.MatrixCalculations, s.TickDuration, s.MaxTickDuration, s.OcclusionEnabled, s.Obstacles, s.SceneRevision, s.HRTFEnabled, s.HRTFPairs, s.HRTFErrors, s.AdaptiveEnabled, s.QualityLevel, s.LoadPressure, s.PoseInterval, s.ActiveObstacles, s.EffectiveHRTF, s.QualityTransitions)
}
+130
View File
@@ -0,0 +1,130 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"fmt"
"github.com/ebitengine/purego"
"math"
"path/filepath"
"runtime"
"sync"
)
type HRTFConfig struct {
Enabled bool `yaml:"enabled,omitempty"`
Library string `yaml:"library,omitempty"`
Interpolation string `yaml:"interpolation,omitempty"`
}
type hrtfAPI struct {
create func(int32, int32, *uintptr) int32
destroy func(uintptr)
pairCreate func(uintptr, *uintptr) int32
pairDestroy func(uintptr)
apply func(uintptr, *float32, *float32, *float32, int32) int32
}
var hrtfLibraries = struct {
sync.Mutex
libraries map[string]*hrtfAPI
}{libraries: make(map[string]*hrtfAPI)}
type HRTFRenderer struct {
api *hrtfAPI
state uintptr
interpolation int32
}
type binauralPair struct {
renderer *HRTFRenderer
state uintptr
amplitude float64
direction [3]float32
output [2 * BlockSamples]float32
interpolation int32
}
func NewHRTFRenderer(c HRTFConfig) (renderer *HRTFRenderer, err error) {
if c.Library == "" {
return nil, fmt.Errorf("hrtf.library must name the native Steam Audio bridge")
}
path, err := filepath.Abs(c.Library)
if err != nil {
return nil, err
}
hrtfLibraries.Lock()
defer hrtfLibraries.Unlock()
defer func() {
if p := recover(); p != nil {
renderer = nil
err = fmt.Errorf("load HRTF symbols: %v", p)
}
}()
api := hrtfLibraries.libraries[path]
if api == nil {
lib, openErr := openHRTFLibrary(path)
if openErr != nil {
return nil, fmt.Errorf("load HRTF: %w", openErr)
}
api = &hrtfAPI{}
purego.RegisterLibFunc(&api.create, lib, "sverse_hrtf_create")
purego.RegisterLibFunc(&api.destroy, lib, "sverse_hrtf_destroy")
purego.RegisterLibFunc(&api.pairCreate, lib, "sverse_hrtf_pair_create")
purego.RegisterLibFunc(&api.pairDestroy, lib, "sverse_hrtf_pair_destroy")
purego.RegisterLibFunc(&api.apply, lib, "sverse_hrtf_apply")
hrtfLibraries.libraries[path] = api
}
renderer = &HRTFRenderer{api: api}
if c.Interpolation == "bilinear" {
renderer.interpolation = 1
}
if code := api.create(SampleRate, BlockSamples, &renderer.state); code != 0 {
return nil, fmt.Errorf("create HRTF renderer: %d", code)
}
return renderer, nil
}
func (r *HRTFRenderer) newPair() (*binauralPair, error) {
p := &binauralPair{renderer: r, direction: [3]float32{0, 0, -1}, interpolation: r.interpolation}
if code := r.api.pairCreate(r.state, &p.state); code != 0 {
return nil, fmt.Errorf("create HRTF pair: %d", code)
}
return p, nil
}
func (r *HRTFRenderer) Close() {
if r != nil && r.state != 0 {
r.api.destroy(r.state)
r.state = 0
}
}
func (p *binauralPair) Close() {
if p != nil && p.state != 0 {
p.renderer.api.pairDestroy(p.state)
p.state = 0
}
}
func (p *binauralPair) process(pcm []float32, direction [3]float32, smoothing float64) bool {
for i := range p.direction {
p.direction[i] += float32(smoothing) * (direction[i] - p.direction[i])
}
if len(pcm) != BlockSamples {
return false
}
code := p.renderer.api.apply(p.state, &pcm[0], &p.output[0], &p.direction[0], p.interpolation)
runtime.KeepAlive(pcm)
runtime.KeepAlive(p)
return code == 0
}
// Unreal-style head coordinates: forward +X, right +Y, up +Z. Steam Audio
// expects right +X, up +Y, forward -Z, relative to the listener's orientation.
func headDirection(listener, source Pose) [3]float32 {
q := listener.Rotation
f := Vec3{1 - 2*(q.Y*q.Y+q.Z*q.Z), 2 * (q.X*q.Y + q.Z*q.W), 2 * (q.X*q.Z - q.Y*q.W)}
right := q.Right()
up := Vec3{2 * (q.X*q.Z + q.Y*q.W), 2 * (q.Y*q.Z - q.X*q.W), 1 - 2*(q.X*q.X+q.Y*q.Y)}
d := Vec3{source.Position.X - listener.Position.X, source.Position.Y - listener.Position.Y, source.Position.Z - listener.Position.Z}
length := math.Sqrt(d.X*d.X + d.Y*d.Y + d.Z*d.Z)
if length < 1e-6 {
return [3]float32{0, 0, -1}
}
dot := func(v Vec3) float32 { return float32((d.X*v.X + d.Y*v.Y + d.Z*v.Z) / length) }
return [3]float32{dot(right), dot(up), -dot(f)}
}
+6
View File
@@ -0,0 +1,6 @@
//go:build linux || darwin || freebsd
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
func openHRTFLibrary(path string) (uintptr, error) { return openOpusLibrary(path) }
+9
View File
@@ -0,0 +1,9 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import "golang.org/x/sys/windows"
func openHRTFLibrary(path string) (uintptr, error) {
lib, err := windows.LoadLibraryEx(path, 0, windows.LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|windows.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)
return uintptr(lib), err
}
+86
View File
@@ -0,0 +1,86 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
// GainMatrix belongs to the room's audio worker. Heartbeat sequence numbers and
// client timestamps do not invalidate geometry. Rotation changes a listener's
// row; position changes its row and its column. Missing poses silence the pair.
type GainMatrix struct {
config Config
poses map[string]Pose
rows map[string]map[string]Gain
calculations uint64
scene *CompiledScene
dirty bool
minPriority int
}
func NewGainMatrix(c Config) *GainMatrix {
return &GainMatrix{config: c, poses: make(map[string]Pose), rows: make(map[string]map[string]Gain)}
}
func (m *GainMatrix) Update(poses map[string]Pose) {
moved := make(map[string]bool)
for id, pose := range poses {
previous, exists := m.poses[id]
if !exists || pose.Position != previous.Position {
moved[id] = true
}
}
for id := range m.poses {
if _, exists := poses[id]; !exists {
delete(m.rows, id)
for _, row := range m.rows {
delete(row, id)
}
}
}
for listenerID, listener := range poses {
previous, exists := m.poses[listenerID]
row := m.rows[listenerID]
if row == nil {
row = make(map[string]Gain, len(poses))
m.rows[listenerID] = row
}
if m.dirty || !exists || moved[listenerID] || listener.Rotation != previous.Rotation {
for sourceID, source := range poses {
if sourceID == listenerID {
continue
}
row[sourceID] = m.gains(listener, source)
m.calculations++
}
} else {
for sourceID := range moved {
if sourceID == listenerID {
continue
}
row[sourceID] = m.gains(listener, poses[sourceID])
m.calculations++
}
}
}
m.poses = poses
m.dirty = false
}
func (m *GainMatrix) SetScene(scene *CompiledScene) { m.scene = scene; m.dirty = true }
func (m *GainMatrix) SetMinPriority(priority int) {
if m.minPriority != priority {
m.minPriority = priority
m.dirty = true
}
}
func (m *GainMatrix) gains(listener, source Pose) Gain {
g := Gains(listener, source, m.config)
if g == (Gain{}) {
return g
}
transmission := m.scene.transmission(listener.Position, source.Position, m.minPriority)
g.Left *= transmission
g.Right *= transmission
return g
}
// Row is read-only to callers and valid until the next Update.
func (m *GainMatrix) Row(listenerID string) map[string]Gain { return m.rows[listenerID] }
func (m *GainMatrix) Calculations() uint64 { return m.calculations }
+252
View File
@@ -0,0 +1,252 @@
// 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
}
+173
View File
@@ -0,0 +1,173 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"encoding/json"
"fmt"
"math"
"strings"
)
const SceneTopic = "sverse.spatial.scene.v1"
const SceneAckTopic = "sverse.spatial.scene.ack.v1"
const MaxSceneBytes = 15000
type OcclusionConfig struct {
Enabled bool `yaml:"enabled,omitempty"`
MaxObjects int `yaml:"max_objects,omitempty"`
}
// Size is [width, height] in metres along local X/Y; local +Z is the
// normal of a zero-thickness rectangle. Rotation is a unit quaternion xyzw.
// Transmission is an amplitude multiplier, not a power ratio or dB value.
type Obstacle struct {
Priority *int `json:"priority,omitempty"`
ID string `json:"id"`
Center [3]float64 `json:"center"`
Size []float64 `json:"size"`
Rotation [4]float64 `json:"rotation"`
Transmission *float64 `json:"transmission"`
}
type Scene struct {
Adaptive *bool `json:"adaptive,omitempty"`
HRTF *bool `json:"hrtf,omitempty"`
Version int `json:"version"`
Revision uint64 `json:"revision"`
LocationID string `json:"location_id"`
Enabled bool `json:"enabled"`
Objects []Obstacle `json:"objects"`
}
type occluder struct {
priority int
center Vec3
half [2]float64
axes [3]Vec3
transmission float64
}
type CompiledScene struct {
Adaptive *bool
HRTF *bool
Revision uint64
Enabled bool
Objects []occluder
}
func ParseScene(payload []byte, maxObjects int) (*CompiledScene, error) {
if len(payload) == 0 || len(payload) > MaxSceneBytes {
return nil, fmt.Errorf("scene exceeds %d bytes", MaxSceneBytes)
}
var scene Scene
if err := json.Unmarshal(payload, &scene); err != nil {
return nil, fmt.Errorf("invalid scene JSON: %w", err)
}
if scene.Version != 1 || scene.Revision == 0 || scene.Revision >= 1<<53 || strings.TrimSpace(scene.LocationID) == "" || len(scene.LocationID) > 100 {
return nil, fmt.Errorf("invalid scene version, revision or location_id")
}
if len(scene.Objects) > maxObjects {
return nil, fmt.Errorf("scene exceeds %d objects", maxObjects)
}
compiled := &CompiledScene{Revision: scene.Revision, Enabled: scene.Enabled, HRTF: scene.HRTF, Adaptive: scene.Adaptive}
ids := make(map[string]bool, len(scene.Objects))
for _, object := range scene.Objects {
priority := 100
if object.Priority != nil {
priority = *object.Priority
}
if priority < 0 || priority > 100 {
return nil, fmt.Errorf("invalid priority for obstacle %q", object.ID)
}
if strings.TrimSpace(object.ID) == "" || len(object.ID) > 64 || ids[object.ID] {
return nil, fmt.Errorf("empty or duplicate obstacle id")
}
ids[object.ID] = true
if len(object.Size) != 2 {
return nil, fmt.Errorf("obstacle %q: size must contain width and height; volumetric walls are unsupported", object.ID)
}
for i := 0; i < 3; i++ {
if !finite(object.Center[i]) || math.Abs(object.Center[i]) >= 1e7 {
return nil, fmt.Errorf("invalid bounds for obstacle %q", object.ID)
}
}
for _, size := range object.Size {
if !finite(size) || size < 1e-4 || size > 1e6 {
return nil, fmt.Errorf("invalid size for obstacle %q", object.ID)
}
}
if object.Transmission == nil || !finite(*object.Transmission) || *object.Transmission < 0 || *object.Transmission > 1 {
return nil, fmt.Errorf("invalid transmission for obstacle %q", object.ID)
}
q := Quaternion{object.Rotation[0], object.Rotation[1], object.Rotation[2], object.Rotation[3]}
if !(Pose{Rotation: q}).Valid() {
return nil, fmt.Errorf("invalid rotation for obstacle %q", object.ID)
}
n := math.Sqrt(q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W)
q.X /= n
q.Y /= n
q.Z /= n
q.W /= n
compiled.Objects = append(compiled.Objects, occluder{
priority: priority,
center: Vec3{object.Center[0], object.Center[1], object.Center[2]},
half: [2]float64{object.Size[0] / 2, object.Size[1] / 2},
axes: [3]Vec3{
{1 - 2*(q.Y*q.Y+q.Z*q.Z), 2 * (q.X*q.Y + q.Z*q.W), 2 * (q.X*q.Z - q.Y*q.W)},
q.Right(),
{2 * (q.X*q.Z + q.Y*q.W), 2 * (q.Y*q.Z - q.X*q.W), 1 - 2*(q.X*q.X+q.Y*q.Y)},
}, transmission: *object.Transmission,
})
}
return compiled, nil
}
// Intersect a finite segment with a two-sided plane, then check the rectangle.
// Parallel/coplanar segments do not cross the wall. Endpoint and edge contact
// count when the segment is not parallel; no volume or thickness is involved.
func (o occluder) intersects(a, b Vec3) bool {
start := Vec3{a.X - o.center.X, a.Y - o.center.Y, a.Z - o.center.Z}
delta := Vec3{b.X - a.X, b.Y - a.Y, b.Z - a.Z}
dot := func(v, axis Vec3) float64 { return v.X*axis.X + v.Y*axis.Y + v.Z*axis.Z }
distance := dot(start, o.axes[2])
denominator := dot(delta, o.axes[2])
if math.Abs(denominator) < 1e-10 {
return false
}
t := -distance / denominator
if t < 0 || t > 1 {
return false
}
point := Vec3{start.X + t*delta.X, start.Y + t*delta.Y, start.Z + t*delta.Z}
return math.Abs(dot(point, o.axes[0])) <= o.half[0]+1e-8 && math.Abs(dot(point, o.axes[1])) <= o.half[1]+1e-8
}
func (s *CompiledScene) Transmission(a, b Vec3) float64 {
return s.transmission(a, b, 0)
}
func (s *CompiledScene) activeObjects(minPriority int) int {
if s == nil || !s.Enabled {
return 0
}
n := 0
for _, object := range s.Objects {
if object.priority >= minPriority {
n++
}
}
return n
}
func (s *CompiledScene) transmission(a, b Vec3, minPriority int) float64 {
if s == nil || !s.Enabled {
return 1
}
gain := 1.0
for _, object := range s.Objects {
if object.priority < minPriority {
continue
}
if object.transmission < 1 && object.intersects(a, b) {
gain *= object.transmission
if gain == 0 {
break
}
}
}
return gain
}
+162
View File
@@ -0,0 +1,162 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"fmt"
"runtime"
"sync"
"github.com/ebitengine/purego"
)
// Opus owns a library handle for the process lifetime; individual codec states
// are exclusively owned by the room's audio worker and destroyed on removal.
type Opus struct {
decoderCreate func(int32, int32, *int32) uintptr
decoderDestroy func(uintptr)
decode func(uintptr, *byte, int32, *float32, int32, int32) int32
encoderCreate func(int32, int32, int32, *int32) uintptr
encoderDestroy func(uintptr)
encode func(uintptr, *float32, int32, *byte, int32) int32
encoderCtl func(uintptr, int32, int32) int32
packetSamples func(*byte, int32, int32) int32
}
var opusLibraries = struct {
sync.Mutex
byPath map[string]*Opus
}{byPath: make(map[string]*Opus)}
func LoadOpus(path string) (opus *Opus, err error) {
if path == "" {
switch runtime.GOOS {
case "windows":
path = "opus.dll"
case "darwin":
path = "libopus.0.dylib"
default:
path = "libopus.so.0"
}
}
opusLibraries.Lock()
defer opusLibraries.Unlock()
if existing := opusLibraries.byPath[path]; existing != nil {
return existing, nil
}
lib, err := openOpusLibrary(path)
if err != nil {
return nil, fmt.Errorf("load libopus %q: %w", path, err)
}
defer func() {
if p := recover(); p != nil {
opus = nil
err = fmt.Errorf("load libopus symbols: %v", p)
}
}()
opus = &Opus{}
purego.RegisterLibFunc(&opus.decoderCreate, lib, "opus_decoder_create")
purego.RegisterLibFunc(&opus.decoderDestroy, lib, "opus_decoder_destroy")
purego.RegisterLibFunc(&opus.decode, lib, "opus_decode_float")
purego.RegisterLibFunc(&opus.encoderCreate, lib, "opus_encoder_create")
purego.RegisterLibFunc(&opus.encoderDestroy, lib, "opus_encoder_destroy")
purego.RegisterLibFunc(&opus.encode, lib, "opus_encode_float")
purego.RegisterLibFunc(&opus.encoderCtl, lib, "opus_encoder_ctl")
purego.RegisterLibFunc(&opus.packetSamples, lib, "opus_packet_get_nb_samples")
opusLibraries.byPath[path] = opus
return opus, nil
}
type Decoder struct {
opus *Opus
state uintptr
}
func (o *Opus) NewDecoder() (*Decoder, error) {
var code int32
state := o.decoderCreate(SampleRate, 1, &code)
if state == 0 || code != 0 {
return nil, fmt.Errorf("opus decoder: %d", code)
}
return &Decoder{o, state}, nil
}
func (d *Decoder) Decode(packet []byte, frameSize int, fec bool) ([]float32, error) {
if frameSize < 120 || frameSize > 5760 {
return nil, fmt.Errorf("invalid Opus frame size")
}
pcm := make([]float32, frameSize)
var data *byte
if len(packet) > 0 {
data = &packet[0]
}
f := int32(0)
if fec {
f = 1
}
n := d.opus.decode(d.state, data, int32(len(packet)), &pcm[0], int32(frameSize), f)
runtime.KeepAlive(packet)
runtime.KeepAlive(pcm)
if n < 0 {
return nil, fmt.Errorf("opus decode: %d", n)
}
return pcm[:n], nil
}
func (d *Decoder) Close() {
if d != nil && d.state != 0 {
d.opus.decoderDestroy(d.state)
d.state = 0
}
}
type Encoder struct {
opus *Opus
state uintptr
channels int
}
func (o *Opus) NewEncoder(channels, bitrate int) (*Encoder, error) {
var code int32
state := o.encoderCreate(SampleRate, int32(channels), 2049, &code)
if state == 0 || code != 0 {
return nil, fmt.Errorf("opus encoder: %d", code)
}
e := &Encoder{o, state, channels}
if code = o.encoderCtl(state, 4002, int32(bitrate)); code != 0 {
e.Close()
return nil, fmt.Errorf("opus bitrate: %d", code)
}
// Force two-channel encoding for personalized output, including centered voices.
if channels == 2 {
if code = o.encoderCtl(state, 4022, 2); code != 0 {
e.Close()
return nil, fmt.Errorf("opus stereo: %d", code)
}
}
return e, nil
}
func (e *Encoder) Encode(pcm []float32) ([]byte, error) {
if len(pcm) != PacketSamples*e.channels {
return nil, fmt.Errorf("expected 20 ms PCM")
}
b := make([]byte, 1275)
n := e.opus.encode(e.state, &pcm[0], PacketSamples, &b[0], int32(len(b)))
runtime.KeepAlive(pcm)
runtime.KeepAlive(b)
if n < 0 {
return nil, fmt.Errorf("opus encode: %d", n)
}
return b[:n], nil
}
func (e *Encoder) Close() {
if e.state != 0 {
e.opus.encoderDestroy(e.state)
e.state = 0
}
}
func (o *Opus) Samples(b []byte) int {
if len(b) == 0 {
return 0
}
n := o.packetSamples(&b[0], int32(len(b)), SampleRate)
runtime.KeepAlive(b)
return int(n)
}
+10
View File
@@ -0,0 +1,10 @@
//go:build linux || darwin || freebsd
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import "github.com/ebitengine/purego"
func openOpusLibrary(path string) (uintptr, error) {
return purego.Dlopen(path, purego.RTLD_NOW|purego.RTLD_LOCAL)
}
+9
View File
@@ -0,0 +1,9 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import "golang.org/x/sys/windows"
func openOpusLibrary(path string) (uintptr, error) {
lib, err := windows.LoadLibrary(path)
return uintptr(lib), err
}
+104
View File
@@ -0,0 +1,104 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"encoding/binary"
"errors"
"math"
"sync"
"time"
)
const PoseTopic = "sverse.spatial.pose.v1"
const PosePacketSize = 44
type Vec3 struct{ X, Y, Z float64 }
type Quaternion struct{ X, Y, Z, W float64 }
type Pose struct {
Sequence uint32
ClientTimeMs float64
Position Vec3
Rotation Quaternion
}
func finite(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) }
func (p Pose) Valid() bool {
for _, v := range []float64{p.ClientTimeMs, p.Position.X, p.Position.Y, p.Position.Z, p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W} {
if !finite(v) {
return false
}
}
n := p.Rotation.X*p.Rotation.X + p.Rotation.Y*p.Rotation.Y + p.Rotation.Z*p.Rotation.Z + p.Rotation.W*p.Rotation.W
return n > 0.5 && n < 1.5 && math.Abs(p.Position.X) < 1e7 && math.Abs(p.Position.Y) < 1e7 && math.Abs(p.Position.Z) < 1e7
}
// Layout: version/u8, reserved/3, sequence/u32, monotonic milliseconds/f64,
// position/3*f32, quaternion x,y,z,w/4*f32. All values are little endian.
func ParsePose(b []byte) (Pose, error) {
if len(b) != PosePacketSize || b[0] != 1 || b[1] != 0 || b[2] != 0 || b[3] != 0 {
return Pose{}, errors.New("invalid spatial pose packet")
}
f := func(i int) float64 { return float64(math.Float32frombits(binary.LittleEndian.Uint32(b[i : i+4]))) }
p := Pose{Sequence: binary.LittleEndian.Uint32(b[4:8]), ClientTimeMs: math.Float64frombits(binary.LittleEndian.Uint64(b[8:16])), Position: Vec3{f(16), f(20), f(24)}, Rotation: Quaternion{f(28), f(32), f(36), f(40)}}
if !p.Valid() {
return Pose{}, errors.New("non-finite or invalid spatial pose")
}
q := &p.Rotation
n := math.Sqrt(q.X*q.X + q.Y*q.Y + q.Z*q.Z + q.W*q.W)
q.X /= n
q.Y /= n
q.Z /= n
q.W /= n
return p, nil
}
func (p Pose) MarshalBinary() []byte {
b := make([]byte, PosePacketSize)
b[0] = 1
binary.LittleEndian.PutUint32(b[4:8], p.Sequence)
binary.LittleEndian.PutUint64(b[8:16], math.Float64bits(p.ClientTimeMs))
for i, v := range []float64{p.Position.X, p.Position.Y, p.Position.Z, p.Rotation.X, p.Rotation.Y, p.Rotation.Z, p.Rotation.W} {
binary.LittleEndian.PutUint32(b[16+i*4:], math.Float32bits(float32(v)))
}
return b
}
func (q Quaternion) Right() Vec3 {
return Vec3{2 * (q.X*q.Y - q.Z*q.W), 1 - 2*(q.X*q.X+q.Z*q.Z), 2 * (q.Y*q.Z + q.X*q.W)}
}
type timedPose struct {
pose Pose
at time.Time
}
type PoseStore struct {
mu sync.RWMutex
poses map[string]timedPose
}
func NewPoseStore() *PoseStore { return &PoseStore{poses: make(map[string]timedPose)} }
func (s *PoseStore) Update(id string, p Pose, now time.Time) bool {
if !p.Valid() {
return false
}
s.mu.Lock()
defer s.mu.Unlock()
old, ok := s.poses[id]
if ok && int32(p.Sequence-old.pose.Sequence) <= 0 {
return false
}
s.poses[id] = timedPose{p, now}
return true
}
func (s *PoseStore) Remove(id string) { s.mu.Lock(); delete(s.poses, id); s.mu.Unlock() }
func (s *PoseStore) Snapshot(now time.Time, timeout time.Duration) map[string]Pose {
s.mu.RLock()
defer s.mu.RUnlock()
out := make(map[string]Pose, len(s.poses))
for id, p := range s.poses {
if now.Sub(p.at) <= timeout {
out[id] = p.pose
}
}
return out
}
+219
View File
@@ -0,0 +1,219 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package spatialaudio
import (
"math"
"os"
"testing"
"time"
)
func poseAt(x, y, z, yaw float64) Pose {
return Pose{Position: Vec3{x, y, z}, Rotation: Quaternion{Z: math.Sin(yaw / 2), W: math.Cos(yaw / 2)}}
}
func TestPoseProtocolAndOrdering(t *testing.T) {
p := poseAt(12, -3, 2, math.Pi/2)
p.Sequence = math.MaxUint32
p.ClientTimeMs = 1250.25
parsed, err := ParsePose(p.MarshalBinary())
if err != nil || parsed.Sequence != p.Sequence || parsed.Position != p.Position {
t.Fatalf("pose roundtrip: %+v %v", parsed, err)
}
r := parsed.Rotation.Right()
if math.Abs(r.X+1) > 1e-6 || math.Abs(r.Y) > 1e-6 {
t.Fatalf("wrong listener right vector: %+v", r)
}
now := time.Now()
store := NewPoseStore()
if !store.Update("listener", parsed, now) {
t.Fatal("first pose rejected")
}
parsed.Sequence = 0
if !store.Update("listener", parsed, now) {
t.Fatal("sequence wrap rejected")
}
parsed.Sequence = math.MaxUint32
if store.Update("listener", parsed, now) {
t.Fatal("stale pose accepted")
}
if len(store.Snapshot(now.Add(501*time.Millisecond), 500*time.Millisecond)) != 0 {
t.Fatal("expired pose still audible")
}
for _, packet := range [][]byte{nil, p.MarshalBinary()[:43], append(p.MarshalBinary(), 0)} {
if _, err := ParsePose(packet); err == nil {
t.Fatal("invalid size accepted")
}
}
p.Position.X = math.NaN()
if _, err := ParsePose(p.MarshalBinary()); err == nil {
t.Fatal("NaN accepted")
}
}
func TestAttenuationAndOrientation(t *testing.T) {
c := Config{}.Defaults()
listener := poseAt(0, 0, 0, 0)
left, right := Gains(listener, poseAt(0, -.5, 0, 0), c), Gains(listener, poseAt(0, .5, 0, 0), c)
if left.Left != 1 || left.Right != 0 || right.Right != 1 || right.Left != 0 {
t.Fatalf("reversed ears: %+v %+v", left, right)
}
if Gains(listener, poseAt(0, 20, 0, 0), c) != (Gain{}) {
t.Fatal("distant voice audible")
}
center := Gains(listener, listener, c)
if !finite(center.Left) || math.Abs(center.Left-center.Right) > 1e-9 {
t.Fatal("coincident positions invalid")
}
rotated := Gains(poseAt(0, 0, 0, math.Pi), poseAt(0, .5, 0, 0), c)
if rotated.Right > 1e-6 || rotated.Left < .999 {
t.Fatal("head rotation ignored")
}
}
func TestMixerExcludesSelfAndSmoothsCutoff(t *testing.T) {
c := Config{}.Defaults()
m := NewMixer(c)
pcm := make([]float32, BlockSamples)
for i := range pcm {
pcm[i] = .2
}
poses := map[string]Pose{"listener": poseAt(0, 0, 0, 0), "source": poseAt(0, .5, 0, 0)}
out := make([]float32, 2*BlockSamples)
for n := 0; n < 30; n++ {
m.Mix("listener", poses, map[string][]float32{"source": pcm, "listener": pcm}, out)
}
if out[len(out)-1] < .199 || out[len(out)-2] != 0 {
t.Fatalf("self leakage or wrong pan: %v", out[len(out)-2:])
}
delete(poses, "source")
previous := out[len(out)-1]
m.Mix("listener", poses, map[string][]float32{"source": pcm}, out)
if out[1] <= 0 || out[1] >= previous || math.Abs(float64(out[1]-previous)) > .001 {
t.Fatal("cutoff introduces a step")
}
for n := 0; n < 100; n++ {
m.Mix("listener", poses, map[string][]float32{"source": pcm}, out)
}
if out[len(out)-1] > .000001 {
t.Fatal("cutoff did not reach silence")
}
}
func nativeOpus(t *testing.T) *Opus {
t.Helper()
path := os.Getenv("SPATIAL_OPUS_LIBRARY")
if path == "" {
t.Skip("set SPATIAL_OPUS_LIBRARY to run native codec tests")
}
o, err := LoadOpus(path)
if err != nil {
t.Fatal(err)
}
return o
}
func TestNativeStereoAndEngineIsolation(t *testing.T) {
opus := nativeOpus(t)
encoder, err := opus.NewEncoder(2, 64000)
if err != nil {
t.Fatal(err)
}
defer encoder.Close()
var code int32
decoder := opus.decoderCreate(SampleRate, 2, &code)
if decoder == 0 {
t.Fatal(code)
}
defer opus.decoderDestroy(decoder)
input := make([]float32, 2*PacketSamples)
output := make([]float32, 2*PacketSamples)
for frame := 0; frame < 8; frame++ {
for i := 0; i < PacketSamples; i++ {
input[2*i] = float32(.2 * math.Sin(2*math.Pi*440*float64(frame*PacketSamples+i)/SampleRate))
input[2*i+1] = 0
}
packet, err := encoder.Encode(input)
if err != nil {
t.Fatal(err)
}
if opus.decode(decoder, &packet[0], int32(len(packet)), &output[0], PacketSamples, 0) != PacketSamples {
t.Fatal("stereo decode length")
}
}
left, right := 0.0, 0.0
for i := 0; i < PacketSamples; i++ {
left += float64(output[2*i] * output[2*i])
right += float64(output[2*i+1] * output[2*i+1])
}
if left < 1 || right > left*.001 {
t.Fatalf("stereo lost: L=%f R=%f", left, right)
}
e, err := NewEngine(Config{Library: os.Getenv("SPATIAL_OPUS_LIBRARY")})
if err != nil {
t.Fatal(err)
}
defer e.Close()
packets := make(chan []byte, 128)
if err = e.AddListener("listener", func(b []byte, _ uint32) error { packets <- append([]byte(nil), b...); return nil }); err != nil {
t.Fatal(err)
}
if err = e.AddListener("source", func([]byte, uint32) error { return nil }); err != nil {
t.Fatal(err)
}
e.Poses.Update("listener", poseAt(0, 0, 0, 0), time.Now())
e.Poses.Update("source", poseAt(0, .5, 0, 0), time.Now())
src, err := e.AddSource("source", "track")
if err != nil {
t.Fatal(err)
}
mono, err := opus.NewEncoder(1, 48000)
if err != nil {
t.Fatal(err)
}
defer mono.Close()
for frame := 0; frame < 10; frame++ {
pcm := make([]float32, PacketSamples)
for i := range pcm {
pcm[i] = float32(.2 * math.Sin(2*math.Pi*440*float64(frame*PacketSamples+i)/SampleRate))
}
packet, err := mono.Encode(pcm)
if err != nil {
t.Fatal(err)
}
src.Push(RTPInput{Sequence: uint16(frame), Timestamp: uint32(frame * PacketSamples), SSRC: 1, Payload: packet})
time.Sleep(20 * time.Millisecond)
}
left, right = 0, 0
mixDecoder := opus.decoderCreate(SampleRate, 2, &code)
if mixDecoder == 0 {
t.Fatal(code)
}
defer opus.decoderDestroy(mixDecoder)
for len(packets) > 0 {
packet := <-packets
if opus.decode(mixDecoder, &packet[0], int32(len(packet)), &output[0], PacketSamples, 0) != PacketSamples {
t.Fatal("mix decode")
}
for i := 0; i < PacketSamples; i++ {
left += float64(output[2*i] * output[2*i])
right += float64(output[2*i+1] * output[2*i+1])
}
}
if right < 1 || left > right*.01 {
t.Fatalf("personalized pan lost L=%f R=%f", left, right)
}
e.RemoveParticipant("source")
stats := e.SnapshotStats()
if stats.Sources != 0 || stats.Listeners != 1 {
t.Fatalf("leaked participant state: %+v", stats)
}
}
func TestREDPrimary(t *testing.T) {
primary, err := PrimaryRED([]byte{0x80 | 111, 0, 0, 2, 111, 9, 8, 1, 2, 3})
if err != nil || string(primary) != string([]byte{1, 2, 3}) {
t.Fatalf("RED parsing %v %v", primary, err)
}
if _, err = PrimaryRED([]byte{0x80 | 111, 0}); err == nil {
t.Fatal("truncated RED accepted")
}
}
-1
View File
@@ -174,7 +174,6 @@ func GetNodeStats(nodeStartedAt int64, prevStats []*livekit.NodeStats, rateInter
ParticipantRtcCanceled: participantRTCCanceled.Load(),
ParticipantRtcActive: participantRTCActive.Load(),
ForwardLatency: forwardLatency.Load(),
ForwardJitter: forwardJitter.Load(),
NumCpus: uint32(cpuStats.NumCPU()), // this will round down to the nearest integer
CpuLoad: float32(cpuStats.GetCPULoad()),
MemoryTotal: memTotal,
+3 -17
View File
@@ -51,7 +51,6 @@ var (
participantRTCCanceled atomic.Uint64
participantRTCActive atomic.Uint64
forwardLatency atomic.Uint32
forwardJitter atomic.Uint32
promPacketLabels = []string{"direction", "transmission", "country"}
promPacketTotal *prometheus.CounterVec
@@ -70,7 +69,6 @@ var (
promParticipantJoin *prometheus.CounterVec
promConnections *prometheus.GaugeVec
promForwardLatency prometheus.Gauge
promForwardJitter prometheus.Gauge
promForwardLatencyHist prometheus.Histogram
)
@@ -164,12 +162,6 @@ func initPacketStats(nodeID string, nodeType livekit.NodeType) {
Name: "latency",
ConstLabels: prometheus.Labels{"node_id": nodeID, "node_type": nodeType.String()},
})
promForwardJitter = prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: livekitNamespace,
Subsystem: "forward",
Name: "jitter",
ConstLabels: prometheus.Labels{"node_id": nodeID, "node_type": nodeType.String()},
})
promForwardLatencyHist = prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: livekitNamespace,
Subsystem: "forward_latency",
@@ -204,7 +196,6 @@ func initPacketStats(nodeID string, nodeType livekit.NodeType) {
prometheus.MustRegister(promParticipantJoin)
prometheus.MustRegister(promConnections)
prometheus.MustRegister(promForwardLatency)
prometheus.MustRegister(promForwardJitter)
prometheus.MustRegister(promForwardLatencyHist)
}
@@ -380,12 +371,7 @@ func RecordForwardLatencySample(forwardLatency int64) {
promForwardLatencyHist.Observe(float64(forwardLatency))
}
func RecordForwardLatency(longTermLatencyAvg uint32) {
forwardLatency.Store(longTermLatencyAvg)
promForwardLatency.Set(float64(longTermLatencyAvg))
}
func RecordForwardJitter(longTermJitterAvg uint32) {
forwardJitter.Store(longTermJitterAvg)
promForwardJitter.Set(float64(longTermJitterAvg))
func RecordForwardLatency(p90 uint32) {
forwardLatency.Store(p90)
promForwardLatency.Set(float64(p90))
}
+24
View File
@@ -0,0 +1,24 @@
# Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
$hrtfRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$hrtfRuntime = Join-Path $hrtfRoot '.spatial-runtime'
$hrtfZip = Join-Path $hrtfRuntime 'steamaudio_4.8.1.zip'
$hrtfSDK = Join-Path $hrtfRuntime 'steam-audio\steamaudio'
New-Item -ItemType Directory -Path $hrtfRuntime -Force | Out-Null
if (!(Test-Path -LiteralPath $hrtfZip)) {
Invoke-WebRequest 'https://github.com/ValveSoftware/steam-audio/releases/download/v4.8.1/steamaudio_4.8.1.zip' -OutFile $hrtfZip
}
if ((Get-FileHash -LiteralPath $hrtfZip -Algorithm SHA256).Hash -ne '4A0AA5EC1176F38F0B0993A37C2259D9E86F27E22D5E24F83EC4C3CB9A1D5449') { throw 'Steam Audio archive checksum mismatch' }
if (!(Test-Path -LiteralPath (Join-Path $hrtfSDK 'include\phonon.h'))) {
Expand-Archive -LiteralPath $hrtfZip -DestinationPath (Join-Path $hrtfRuntime 'steam-audio') -Force
}
$hrtfBuild = Join-Path $hrtfRuntime 'hrtf-build'
& cmake -S (Join-Path $hrtfRoot 'native\hrtf') -B $hrtfBuild -G 'Visual Studio 17 2022' -A x64 "-DSTEAMAUDIO_ROOT=$hrtfSDK"
if ($LASTEXITCODE -ne 0) { throw 'HRTF configuration failed' }
& cmake --build $hrtfBuild --config Release --parallel
if ($LASTEXITCODE -ne 0) { throw 'HRTF build failed' }
Copy-Item -LiteralPath (Join-Path $hrtfSDK 'THIRDPARTY.md') -Destination (Join-Path $hrtfBuild 'Release\STEAMAUDIO-THIRDPARTY.md')
Copy-Item -LiteralPath (Join-Path $hrtfRoot 'docs\third-party\steam-audio-LICENSE.md') -Destination (Join-Path $hrtfBuild 'Release\STEAMAUDIO-LICENSE.md')
Write-Host "HRTF bridge: $hrtfBuild\Release\sverse_hrtf.dll"
+18
View File
@@ -0,0 +1,18 @@
# Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
[CmdletBinding()]
param([string]$Generator = 'Visual Studio 17 2022')
$ErrorActionPreference = 'Stop'
$spatialRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$spatialRuntime = Join-Path $spatialRoot '.spatial-runtime'
$spatialSource = Join-Path $spatialRuntime 'opus-src'
$spatialBuild = Join-Path $spatialRuntime 'opus-build'
New-Item -ItemType Directory -Path $spatialRuntime -Force | Out-Null
if (!(Test-Path -LiteralPath $spatialSource)) {
& git clone --depth 1 --branch v1.5.2 https://github.com/xiph/opus.git $spatialSource
if ($LASTEXITCODE -ne 0) { throw 'Opus clone failed' }
}
& cmake -S $spatialSource -B $spatialBuild -G $Generator -A x64 -DBUILD_SHARED_LIBS=ON -DOPUS_BUILD_TESTING=OFF -DOPUS_BUILD_PROGRAMS=OFF
if ($LASTEXITCODE -ne 0) { throw 'Opus configure failed' }
& cmake --build $spatialBuild --config Release --parallel
if ($LASTEXITCODE -ne 0) { throw 'Opus build failed' }
Write-Host "Library: $(Join-Path $spatialBuild 'Release\opus.dll')"
+52
View File
@@ -0,0 +1,52 @@
# Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
[CmdletBinding()]
param([switch]$Restart, [switch]$SkipBuild)
$ErrorActionPreference = 'Stop'
$spatialRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$spatialRuntime = Join-Path $spatialRoot '.spatial-runtime'
$spatialOpus = Join-Path $spatialRuntime 'opus-build\Release\opus.dll'
if (!(Test-Path -LiteralPath $spatialOpus)) {
throw "Missing $spatialOpus. Run scripts/build-spatial-opus.ps1 first."
}
$spatialHRTF = Join-Path $spatialRuntime 'hrtf-build\Release\sverse_hrtf.dll'
$spatialSampleConfig = Get-Content -LiteralPath (Join-Path $spatialRoot 'config-sample-spatial.yaml') -Raw
if ($spatialSampleConfig -match '(?m)^ hrtf:\r?\n enabled: true\s*$' -and !(Test-Path -LiteralPath $spatialHRTF)) {
throw "Missing $spatialHRTF. Run scripts/build-spatial-hrtf.ps1 first for the sample HRTF configuration."
}
if ($Restart) { & (Join-Path $PSScriptRoot 'stop-spatial.ps1') }
foreach ($spatialPort in @(7880, 8899)) {
if (Get-NetTCPConnection -State Listen -LocalPort $spatialPort -ErrorAction SilentlyContinue) {
throw "Port $spatialPort is already in use. Use -Restart for this repository's running laboratory."
}
}
New-Item -ItemType Directory -Path $spatialRuntime -Force | Out-Null
Push-Location -LiteralPath $spatialRoot
try {
if (!$SkipBuild) {
& go build -o .spatial-runtime/livekit-server-current.exe ./cmd/server
if ($LASTEXITCODE -ne 0) { throw 'LiveKit build failed' }
& go build -o .spatial-runtime/spatial-test-current.exe ./cmd/spatial-test
if ($LASTEXITCODE -ne 0) { throw 'HTML laboratory build failed' }
}
foreach ($spatialName in @('livekit-server-current.exe', 'spatial-test-current.exe')) {
if (!(Test-Path -LiteralPath (Join-Path $spatialRuntime $spatialName))) { throw "Missing $spatialName" }
}
$spatialServer = Start-Process -FilePath (Join-Path $spatialRuntime 'livekit-server-current.exe') -ArgumentList '--config', 'config-sample-spatial.yaml' -WorkingDirectory $spatialRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $spatialRuntime 'server.stdout.log') -RedirectStandardError (Join-Path $spatialRuntime 'server.stderr.log') -PassThru
$spatialPreviousKey = $env:LIVEKIT_API_KEY
$spatialPreviousSecret = $env:LIVEKIT_API_SECRET
try {
# These credentials match the public local development YAML only.
$env:LIVEKIT_API_KEY = 'devkey'
$env:LIVEKIT_API_SECRET = 'spatial-local-development-secret'
$spatialLab = Start-Process -FilePath (Join-Path $spatialRuntime 'spatial-test-current.exe') -WorkingDirectory $spatialRoot -WindowStyle Hidden -RedirectStandardOutput (Join-Path $spatialRuntime 'lab.stdout.log') -RedirectStandardError (Join-Path $spatialRuntime 'lab.stderr.log') -PassThru
} catch {
Stop-Process -Id $spatialServer.Id -ErrorAction SilentlyContinue
throw
} finally {
$env:LIVEKIT_API_KEY = $spatialPreviousKey
$env:LIVEKIT_API_SECRET = $spatialPreviousSecret
}
Write-Host "LiveKit PID: $($spatialServer.Id); HTML PID: $($spatialLab.Id)"
Write-Host 'Open http://127.0.0.1:8899/ in your browser (do not open index.html as a file).'
Write-Host "Logs: $spatialRuntime"
} finally { Pop-Location }
+15
View File
@@ -0,0 +1,15 @@
# Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
[CmdletBinding()]
param()
$ErrorActionPreference = 'Stop'
$spatialRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$spatialRuntime = [IO.Path]::GetFullPath((Join-Path $spatialRoot '.spatial-runtime')) + [IO.Path]::DirectorySeparatorChar
# Select only this checkout's development binaries; never stop by name alone.
Get-CimInstance Win32_Process | Where-Object {
$_.ExecutablePath -and $_.ExecutablePath.StartsWith($spatialRuntime, [StringComparison]::OrdinalIgnoreCase) -and
([IO.Path]::GetFileName($_.ExecutablePath) -match '^(livekit-server|spatial-test)(-[a-z0-9-]+)?\.exe$')
} | ForEach-Object {
Stop-Process -Id $_.ProcessId
Wait-Process -Id $_.ProcessId -Timeout 10 -ErrorAction SilentlyContinue
Write-Host "Stopped PID $($_.ProcessId)"
}