Add server-side spatial audio with HRTF, occlusion and adaptive quality
This commit is contained in:
@@ -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"
|
||||
@@ -250,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"`
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)}
|
||||
}
|
||||
@@ -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) }
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
|
||||
// Sizes are full dimensions in metres; 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 [3]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 [3]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
|
||||
for i := 0; i < 3; i++ {
|
||||
if !finite(object.Center[i]) || math.Abs(object.Center[i]) >= 1e7 || !finite(object.Size[i]) || object.Size[i] < 1e-4 || object.Size[i] > 1e6 {
|
||||
return nil, fmt.Errorf("invalid bounds 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: [3]float64{object.Size[0] / 2, object.Size[1] / 2, object.Size[2] / 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
|
||||
}
|
||||
|
||||
// The segment/OBB slab test clips t to [0,1], not to an infinite ray. Each
|
||||
// object attenuates once, including when an endpoint is inside the volume.
|
||||
// Boundary contact counts as an intersection; no thickness-based absorption.
|
||||
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}
|
||||
lo, hi := 0.0, 1.0
|
||||
for i, axis := range o.axes {
|
||||
p := start.X*axis.X + start.Y*axis.Y + start.Z*axis.Z
|
||||
d := delta.X*axis.X + delta.Y*axis.Y + delta.Z*axis.Z
|
||||
if math.Abs(d) < 1e-10 {
|
||||
if p < -o.half[i] || p > o.half[i] {
|
||||
return false
|
||||
}
|
||||
continue
|
||||
}
|
||||
t0, t1 := (-o.half[i]-p)/d, (o.half[i]-p)/d
|
||||
if t0 > t1 {
|
||||
t0, t1 = t1, t0
|
||||
}
|
||||
lo = math.Max(lo, t0)
|
||||
hi = math.Min(hi, t1)
|
||||
if lo > hi {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user