302 lines
11 KiB
Go
302 lines
11 KiB
Go
// 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) }
|