Files
livekit-3d/cmd/spatial-node/main.go

339 lines
10 KiB
Go

// 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)
}
}