Add server-side spatial audio with HRTF, occlusion and adaptive quality
Test / test (pull_request) Canceled after 0s
PR Slack Notifier / notify-devs (pull_request) Canceled after 0s

This commit is contained in:
2026-10-05 17:29:30 +03:00
parent 44b791ad50
commit 909e51bc0a
46 changed files with 5255 additions and 0 deletions
+24
View File
@@ -144,6 +144,7 @@ type MediaTrackReceiver struct {
onMediaLossFeedback func(dt *sfu.DownTrack, report *rtcp.ReceiverReport)
onClose []func(isExpectedToResume bool)
onCodecRegression func(old, new webrtc.RTPCodecParameters)
rtpObserver func(webrtc.RTPCodecParameters, *buffer.ExtPacket)
*MediaTrackSubscriptions
}
@@ -228,6 +229,11 @@ func (t *MediaTrackReceiver) SetupReceiver(receiver sfu.TrackReceiver, priority
}
t.receivers = receivers
if observer, ok := receiver.(interface {
SetRTPObserver(func(webrtc.RTPCodecParameters, *buffer.ExtPacket))
}); ok {
observer.SetRTPObserver(t.rtpObserver)
}
onSetupReceiver := t.onSetupReceiver
t.lock.Unlock()
@@ -248,6 +254,24 @@ func (t *MediaTrackReceiver) SetupReceiver(receiver sfu.TrackReceiver, priority
}
}
// SetRTPObserver also applies to receivers added after publication (codec changes).
func (t *MediaTrackReceiver) SetRTPObserver(fn func(webrtc.RTPCodecParameters, *buffer.ExtPacket)) {
t.lock.Lock()
t.rtpObserver = fn
for _, r := range t.receivers {
receiver := r.TrackReceiver
if dummy, ok := receiver.(*DummyReceiver); ok {
receiver = dummy.Receiver()
}
if observer, ok := receiver.(interface {
SetRTPObserver(func(webrtc.RTPCodecParameters, *buffer.ExtPacket))
}); ok {
observer.SetRTPObserver(fn)
}
}
t.lock.Unlock()
}
func (t *MediaTrackReceiver) HandleReceiverCodecChange(r sfu.TrackReceiver, codec webrtc.RTPCodecParameters, state sfu.ReceiverCodecState) {
// TODO: we only support codec regress to backup codec now, so the receiver will not be available
// once fallback / regression happens.
+46
View File
@@ -152,6 +152,8 @@ type Room struct {
onStateChangeMu sync.Mutex
localParticipantListener types.LocalParticipantListener
participantTelemetryListener types.ParticipantTelemetryListener
spatial *spatialAudioRoom
spatialErr error
}
type ParticipantOptions struct {
@@ -289,6 +291,10 @@ func NewRoom(
}),
}
r.trackManager = NewRoomTrackManager(r.logger)
r.spatial, r.spatialErr = newSpatialAudioRoom(r)
if r.spatialErr != nil {
r.logger.Errorw("spatial audio initialization failed", r.spatialErr)
}
r.localParticipantListener = &localParticipantListener{room: r}
r.participantTelemetryListener = &participantTelemetryListener{room: r}
@@ -451,6 +457,12 @@ func (r *Room) Join(
if r.IsClosed() {
return ErrRoomClosed
}
if r.spatialErr != nil {
return spatialJoinError(r.spatialErr)
}
if r.spatial != nil && len(r.participants) >= r.spatial.config.MaxParticipants {
return ErrMaxParticipantsExceeded
}
if r.participants[participant.Identity()] != nil {
return ErrAlreadyJoined
@@ -595,6 +607,9 @@ func (r *Room) ResumeParticipant(
if err := p.SendParticipantUpdate(updates); err != nil {
return err
}
if r.spatial != nil {
go r.attachSpatial(p)
}
_ = p.SendRoomUpdate(r.ToProto())
p.ICERestart(iceConfig)
@@ -727,6 +742,13 @@ func (r *Room) ResolveMediaTrackForSubscriber(sub types.LocalParticipant, trackI
res.TrackRemovedNotifier = r.trackManager.GetOrCreateTrackRemoveNotifier(trackID)
res.PublisherIdentity = info.PublisherIdentity
res.PublisherID = info.PublisherID
if output, ok := info.Track.(*spatialPublication); ok {
res.HasPermission = output.target == sub.ID()
return res
}
if r.spatial != nil && info.Track.Kind() == livekit.TrackType_AUDIO {
return res
}
pub := r.GetParticipantByID(info.PublisherID)
// when publisher is not found, we will assume it doesn't have permission to access
@@ -820,6 +842,9 @@ func (r *Room) Close(reason types.RoomCloseReason) {
r.lock.Unlock()
r.logger.Infow("closing room", "reason", reason)
if r.spatial != nil {
r.spatial.close()
}
participantCloseReason := reason.ToParticipantCloseReason()
for _, p := range r.GetParticipants() {
_ = p.Close(true, participantCloseReason, false)
@@ -1075,6 +1100,9 @@ func (r *Room) createJoinResponseLocked(
// a ParticipantImpl in the room added a new track, subscribe other participants to it
func (r *Room) onTrackPublished(participant types.Participant, track types.MediaTrack) {
r.trackManager.AddTrack(track, participant.Identity(), participant.ID())
if r.spatial != nil {
r.spatial.published(participant, track)
}
// publish participant update, since track state is changed
r.broadcastParticipantState(participant, broadcastOptions{skipSource: true})
@@ -1082,6 +1110,9 @@ func (r *Room) onTrackPublished(participant types.Participant, track types.Media
r.lock.RLock()
// subscribe all existing participants to this MediaTrack
for _, existingParticipant := range r.participants {
if r.spatial != nil && track.Kind() == livekit.TrackType_AUDIO {
continue
}
if existingParticipant == participant {
// skip publishing participant
continue
@@ -1245,6 +1276,9 @@ func (r *Room) onStateChange(p types.LocalParticipant) {
switch p.State() {
case livekit.ParticipantInfo_ACTIVE:
if r.spatial != nil {
go r.attachSpatial(p)
}
// subscribe participant to existing published tracks
r.subscribeToExistingTracks(p, false)
@@ -1290,6 +1324,12 @@ func (r *Room) onStateChange(p types.LocalParticipant) {
}
func (r *Room) onDataMessage(source types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket) {
if r.spatial != nil && r.spatial.scene(source, kind, dp) {
return
}
if r.spatial != nil && r.spatial.pose(source, dp) {
return
}
if kind == livekit.DataPacket_RELIABLE && source != nil && dp.GetSequence() > 0 {
data, err := proto.Marshal(dp)
if err != nil {
@@ -1455,6 +1495,9 @@ func (r *Room) RemoveParticipant(
}
r.lock.Unlock()
r.protoProxy.MarkDirty(immediateChange)
if r.spatial != nil {
r.spatial.remove(p)
}
if !p.HasConnected() {
fields := append(
@@ -1518,6 +1561,9 @@ func (r *Room) subscribeToExistingTracks(p types.LocalParticipant, isSync bool)
// subscribe to all
if autoSubscribe {
for _, track := range op.GetPublishedTracks() {
if r.spatial != nil && track.Kind() == livekit.TrackType_AUDIO {
continue
}
trackIDs = append(trackIDs, track.ID())
p.SubscribeToTrack(track.ID(), isSync)
}
+301
View File
@@ -0,0 +1,301 @@
// Copyright 2026 Sverse contributors. Licensed under the Apache License, Version 2.0.
package rtc
import (
"crypto/rand"
"encoding/binary"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/livekit-server/pkg/sfu/buffer"
"github.com/livekit/livekit-server/pkg/spatialaudio"
"github.com/livekit/mediatransportutil"
"github.com/livekit/protocol/codecs/mime"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/guid"
"github.com/livekit/protocol/utils/mono"
"github.com/pion/rtp"
"github.com/pion/webrtc/v4"
"google.golang.org/protobuf/proto"
)
type spatialPublication struct {
*MediaTrackReceiver
target livekit.ParticipantID
receiver *sfu.ReceiverBase
buffer *buffer.Buffer
ssrc uint32
sequence uint16
packets uint32
octets uint64
lastSR time.Time
lastTimestamp uint32
timestampCycles uint64
}
var _ types.MediaTrack = (*spatialPublication)(nil)
func (t *spatialPublication) Logger() logger.Logger { return t.MediaTrackReceiver.params.Logger }
func (t *spatialPublication) ToProto() *livekit.TrackInfo { return t.TrackInfoClone() }
func (t *spatialPublication) OnTrackSubscribed() {}
func (t *spatialPublication) GetTemporalLayerForSpatialFps(mime.MimeType, int32, uint32) int32 {
return 0
}
func (t *spatialPublication) AddSubscriber(p types.LocalParticipant) (types.SubscribedTrack, error) {
if p.ID() != t.target {
return nil, ErrNoTrackPermission
}
return t.MediaTrackReceiver.AddSubscriber(p)
}
func (t *spatialPublication) Close(resume bool) {
t.receiver.Close("spatial output closed", true)
t.MediaTrackReceiver.Close(resume)
}
func (t *spatialPublication) Write(payload []byte, timestamp uint32) error {
p := rtp.Packet{Header: rtp.Header{Version: 2, PayloadType: 111, SequenceNumber: t.sequence, Timestamp: timestamp, SSRC: t.ssrc}, Payload: payload}
b, err := p.Marshal()
if err != nil {
return err
}
t.sequence++
if _, err = t.buffer.Write(b); err != nil {
return err
}
t.packets++
t.octets += uint64(len(payload))
if timestamp < t.lastTimestamp {
t.timestampCycles += 1 << 32
}
t.lastTimestamp = timestamp
now := time.Now()
if now.Sub(t.lastSR) >= time.Second {
t.lastSR = now
at := mono.UnixNano()
t.buffer.SetSenderReportData(&livekit.RTCPSenderReportState{RtpTimestamp: timestamp, RtpTimestampExt: t.timestampCycles + uint64(timestamp), NtpTimestamp: uint64(mediatransportutil.ToNtpTime(now)), At: at, AtAdjusted: at, Packets: t.packets, Octets: t.octets})
}
return nil
}
func newSpatialPublication(r *Room, p types.LocalParticipant) (*spatialPublication, error) {
var seed [6]byte
if _, err := rand.Read(seed[:]); err != nil {
return nil, err
}
t := &spatialPublication{target: p.ID(), ssrc: binary.LittleEndian.Uint32(seed[:4]), sequence: binary.LittleEndian.Uint16(seed[4:])}
pubID := livekit.ParticipantID(guid.New("PA_"))
trackID := guid.New("TR_")
info := &livekit.TrackInfo{Sid: trackID, Name: "spatial_mix", Type: livekit.TrackType_AUDIO, Source: livekit.TrackSource_UNKNOWN, MimeType: webrtc.MimeTypeOpus, Stereo: true, DisableDtx: true, DisableRed: true, AudioFeatures: []livekit.AudioTrackFeature{livekit.AudioTrackFeature_TF_STEREO, livekit.AudioTrackFeature_TF_NO_DTX}, Codecs: []*livekit.SimulcastCodecInfo{{MimeType: webrtc.MimeTypeOpus}}}
codec := webrtc.RTPCodecParameters{RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48000, Channels: 2, SDPFmtpLine: "minptime=10;stereo=1;sprop-stereo=1;useinbandfec=1"}, PayloadType: 111}
t.MediaTrackReceiver = NewMediaTrackReceiver(MediaTrackReceiverParams{MediaTrack: t, ParticipantID: func() livekit.ParticipantID { return pubID }, ParticipantIdentity: livekit.ParticipantIdentity("__spatial_" + string(p.ID())), ParticipantVersion: 1, ReceiverConfig: r.config.Receiver, SubscriberConfig: r.config.Subscriber, AudioConfig: *r.audioConfig, TelemetryListener: func() types.ParticipantTelemetryListener { return types.NullParticipantTelemetryListener{} }, Logger: r.logger}, info)
t.receiver = sfu.NewReceiverBase(sfu.ReceiverBaseParams{TrackID: livekit.TrackID(trackID), StreamID: string(pubID), Kind: webrtc.RTPCodecTypeAudio, Codec: codec, Logger: r.logger}, info, sfu.ReceiverCodecStateNormal)
t.buffer = buffer.NewBuffer(t.ssrc, r.config.Receiver.PacketBufferSizeVideo, r.config.Receiver.PacketBufferSizeAudio)
t.receiver.AddBuffer(t.buffer, 0)
if err := t.buffer.Bind(webrtc.RTPParameters{Codecs: []webrtc.RTPCodecParameters{codec}}, codec.RTPCodecCapability, 64000); err != nil {
t.Close(false)
return nil, err
}
t.MediaTrackReceiver.SetupReceiver(t.receiver, 0, "")
t.receiver.StartBuffer(t.buffer, 0)
return t, nil
}
func (t *spatialPublication) ParticipantInfo() *livekit.ParticipantInfo {
return &livekit.ParticipantInfo{Sid: string(t.PublisherID()), Identity: string(t.PublisherIdentity()), Name: "Spatial audio", State: livekit.ParticipantInfo_ACTIVE, Version: 1, Tracks: []*livekit.TrackInfo{t.ToProto()}}
}
type spatialAudioRoom struct {
room *Room
engine *spatialaudio.Engine
config spatialaudio.Config
mu sync.Mutex
outputs map[livekit.ParticipantID]*spatialPublication
closed bool
}
func newSpatialAudioRoom(r *Room) (*spatialAudioRoom, error) {
c := r.roomConfig.SpatialAudio.Defaults()
if !c.Enabled || !strings.HasPrefix(string(r.Name()), c.RoomPrefix) {
return nil, nil
}
engine, err := spatialaudio.NewEngine(c)
if err != nil {
return nil, err
}
s := &spatialAudioRoom{room: r, engine: engine, config: c, outputs: make(map[livekit.ParticipantID]*spatialPublication)}
if c.DebugStats {
go func() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
select {
case <-r.closed:
return
case <-ticker.C:
r.logger.Infow("spatial audio stats", "stats", engine.String())
}
}
}()
}
return s, nil
}
func (s *spatialAudioRoom) attach(p types.LocalParticipant) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed || p.IsDisconnected() || s.room.GetParticipantByID(p.ID()) != p {
return nil
}
if !p.CanSubscribe() {
return nil
}
out := s.outputs[p.ID()]
if out == nil {
var err error
out, err = newSpatialPublication(s.room, p)
if err != nil {
return err
}
if err = s.engine.AddListener(string(p.ID()), out.Write); err != nil {
out.Close(false)
return err
}
s.outputs[p.ID()] = out
s.room.trackManager.AddTrack(out, out.PublisherIdentity(), out.PublisherID())
}
if err := p.SendParticipantUpdate([]*livekit.ParticipantInfo{out.ParticipantInfo()}); err != nil {
return err
}
p.SubscribeToTrack(out.ID(), false)
return nil
}
func (s *spatialAudioRoom) pose(p types.LocalParticipant, dp *livekit.DataPacket) bool {
u := dp.GetUser()
if u == nil || u.GetTopic() != spatialaudio.PoseTopic {
return false
}
if p != nil {
if pose, err := spatialaudio.ParsePose(u.Payload); err == nil {
s.engine.Poses.Update(string(p.ID()), pose, time.Now())
}
}
return true
}
func (s *spatialAudioRoom) scene(p types.LocalParticipant, kind livekit.DataPacket_Kind, dp *livekit.DataPacket) bool {
u := dp.GetUser()
if u == nil || u.GetTopic() != spatialaudio.SceneTopic {
return false
}
if p == nil {
return true
}
var revision uint64
var err error
grants := p.ClaimGrants()
if grants == nil || grants.Video == nil || !grants.Video.RoomAdmin {
err = fmt.Errorf("scene updates require roomAdmin permission")
} else if kind != livekit.DataPacket_RELIABLE {
err = fmt.Errorf("scene updates require reliable data")
} else if s.room.GetParticipantByID(p.ID()) != p {
err = fmt.Errorf("scene publisher has left the room")
} else {
revision, err = s.engine.ApplyScene(u.Payload)
}
ack := struct {
Revision uint64 `json:"revision"`
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
}{Revision: revision, OK: err == nil}
if err != nil {
ack.Error = err.Error()
}
payload, _ := json.Marshal(ack)
topic := spatialaudio.SceneAckTopic
data, marshalErr := proto.Marshal(&livekit.DataPacket{Kind: livekit.DataPacket_RELIABLE, Value: &livekit.DataPacket_User{User: &livekit.UserPacket{Payload: payload, Topic: &topic}}})
if marshalErr == nil {
_ = p.SendDataMessage(livekit.DataPacket_RELIABLE, data, "", 0)
}
if err == nil {
s.room.logger.Infow("spatial scene updated", "revision", revision, "publisher", p.Identity())
}
return true
}
func (s *spatialAudioRoom) published(p types.Participant, track types.MediaTrack) {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed || s.room.GetParticipantByID(p.ID()) == nil {
return
}
if track.Kind() != livekit.TrackType_AUDIO || track.Source() != livekit.TrackSource_MICROPHONE {
return
}
if track.IsEncrypted() {
s.room.logger.Warnw("spatial audio requires unencrypted application audio", nil, "track", track.ID())
return
}
observer, ok := track.(interface {
SetRTPObserver(func(webrtc.RTPCodecParameters, *buffer.ExtPacket))
})
if !ok {
return
}
input, err := s.engine.AddSource(string(p.ID()), string(track.ID()))
if err != nil {
s.room.logger.Errorw("add spatial audio input", err)
return
}
observer.SetRTPObserver(func(codec webrtc.RTPCodecParameters, packet *buffer.ExtPacket) {
if track.IsMuted() {
return
}
payload := packet.Packet.Payload
if mime.IsMimeTypeStringRED(codec.MimeType) {
var err error
payload, err = spatialaudio.PrimaryRED(payload)
if err != nil {
return
}
} else if !mime.IsMimeTypeStringOpus(codec.MimeType) {
return
}
input.Push(spatialaudio.RTPInput{Sequence: packet.Packet.SequenceNumber, Timestamp: packet.Packet.Timestamp, SSRC: packet.Packet.SSRC, Payload: payload})
})
track.AddOnClose(func(bool) { observer.SetRTPObserver(nil); s.engine.RemoveSource(string(p.ID()), string(track.ID())) })
}
func (s *spatialAudioRoom) remove(p types.LocalParticipant) {
s.mu.Lock()
defer s.mu.Unlock()
s.engine.RemoveParticipant(string(p.ID()))
if out := s.outputs[p.ID()]; out != nil {
delete(s.outputs, p.ID())
s.room.trackManager.RemoveTrack(out)
out.Close(false)
}
}
func (s *spatialAudioRoom) close() {
s.mu.Lock()
defer s.mu.Unlock()
if s.closed {
return
}
s.closed = true
s.engine.Close()
for _, out := range s.outputs {
s.room.trackManager.RemoveTrack(out)
out.Close(false)
}
clear(s.outputs)
}
func (r *Room) attachSpatial(p types.LocalParticipant) {
if r.spatial != nil {
if err := r.spatial.attach(p); err != nil {
r.logger.Errorw("attach spatial audio output", err, "participant", p.ID())
}
}
}
func spatialJoinError(err error) error { return fmt.Errorf("spatial audio room unavailable: %w", err) }