feat(oglvoice): spatial multi-speaker Opus mixer and trusted live position sync (#123)

* build(oglvoice): add libopus encoder/decoder for simultaneous spatial audio mixing

* feat(oglvoice): spatial Opus multi-speaker decode/mix/encode per listener with bounded jitter buffers

* feat(oglvoice): replace single-speaker RTP relay with per-listener decoded spatial Opus mixer

* feat(oglvoice): bind spatial listener/source updates to authenticated region admission and LiveKit room

* feat(oglvoice): add verified simulator avatar coordinates to signed media admission payload

* feat(oglvoice): carry simulator-verified spatial position in trusted media admission

* feat(oglvoice): derive listener position and quaternion heading from authenticated ScenePresence

* fix(oglvoice): start Opus downlink mixing only after WebRTC transport is connected

* feat(oglvoice): accept signed simulator-only position updates for active viewer sessions

* feat(oglvoice): push verified avatar position/heading every two seconds and revoke absent sessions

* fix: initialize spatial sync admission

* ci(oglvoice): install libopus-dev and compile/race-test Opus mixer without opusfile

* test(oglvoice): assert real Opus multi-speaker mixing, stereo pan, range, jitter budgets and packet splitting

* fix(oglvoice): align stereo pan left/right with avatar yaw orientation

* fix(test): use explicit negative sample comparisons in spatial saturation regression

* test(oglvoice): reject forged viewer sessions and accept signed moving-avatar spatial updates

* docs(oglvoice): describe multi-speaker libopus spatial mixing, runtime dependencies and remaining HRTF limits

* docs(release): record live Opus spatial-mixer foundation and preserve production acceptance gates
This commit is contained in:
OpenGenesis (MPL 2.0) authored and GitHub committed 2026-10-09 22:16:15 +02:00
1 parent 17f8d4f63f
commit 9c3a174d2e
14 files changed
+705 -27

No files matched your search

+9 -3
View File
@@ -35,6 +35,12 @@ jobs:
go-version-file: services/oglvoice-media/go.mod
cache-dependency-path: services/oglvoice-media/go.mod
- name: Install libopus build dependencies
shell: bash
run: |
sudo apt-get update -qq
sudo apt-get install -y --no-install-recommends pkg-config libopus-dev
- name: Resolve pinned dependencies
shell: bash
run: go mod tidy
@@ -47,15 +53,15 @@ jobs:
shell: bash
run: |
gofmt -w .
go vet -mod=mod ./...
go vet -tags nolibopusfile -mod=mod ./...
- name: Media bridge unit and WebRTC integration tests
shell: bash
run: go test -mod=mod -race -count=1 -timeout=3m ./...
run: go test -tags nolibopusfile -mod=mod -race -count=1 -timeout=3m ./...
- name: Build OGLVoice media daemon
shell: bash
run: go build -mod=mod -trimpath -o /tmp/oglvoice-media .
run: go build -tags nolibopusfile -mod=mod -trimpath -o /tmp/oglvoice-media .
- name: Local daemon configuration-negative smoke
shell: bash
@@ -23,6 +23,13 @@ namespace NexVerse.Core.Voice
public string HomeGridOrigin { get; init; }
public bool IsHypergridGuest { get; init; }
public bool VoiceAllowed { get; init; }
// Spatial coordinates are taken only from the simulator's ScenePresence.
// They do NOT affect JWT identity, and are never client-authorized.
public bool PositionValid { get; init; }
public float PositionX { get; init; }
public float PositionY { get; init; }
public float PositionZ { get; init; }
public float Heading { get; init; }
}
public sealed class OglVoiceIssuedToken
@@ -42,6 +42,7 @@ namespace NexVerse.RegionModules.Voice
{
public string ViewerSession;
public Guid AgentSessionId;
public OglVoiceAdmission LastAdmission;
}
private readonly ConcurrentDictionary<UUID, VoiceSession> m_Sessions = new();
@@ -50,6 +51,8 @@ namespace NexVerse.RegionModules.Voice
private Scene m_Scene;
private HttpClient m_Http;
private ISimulatorFeaturesModule m_Features;
private Timer m_PositionTimer;
private int m_PositionUpdateRunning;
private bool m_Enabled;
private string m_NodeId;
private string m_Key;
@@ -115,7 +118,12 @@ namespace NexVerse.RegionModules.Voice
m_Features.OnSimulatorFeaturesRequest += OnSimulatorFeaturesRequest;
}
public void PostInitialise() { }
public void PostInitialise()
{
if (m_Enabled)
m_PositionTimer = new Timer(_ => _ = PushPositionsAsync(), null,
TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(2));
}
public void RemoveRegion(Scene scene)
{
@@ -125,6 +133,8 @@ namespace NexVerse.RegionModules.Voice
if (m_Features != null)
m_Features.OnSimulatorFeaturesRequest -= OnSimulatorFeaturesRequest;
m_Features = null;
m_PositionTimer?.Dispose();
m_PositionTimer = null;
m_Scene = null;
m_Sessions.Clear();
}
@@ -355,7 +365,8 @@ namespace NexVerse.RegionModules.Voice
m_Sessions[avatar] = new VoiceSession
{
ViewerSession = media.viewer_session,
AgentSessionId = admission.SessionId
AgentSessionId = admission.SessionId,
LastAdmission = admission
};
response.RawBuffer = Encoding.UTF8.GetBytes(
OSDParser.SerializeLLSDXmlString(new OSDMap
@@ -393,6 +404,96 @@ namespace NexVerse.RegionModules.Voice
}
}
private async Task PushPositionsAsync()
{
if (Interlocked.Exchange(ref m_PositionUpdateRunning, 1) != 0)
return;
try
{
OglVoiceProviderDescriptor provider = ReadyProvider();
Scene scene = m_Scene;
if (provider == null || scene == null || m_Sessions.IsEmpty)
return;
// Never trust viewer-reported location: only the current root
// agent's ScenePresence/estate/parcel assertion is sent.
// Bounded concurrency avoids overwhelming simulator threads.
using SemaphoreSlim gate = new(8, 8);
List<Task> batch = new();
foreach (var item in m_Sessions)
{
await gate.WaitAsync().ConfigureAwait(false);
batch.Add(PushOnePositionAsync(scene, provider,
item.Key, item.Value, gate));
}
await Task.WhenAll(batch).ConfigureAwait(false);
}
catch (Exception e)
{
m_Log.Warn("[OGL-VOICE]: Spatial sync error: " + e.Message);
}
finally
{
Interlocked.Exchange(ref m_PositionUpdateRunning, 0);
}
}
private async Task PushOnePositionAsync(Scene scene,
OglVoiceProviderDescriptor provider, UUID avatar, VoiceSession session,
SemaphoreSlim gate)
{
try
{
OglVoiceAdmission current = null;
bool present = scene == m_Scene &&
OglVoiceRegionAdmission.TryCreate(scene, avatar,
provider.tenant_id, provider.hypergrid_guests,
out current) &&
current.SessionId == session.AgentSessionId;
OglVoiceMediaExchange exchange = new()
{
operation = present ? "position" : "leave",
admission = present ? current : session.LastAdmission,
viewer_session = session.ViewerSession
};
if (!present)
m_Sessions.TryRemove(avatar, out _);
if (present && !current.PositionValid)
return;
byte[] data = JsonSerializer.SerializeToUtf8Bytes(exchange);
if (data.Length > OglVoiceMediaProof.MaximumPayloadBytes)
return;
using HttpRequestMessage request =
new(HttpMethod.Post, new Uri(provider.media_gateway_url));
request.Content = new ByteArrayContent(data);
request.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
long stamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
string nonce = OglVoiceDiscoveryProof.NewNonce();
request.Headers.TryAddWithoutValidation("X-OGLVoice-Node", m_NodeId);
request.Headers.TryAddWithoutValidation("X-OGLVoice-Timestamp",
stamp.ToString(System.Globalization.CultureInfo.InvariantCulture));
request.Headers.TryAddWithoutValidation("X-OGLVoice-Nonce", nonce);
request.Headers.TryAddWithoutValidation("X-OGLVoice-Signature",
OglVoiceMediaProof.Sign(m_Key, m_NodeId, stamp, nonce, data));
using HttpResponseMessage response = await m_Http.SendAsync(
request, HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
m_Log.DebugFormat("[OGL-VOICE]: Spatial sync rejected ({0})",
(int)response.StatusCode);
}
catch (Exception e)
{
m_Log.Debug("[OGL-VOICE]: Spatial sync temporarily unavailable: " + e.Message);
}
finally
{
gate.Release();
}
}
private static void Error(IOSHttpResponse resp, HttpStatusCode code)
{
resp.StatusCode = (int)code;
@@ -74,7 +74,19 @@ namespace NexVerse.RegionModules.Voice
SessionId = Guid.Parse(circuit.SessionID.ToString()),
IsHypergridGuest = guest,
HomeGridOrigin = home,
VoiceAllowed = true
VoiceAllowed = true,
PositionValid = float.IsFinite(sp.AbsolutePosition.X) &&
float.IsFinite(sp.AbsolutePosition.Y) &&
float.IsFinite(sp.AbsolutePosition.Z),
PositionX = sp.AbsolutePosition.X,
PositionY = sp.AbsolutePosition.Y,
PositionZ = sp.AbsolutePosition.Z,
// Local avatar rotation is authoritative; quaternion yaw.
Heading = (float)Math.Atan2(
2.0 * (sp.Rotation.W * sp.Rotation.Z +
sp.Rotation.X * sp.Rotation.Y),
1.0 - 2.0 * (sp.Rotation.Y * sp.Rotation.Y +
sp.Rotation.Z * sp.Rotation.Z))
};
return true;
}
+2 -1
View File
@@ -30,7 +30,8 @@ Das Release bündelt den gesamten geplanten Meilenstein **0.9.3.9** (OGLVoice un
- [x] HG-Identitaetskern: kanonische Heim-Grid-Origin + Original-Avatar-UUID (SHA-256), C#-Regressionstests. **Noch keine authentifizierte HG-Session-/Voice-Anbindung.**
- [ ] Firestorm-WebRTC-CAPS-/Signalisierungs-/Media-Gateway mit funktionierendem Audio, nicht nur Browser-Demo.
- [x] **Erster realer Go Media-Gateway-Daemon:** Pion v4 terminiert SDP/ICE/DTLS/SRTP/SCTP, LiveKit Go-SDK publiziert Firestorm-Opus-RTP und leitet den ersten empfangenen fremden Opus-Track zum Viewer; echte LiveKit-Roster-/Speaking-Datenkanael-Meldungen, Node-Tenant-HMAC/Replay, Quoten, Session-Reaper. Eigenes Go-CI mit lokaler Pion-WebRTC-SDP-Verhandlung. **Noch kein simultaner Multi-Speaker-/Spatial-Audio-Mixer, kein echter Zwei-Firestorm-Plus-HG-Livetest, keine Stable-Freigabe.**
- [ ] Operative LiveKit-/STUN-/TURN-Konfiguration, echtes Firestorm-Audio im Grid, Multi-Speaker-Opus-Mixing, durchgaengige HG-Guest-Voice-Anzeige, sichere Revoke-Pipeline sowie Quota- und Belastungsabnahme.
- [x] **Multi-Speaker-Opus-Spatial-Mixer (Dev):** eigene libopus-Decoder je LiveKit-Track, 20-ms-Stereo-Mix/Opus-Encoder je Firestorm-Zuhoerer, 40-m-Hoergrenze, Distanzdaempfung/Panning/Clipping, begrenzte Jitter-Puffer/Quellen, signierte Positions-/Heading-Updates aus `ScenePresence` und Eventweitergabe ueber LiveKit. Vollstaendige Race-/PCM-/RTP-/Audio-CI erforderlich; kein Nachweis im produktiven Grid.
- [ ] Operative LiveKit-/STUN-/TURN-Konfiguration, echtes Firestorm-Audio im Grid mit mehreren Sprechern, HRTF/Occlusion und Multi-Region-Audio, durchgaengige HG-Guest-Voice-Anzeige, sichere Revoke-Pipeline sowie Quota- und Belastungsabnahme.
- [x] **Firestorm-LLSD-CAPS/SDP/ICE-Adapter:** `ProvisionVoiceAccountRequest`, `VoiceSignalingRequest`, `VoiceServerType=webrtc` bei signierter und ausdruecklich freigeschalteter MediaGatewayUrl; signierte, beschraenkte JSON-Media-Exchange und .NET-Protokoll-Regressionen. Default `EnableFirestormGateway=false`. **Eine tatsaechliche kompatible SDP/DTLS/SRTP/SCTP-/LiveKit-Media-Bridge existiert dadurch noch NICHT.**
- [x] **Remote-Speaker-Wire-Format:** Firestorm-konforme JSON-Nachrichten `j`/ `p` / `v` / `l` nach wahrer Avatar-UUID samt Tests. **Noch keine LiveKit-Mediaquelle, die diese Nachrichten in echte WebRTC-Datenkanaele sendet.**
- [ ] Spatial-/Parcel-Voice mit Autorität des Simulators, Echtzeitpositionen und Distanz-/Richtungsmodell.
+44 -1
View File
@@ -15,6 +15,49 @@ Firestorm-Viewer (Audio + DataChannel)
Der Dienst liegt unter `services/oglvoice-media`. Ein einziges Media-Service-Cluster kann die Nodes vieler Grids aufnehmen. Nur die **serverseitige** Node-/Tenant-Konfiguration legt Rechte fest. Der `nexverse`-Mandant bekommt `max_sessions=0,max_regions=0` fuer **keine Lizenz-Quoten**. Fuer andere Mandanten koennen Limits gesetzt werden.
## 0.9.3.10 Dev: simultaner Opus-Spatial-Mixer
Dieser Entwicklungszweig ersetzt den vorherigen Ein-Sprecher-Downlink durch
**pro Zuhörer individuelle Stereo-Mischungen**. Der Media-Server decodiert
jede empfangene LiveKit-Opus-Spur getrennt (libopus), puffert höchstens fünf
20-ms-Frames und mischt die aktuell hörbaren Stimmen alle 20 ms als Stereo-PCM.
Entfernung (40 m Hörgrenze), Hörerrichtung, Equal-Power-Panning, Pegelabfall
und weiche Begrenzung werden in `spatial_mixer.go` berechnet. Die Summe wird
als **neuer Opus-Stream** an Firestorm encodiert.
**Positionsdaten stammen ausschließlich aus der authentifizierten
`ScenePresence` im Simulator**, nicht aus Viewer-Formularen. Der Simulator
sendet bei der Voice-Session-Einrichtung eine Positions-/Blickrichtungsprobe
und aktualisiert sie über signierte `position`-Requests alle zwei Sekunden.
Der Media-Server teilt bestätigte Veränderungen über den bestehenden LiveKit-
Raum und dessen Datenkanal mit den anderen Zuhörer-Mixern. Ist die Position
unbekannt, wird der betreffende Sprecher nicht hörbar. Bei entfallender
Estate-/Parcel-/Root-Agent-Berechtigung wird ein `leave` gesendet.
**Grenzen:** maximal 64 gleichzeitig abonnierten Quellen pro Zuhörer und
24 stärkste Quellen pro 20-ms-Mix als CPU-Sicherungsgrenze (keine
Lizenzbegrenzung der Avatare/Regionen). Es ist ein stereophoner
Entfernungs-/Richtungsmixer, **keine** vollständige HRTF-Ohrsimulation,
akustische Abschattung/Reflexion, lückenloser Regionsgrenzen-Mix oder
professionelle adaptive Jitter-/Loss-Concealment-Engine.
Für den neuen Mixer benötigt der **Build** jetzt `pkg-config` und
`libopus-dev`; die **Laufzeit** benötigt die dynamische Systembibliothek
`libopus.so.0` (Debian: `libopus0`). Mit dem Build-Tag
`nolibopusfile` sind keine `libopusfile`-Header nötig:
```bash
sudo apt-get install -y pkg-config libopus-dev
go mod tidy
go test -tags nolibopusfile -race ./...
go build -tags nolibopusfile -trimpath -o oglvoice-media .
```
Die automatische Go-CI installiert die libopus-Build-Abhängigkeiten und
testet simultane Opus-Signale, Panning, Dämpfung, 40-ms-Paket-Splitting,
Clipping, Quoten und signierte Positionsupdates. **Das ist noch kein
Nachweis der Funktion im echten Firestorm mit drei Sprechern.**
### Bereits implementiert
- Echte Pion-v4-`PeerConnection`, WebRTC Offer/Answer, ICE-Gathering, Trickle-ICE, DTLS/SRTP und SCTP-Datenkanal des Firestorm-Viewers.
@@ -26,7 +69,7 @@ Der Dienst liegt unter `services/oglvoice-media`. Ein einziges Media-Service-Clu
### Grenzen dieser Ausbaustufe (wichtige Release-Blocker)
- **Noch kein Opus-Mixer:** Es kann pro Firestorm-Viewer gegenwaertig **nur ein einzelner entfernter Audiostream gleichzeitig** wiedergegeben werden; der Media-Service und LiveKit transportieren zwar mehrere publizierte Teilnehmer, mischen sie aber noch nicht zu einem raeumlichen Summensignal. Der fuer den vollstaendigen Vivox-Ersatz erforderliche Mehrsprecher-Spatial-Mixer, Sichtweitenabstand, Orientierung und Parzellengrenzen sind offen.
- **Noch kein Opus-Mixer:** Die aktuelle Spatial-Mixer-Ausbaustufe kann mehrere entfernte Audiostreams gleichzeitig decodieren und als Stereo-Opus-Downlink mischen; ein produktionserprobtes HRTF-System mit akustischer Abschattung, Loss Concealment und Mesh-Hindernissen bleibt offen. Der fuer den vollstaendigen Vivox-Ersatz erforderliche Mehrsprecher-Spatial-Mixer, Sichtweitenabstand, Orientierung und Parzellengrenzen sind offen.
- **Noch keine Full-E2E-Bestaetigung mit echten Firestorm-Viewern** und produktivem LiveKit sowie konkreter Firewall-/ICE-Konfiguration. Die CI uebt reale lokale Pion-WebRTC-Verbindungen aus, kein produktives Grid.
- **Keine komplette zentrale Revoke-/Presence-Kontrollschicht:** der Go-Gateway loescht Sitzungen bei `leave`, Peer-Ausfall, Leerlauf und Shutdown. Ein plattformuebergreifender zweifelsfreier Logout-/Teleport-/Rollenwechsel-Push aus Robust zum Gateway fehlt.
- **Voice-orb Status:** Der Code sendet Roster und LiveKit-Aktivitaetsereignisse an alle autorisierten Viewer-Datenkanaele. Ob die Viewer die graue Kugel in jeder Hypergrid-Konstellation zeigen, muss real getestet werden.
+1
View File
@@ -4,5 +4,6 @@ go 1.26.8
require (
github.com/livekit/server-sdk-go/v2 v2.18.1
github.com/hraban/opus v0.0.0-20260625065747-1d0df3f46084
github.com/pion/webrtc/v4 v4.2.19
)
+44 -18
View File
@@ -2,6 +2,7 @@
package main
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -12,7 +13,7 @@ import (
"strings"
"sync"
"sync/atomic"
"time"
"time"
lksdk "github.com/livekit/server-sdk-go/v2"
"github.com/pion/webrtc/v4"
@@ -24,8 +25,10 @@ type peerState struct {
admission admission
pc *webrtc.PeerConnection
room *lksdk.Room
downlink *webrtc.TrackLocalStaticRTP
downlinkBusy atomic.Bool
downlink *webrtc.TrackLocalStaticSample
mixer *spatialMixer
mediaCancel context.CancelFunc
mixerStarted sync.Once
lastSeen time.Time
lastUnix atomic.Int64
closeOnce sync.Once
@@ -60,12 +63,14 @@ func startPeer(cfg config, a admission, id string, onClose func()) (*peerState,
if err != nil { return nil, fmt.Errorf("Pion: %w", err) }
p.pc = pc
// One downlink transceiver matches Firestorm's unmodified audio offer.
// Multi-speaker *mixed* downlink is not implemented: at most one remote
// LiveKit Opus track is forwarded. This is NOT full spatial audio.
p.downlink, err = webrtc.NewTrackLocalStaticRTP(
// One stereo Opus transceiver is a per-listener mix of all audible
// subscribed LiveKit participants. Mixing runs at a bounded 20ms cadence.
p.mixer, err = newSpatialMixer()
if err != nil { _ = pc.Close(); return nil, err }
p.mixer.setListener(admissionPosition(a))
p.downlink, err = webrtc.NewTrackLocalStaticSample(
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus,
ClockRate: 48000, Channels: 2}, "oglvoice-remote", "oglvoice")
ClockRate: audioRate, Channels: audioChannels}, "oglvoice-spatial", "oglvoice")
if err != nil { _ = pc.Close(); return nil, err }
sender, err := pc.AddTrack(p.downlink)
if err != nil { _ = pc.Close(); return nil, err }
@@ -123,6 +128,11 @@ func startPeer(cfg config, a admission, id string, onClose func()) (*peerState,
switch s {
case webrtc.PeerConnectionStateConnected:
p.touch()
p.mixerStarted.Do(func() {
ctx, cancel := context.WithCancel(context.Background())
p.mediaCancel = cancel
go p.mixer.stream(ctx, p.downlink.WriteSample)
})
case webrtc.PeerConnectionStateFailed, webrtc.PeerConnectionStateClosed:
p.close()
}
@@ -135,26 +145,41 @@ func startPeer(cfg config, a admission, id string, onClose func()) (*peerState,
rp *lksdk.RemoteParticipant) {
if track.Kind() != webrtc.RTPCodecTypeAudio ||
!strings.EqualFold(track.Codec().MimeType, webrtc.MimeTypeOpus) ||
!p.downlinkBusy.CompareAndSwap(false, true) {
return
}
p.mixer == nil { return }
identity := rp.Identity()
if !p.mixer.addSource(identity, parseParticipantPosition(rp.Metadata())) { return }
go func() {
defer p.downlinkBusy.Store(false)
for {
pkt, _, err := track.ReadRTP()
if err != nil { return }
if err := p.downlink.WriteRTP(pkt); err != nil { return }
}
defer p.mixer.removeSource(identity)
p.mixer.consumeOpus(identity, func() ([]byte, error) {
pkt, _, e := track.ReadRTP()
if e != nil { return nil, e }
return pkt.Payload, nil
})
}()
},
OnIsSpeakingChanged: func(participant lksdk.Participant) {
p.sendVoiceEvent(participant)
},
OnMetadataChanged: func(oldMetadata string, participant lksdk.Participant) {
if p.mixer != nil {
p.mixer.updateSource(participant.Identity(),
parseParticipantPosition(participant.Metadata()))
}
},
OnDataReceived: func(data []byte, params lksdk.DataReceiveParams) {
if p.mixer == nil || params.SenderIdentity == "" { return }
var pos spatialUpdate
if json.Unmarshal(data, &pos) == nil && pos.Protocol == spatialWire &&
validPosition(pos.position()) {
p.mixer.updateSource(params.SenderIdentity, pos.position())
}
},
},
OnParticipantConnected: func(rp *lksdk.RemoteParticipant) {
p.sendRoster(rp, false, true)
},
OnParticipantDisconnected: func(rp *lksdk.RemoteParticipant) {
if p.mixer != nil { p.mixer.removeSource(rp.Identity()) }
p.sendRoster(rp, true, false)
},
OnDisconnected: func() {
@@ -165,7 +190,7 @@ func startPeer(cfg config, a admission, id string, onClose func()) (*peerState,
// Participant metadata is sourced from the *authenticated simulator*,
// never from a viewer-provided room ID. All LiveKit participant secrets
// stay inside this media service.
meta, _ := json.Marshal(map[string]string{"avatar": strings.ToLower(a.AvatarID)})
meta, _ := json.Marshal(participantSpatialMetadata(a))
room, err := lksdk.ConnectToRoom(cfg.LiveKitURL, lksdk.ConnectInfo{
APIKey: cfg.LiveKitKey, APISecret: cfg.LiveKitSecret,
RoomName: roomID(a), ParticipantIdentity: participantID(a),
@@ -227,6 +252,7 @@ func (p *peerState) close() {
// Trigger shutdown on a separate goroutine to avoid deadlocking a
// Pion PeerConnectionState callback that itself holds locks.
go func() {
if p.mediaCancel != nil { p.mediaCancel() }
if p.room != nil { p.room.Disconnect() }
if p.pc != nil { _ = p.pc.Close() }
if p.onClose != nil { p.onClose() }
+8
View File
@@ -96,6 +96,11 @@ type admission struct {
HomeGridOrigin string `json:"HomeGridOrigin"`
IsHypergridGuest bool `json:"IsHypergridGuest"`
VoiceAllowed bool `json:"VoiceAllowed"`
PositionValid bool `json:"PositionValid"`
PositionX float64 `json:"PositionX"`
PositionY float64 `json:"PositionY"`
PositionZ float64 `json:"PositionZ"`
Heading float64 `json:"Heading"`
}
type iceCandidate struct {
Candidate string `json:"candidate"`
@@ -135,6 +140,9 @@ func validAdmission(node nodeConfig, a admission) error {
if len(a.HomeGridOrigin) > 1024 {
return errors.New("invalid home grid")
}
if a.PositionValid && !validPosition(admissionPosition(a)) {
return errors.New("invalid simulator-authenticated position")
}
return nil
}
+13 -1
View File
@@ -81,7 +81,7 @@ func (g *mediaServer) exchange(w http.ResponseWriter, req *http.Request) {
switch input.Operation {
case "offer":
g.offer(w, n, node, input)
case "trickle", "leave":
case "trickle", "leave", "position":
g.existing(w, node, input)
default:
jsonReply(w, http.StatusBadRequest, reply{Protocol: wireProtocol, Status: "invalid_operation"})
@@ -214,6 +214,18 @@ func (g *mediaServer) existing(w http.ResponseWriter, node string, e exchange) {
jsonReply(w, http.StatusOK, reply{Protocol: wireProtocol, Status: "closed"})
return
}
if e.Operation == "position" {
if !e.Admission.PositionValid || !validPosition(admissionPosition(e.Admission)) {
jsonReply(w, http.StatusBadRequest, reply{Protocol:wireProtocol,Status:"invalid_spatial_position"})
return
}
if err := p.updatePosition(e.Admission); err != nil {
jsonReply(w, http.StatusServiceUnavailable, reply{Protocol:wireProtocol,Status:"position_update_failed"})
return
}
jsonReply(w, http.StatusOK, reply{Protocol:wireProtocol,Status:"ok"})
return
}
if len(e.Candidates) > 32 || (len(e.Candidates) == 0 && !e.ICECompleted) {
jsonReply(w, http.StatusBadRequest, reply{Protocol: wireProtocol, Status: "bad_ice_candidates"})
return
+210
View File
@@ -0,0 +1,210 @@
// SPDX-License-Identifier: MPL-2.0
package main
import (
"context"
"errors"
"math"
"sync"
"time"
"github.com/hraban/opus"
"github.com/pion/webrtc/v4/pkg/media"
)
const (
audioRate = 48000
audioChannels = 2
audioFrame = 960 // 20 ms per channel
audioSamples = audioFrame * audioChannels
maxSources = 64
maxAudible = 24
maxDistance = 40.0
audioFrameTime = 20 * time.Millisecond
)
type voicePosition struct {
X, Y, Z float64
Heading float64 // viewer-forward heading in radians, 0 east
Valid bool
}
func validPosition(p voicePosition) bool {
return p.Valid && isFinite(p.X) && isFinite(p.Y) &&
isFinite(p.Z) && isFinite(p.Heading) &&
p.X >= -4096 && p.X <= 4096 && p.Y >= -4096 &&
p.Y <= 4096 && p.Z >= -4096 && p.Z <= 8192
}
func isFinite(n float64) bool { return !math.IsNaN(n) && !math.IsInf(n, 0) }
type audioSource struct {
frames chan []float32 // bounded low-latency jitter FIFO
pos voicePosition
}
type spatialMixer struct {
mu sync.RWMutex
listener voicePosition
sources map[string]*audioSource
encoder *opus.Encoder // accessed by single mix/encode loop only
}
// Each Firestorm viewer gets a separate mix: no audio from other tenants,
// and the listener itself is never included in its own returned audio.
func newSpatialMixer() (*spatialMixer, error) {
encoder, err := opus.NewEncoder(audioRate, audioChannels, opus.AppVoIP)
if err != nil { return nil, err }
if err = encoder.SetBitrate(48000); err != nil { return nil, err }
return &spatialMixer{sources: make(map[string]*audioSource), encoder: encoder}, nil
}
func (m *spatialMixer) setListener(pos voicePosition) {
if !validPosition(pos) { return }
m.mu.Lock()
m.listener = pos
m.mu.Unlock()
}
func (m *spatialMixer) addSource(identity string, pos voicePosition) bool {
if identity == "" { return false }
m.mu.Lock()
defer m.mu.Unlock()
if len(m.sources) >= maxSources { return false }
if _, ok := m.sources[identity]; ok { return false }
m.sources[identity] = &audioSource{frames: make(chan []float32, 5), pos: pos}
return true
}
func (m *spatialMixer) updateSource(identity string, pos voicePosition) {
if !validPosition(pos) { return }
m.mu.Lock()
if source := m.sources[identity]; source != nil { source.pos = pos }
m.mu.Unlock()
}
func (m *spatialMixer) removeSource(identity string) {
m.mu.Lock()
delete(m.sources, identity)
m.mu.Unlock()
}
func (m *spatialMixer) queueFrame(identity string, pcm []float32) {
if len(pcm) != audioSamples { return }
m.mu.RLock()
source := m.sources[identity]
if source == nil { m.mu.RUnlock(); return }
frame := append([]float32(nil), pcm...)
select {
case source.frames <- frame:
default:
// Drop the oldest frame rather than building unbounded latency.
select { case <-source.frames: default: }
select { case source.frames <- frame: default: }
}
m.mu.RUnlock()
}
type spatialGains struct{ left, right float64 }
func gains(listener, speaker voicePosition) spatialGains {
if !validPosition(listener) || !validPosition(speaker) {
return spatialGains{} // unknown location cannot bypass spatial policy
}
dx, dy, dz := speaker.X-listener.X, speaker.Y-listener.Y, speaker.Z-listener.Z
distance := math.Sqrt(dx*dx+dy*dy+dz*dz)
if distance >= maxDistance { return spatialGains{} }
// 1 m is full volume; radius and exponential curve are service policies.
attenuation := 1.0 / (1.0 + math.Pow(math.Max(0, distance-1)/9, 1.7))
// Equal-power stereo panning relative to listener orientation.
angle := math.Atan2(dy, dx) - listener.Heading
pan := -math.Sin(angle)
left := math.Sqrt((1-pan)/2) * math.Sqrt2
right := math.Sqrt((1+pan)/2) * math.Sqrt2
return spatialGains{left: attenuation*left, right: attenuation*right}
}
func (m *spatialMixer) mixFrame() []float32 {
// Mixer lock protects positions and session membership. Frame channels are
// bounded; never wait for remote speakers to send a packet.
m.mu.RLock()
defer m.mu.RUnlock()
out := make([]float32, audioSamples)
type audible struct {
src *audioSource
gain spatialGains
}
active := make([]audible, 0, len(m.sources))
for _, source := range m.sources {
g := gains(m.listener, source.pos)
if g.left+g.right > 0 {
active = append(active, audible{src:source, gain:g})
}
}
// Hard maximum work per listener/frame, even for Unlimited tenants.
// Prefer strongest/nearest sources; a call with >24 simultaneous
// speakers should use hierarchy mixing, not unlimited CPU work.
if len(active) > maxAudible {
for i:=0;i<maxAudible;i++ {
best:=i
for j:=i+1;j<len(active);j++ {
if active[j].gain.left+active[j].gain.right >
active[best].gain.left+active[best].gain.right {best=j}
}
active[i],active[best]=active[best],active[i]
}
active=active[:maxAudible]
}
for _, current := range active {
var pcm []float32
select { case pcm = <-current.src.frames: default: continue }
for j:=0;j<audioSamples;j+=2 {
// Mix each decoded source's stereo signal to mono first, then
// position it in the listener's stereo soundstage.
sample:=float64(pcm[j]+pcm[j+1])*0.5
out[j] += float32(sample*current.gain.left)
out[j+1] += float32(sample*current.gain.right)
}
}
// Smooth limiter to avoid hard clipping when many people speak at once.
for i,v:=range out {
if v > 1 || v < -1 {
out[i]=float32(math.Tanh(float64(v)))
}
}
return out
}
func (m *spatialMixer) encodeFrame(frame []float32) ([]byte,error) {
if len(frame)!=audioSamples {return nil,errors.New("invalid stereo PCM frame")}
buffer:=make([]byte, 4000)
n,err:=m.encoder.EncodeFloat32(frame,buffer)
if err!=nil {return nil,err}
return buffer[:n],nil
}
func (m *spatialMixer) stream(ctx context.Context, send func(media.Sample) error) {
tick:=time.NewTicker(audioFrameTime)
defer tick.Stop()
for {
select {
case <-ctx.Done():return
case <-tick.C:
audio:=m.mixFrame()
payload,err:=m.encodeFrame(audio)
if err!=nil {continue}
if err=send(media.Sample{Data:payload,Duration:audioFrameTime});err!=nil {return}
}
}
}
// Every subscribed remote Opus RTP track has its OWN decoder state. One
// packet may carry >20ms of audio; split into 20ms chunks for the mixer.
// Out-of-order RTP and loss concealment are still improvement areas.
func (m *spatialMixer) consumeOpus(identity string, read func() ([]byte,error)) {
decoder,err:=opus.NewDecoder(audioRate, audioChannels)
if err!=nil {return}
pending:=make([]float32,0,audioSamples*3)
for {
packet,e:=read()
if e!=nil {return}
if len(packet)==0 {continue}
pcm:=make([]float32,5760*audioChannels) // Opus maximum 120ms packet
n,e:=decoder.DecodeFloat32(packet,pcm)
if e!=nil || n<=0 || n>5760 {continue}
pending=append(pending,pcm[:n*audioChannels]...)
for len(pending)>=audioSamples {
m.queueFrame(identity,pending[:audioSamples])
pending=pending[audioSamples:]
}
}
}
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: MPL-2.0
package main
import (
"encoding/json"
"io"
"strconv"
"math"
"testing"
"github.com/hraban/opus"
)
func voicePos(x,y,z,heading float64) voicePosition {
return voicePosition{X:x,Y:y,Z:z,Heading:heading,Valid:true}
}
func TestSpatialMultiSpeakerMixAndRange(t *testing.T) {
m,err:=newSpatialMixer()
if err!=nil { t.Fatal(err) }
m.setListener(voicePos(0,0,20,0))
if !m.addSource("alice",voicePos(1,0,20,0)) ||
!m.addSource("bob",voicePos(1,0,20,0)) {
t.Fatal("two simultaneous speakers not admitted")
}
frame:=make([]float32,audioSamples)
for i:=range frame {frame[i]=0.15}
m.queueFrame("alice",frame)
m.queueFrame("bob",frame)
mixed:=m.mixFrame()
if mixed[0]<=0.15||mixed[1]<=0.15 {
t.Fatalf("multiple simultaneous speakers were not summed: %f / %f",mixed[0],mixed[1])
}
payload,err:=m.encodeFrame(mixed)
if err!=nil||len(payload)==0 {t.Fatalf("mixed Opus not encoded: %v",err)}
decoder,err:=opus.NewDecoder(audioRate,audioChannels)
if err!=nil {t.Fatal(err)}
decoded:=make([]float32,5760*audioChannels)
n,err:=decoder.DecodeFloat32(payload,decoded)
if err!=nil||n!=audioFrame {t.Fatalf("mixed stream could not be decoded: n=%d %v",n,err)}
m.updateSource("alice",voicePos(120,120,20,0))
m.updateSource("bob",voicePos(120,120,20,0))
m.queueFrame("alice",frame)
m.queueFrame("bob",frame)
far:=m.mixFrame()
for _,v:=range far {if v!=0 {t.Fatal("voice leaked beyond audible distance")}}
m.removeSource("bob")
m.removeSource("alice")
if len(m.sources)!=0 {t.Fatal("speaker cleanup")}
}
func TestSpatialStereoOrientation(t *testing.T) {
center:=voicePos(5,5,20,0)
onLeft:=voicePos(5,7,20,0)
l:=gains(center,onLeft)
if l.left<=l.right {t.Fatalf("speaker north of listener should pan left: %+v",l)}
center.Heading=math.Pi
r:=gains(center,onLeft)
if r.right<=r.left {t.Fatalf("turning around should move speaker to right: %+v",r)}
near:=gains(center,voicePos(6,5,20,0))
distant:=gains(center,voicePos(38,5,20,0))
if near.left+near.right <= distant.left+distant.right {t.Fatal("distance attenuation not applied")}
if gains(voicePosition{},voicePos(1,0,20,0)).left!=0 {
t.Fatal("unknown listener coordinates must remain inaudible")
}
if gains(center,voicePosition{}).left!=0 {
t.Fatal("unknown speaker location must remain inaudible")
}
}
func TestSpatialJitterBoundAndLimiting(t *testing.T) {
m,err:=newSpatialMixer();if err!=nil {t.Fatal(err)}
m.setListener(voicePos(0,0,20,0))
for i:=0;i<maxSources;i++ {
if !m.addSource("speaker-"+strconv.Itoa(i),voicePos(1,0,20,0)) {
t.Fatal("failed to admit speaker under cap")
}
}
if m.addSource("too-many",voicePos(1,0,20,0)) {t.Fatal("unbounded source count")}
pcm:=make([]float32,audioSamples)
for i:=range pcm {pcm[i]=0.9}
for source:=range m.sources {
for i:=0;i<20;i++ {m.queueFrame(source,pcm)}
if len(m.sources[source].frames)>5 {t.Fatal("unbounded audio jitter queue")}
}
out:=m.mixFrame()
if out[0]>1||out[0] < -1||out[1]>1||out[1] < -1 {
t.Fatalf("sample limiter failed: %v",out[:2])
}
}
func TestSpatialOpusPacketSplit(t *testing.T) {
m,err:=newSpatialMixer();if err!=nil {t.Fatal(err)}
m.addSource("two-frames",voicePos(1,1,20,0))
enc,err:=opus.NewEncoder(audioRate,audioChannels,opus.AppVoIP)
if err!=nil {t.Fatal(err)}
pcm:=make([]float32,audioSamples*2) // 40ms
for i:=range pcm {pcm[i]=float32(0.1*math.Sin(float64(i)*0.02))}
buf:=make([]byte,4000)
n,err:=enc.EncodeFloat32(pcm,buf)
if err!=nil {t.Fatal(err)}
count:=0
m.consumeOpus("two-frames",func()([]byte,error){
if count>0 {return nil,io.EOF}
count++
return buf[:n],nil
})
if got:=len(m.sources["two-frames"].frames);got!=2 {
t.Fatalf("40ms Opus packet must split into two 20ms frames, got %d",got)
}
}
func TestPositionsStayWithinTrustedRoom(t *testing.T) {
local:=sampleAdmission("nexverse")
local.PositionValid=true
local.PositionX=12
local.PositionY=17
local.PositionZ=22
local.Heading=.5
if !validPosition(admissionPosition(local)) {t.Fatal("verified position rejected")}
meta,err:=json.Marshal(participantSpatialMetadata(local))
if err!=nil {t.Fatal(err)}
pos:=parseParticipantPosition(string(meta))
if pos.X!=12||pos.Y!=17||!pos.Valid {
t.Fatalf("room metadata coordinates: %+v",pos)
}
if parseParticipantPosition(`{"avatar":"someone"}`).Valid {
t.Fatal("unknown room metadata must remain silent")
}
local.PositionX=math.NaN()
if validPosition(admissionPosition(local)) {t.Fatal("NaN position accepted")}
}
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: MPL-2.0
package main
import (
"encoding/json"
"errors"
"strings"
)
const spatialWire = "oglvoice-spatial-v1"
// Positions originate from an authenticated simulator Scene, never viewer
// messages. LiveKit broadcasts are accepted only under the actual sender
// participant identity in the same pre-authorized region room.
type spatialUpdate struct {
Protocol string `json:"protocol"`
X float64 `json:"x"`
Y float64 `json:"y"`
Z float64 `json:"z"`
Heading float64 `json:"heading"`
}
func (v spatialUpdate) position() voicePosition {
return voicePosition{X:v.X,Y:v.Y,Z:v.Z,Heading:v.Heading,Valid:v.Protocol==spatialWire}
}
func admissionPosition(a admission) voicePosition {
return voicePosition{X:a.PositionX,Y:a.PositionY,Z:a.PositionZ,
Heading:a.Heading, Valid:a.PositionValid}
}
func participantSpatialMetadata(a admission) map[string]interface{} {
return map[string]interface{}{
"avatar": strings.ToLower(a.AvatarID),
"position": spatialUpdate{Protocol:spatialWire, X:a.PositionX,
Y:a.PositionY, Z:a.PositionZ, Heading:a.Heading},
"position_valid": a.PositionValid,
}
}
func parseParticipantPosition(metadata string) voicePosition {
var decoded struct {
Position spatialUpdate `json:"position"`
PositionValid bool `json:"position_valid"`
}
if len(metadata)>2048 || json.Unmarshal([]byte(metadata),&decoded)!=nil ||
!decoded.PositionValid { return voicePosition{} }
pos:=decoded.Position.position()
if !validPosition(pos) { return voicePosition{} }
return pos
}
func (p *peerState) updatePosition(a admission) error {
pos:=admissionPosition(a)
if !validPosition(pos) { return errors.New("invalid position") }
if p.mixer==nil { return errors.New("missing audio mixer") }
p.mixer.setListener(pos)
p.touch()
if p.room!=nil {
wire:=spatialUpdate{Protocol:spatialWire,X:pos.X,Y:pos.Y,
Z:pos.Z,Heading:pos.Heading}
data,_:=json.Marshal(wire)
// Only the room's authenticated media participant can transmit.
if err:=p.room.LocalParticipant.PublishData(data); err!=nil {return err}
}
return nil
}
@@ -0,0 +1,57 @@
// SPDX-License-Identifier: MPL-2.0
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestSignedSpatialUpdatesBoundToNodeAndSession(t *testing.T) {
cfg:=testConfig()
g:=newMediaServer(cfg)
now:=time.Unix(1791568800,0)
g.now=func()time.Time{return now}
a:=sampleAdmission("nexverse")
a.PositionValid=true
a.PositionX=12
a.PositionY=15
a.PositionZ=25
mix,err:=newSpatialMixer()
if err!=nil {t.Fatal(err)}
peer:=&peerState{id:"media-session",node:"sim-freiburg",
admission:a,mixer:mix,lastSeen:time.Now()}
peer.touch()
g.sessions[sessionKey("sim-freiburg",a)]=peer
send:=func(update admission,session,nonce string) *httptest.ResponseRecorder {
t.Helper()
wire:=exchange{Protocol:wireProtocol,Operation:"position",
Admission:update,ViewerSession:session}
data,_:=json.Marshal(wire)
request:=signedRequest(t,exchangeRoute,"sim-freiburg",
cfg.Nodes["sim-freiburg"],data,now,nonce)
out:=httptest.NewRecorder()
g.exchange(out,request)
return out
}
result:=send(a,"media-session",strings.Repeat("b",32))
if result.Code!=http.StatusOK {
t.Fatalf("signed spatial update failed: %d: %s",result.Code,result.Body)
}
if mix.listener.X!=12||mix.listener.Y!=15 {t.Fatal("mixer missed current verified location")}
a.PositionX=35
a.Heading=1.1
result=send(a,"wrong-media-session",strings.Repeat("c",32))
if result.Code!=http.StatusForbidden {t.Fatal("stolen viewer_session accepted")}
if mix.listener.X!=12 {t.Fatal("invalid token mutated position")}
result=send(a,"media-session",strings.Repeat("d",32))
if result.Code!=http.StatusOK||mix.listener.X!=35 {
t.Fatal("real-time position update not applied")
}
a.PositionValid=false
result=send(a,"media-session",strings.Repeat("e",32))
if result.Code!=http.StatusBadRequest {t.Fatal("invalid position accepted")}
}