Control latency of lossy data channel (#4088)

* Control latency of lossy data channel

* remove log

* test
This commit is contained in:
cnderrauber
2025-11-18 16:30:16 +08:00
committed by GitHub
parent 5175c1afa1
commit 54cf7d46c8
8 changed files with 274 additions and 140 deletions
+3
View File
@@ -124,6 +124,9 @@ type RTCConfig struct {
// be dropped for a slow data channel to avoid blocking the room. // be dropped for a slow data channel to avoid blocking the room.
DatachannelSlowThreshold int `yaml:"datachannel_slow_threshold,omitempty"` DatachannelSlowThreshold int `yaml:"datachannel_slow_threshold,omitempty"`
// Target latency for lossy data channels, used to drop packets to reduce latency.
DatachannelLossyTargetLatency time.Duration `yaml:"datachannel_lossy_target_latency,omitempty"`
ForwardStats ForwardStatsConfig `yaml:"forward_stats,omitempty"` ForwardStats ForwardStatsConfig `yaml:"forward_stats,omitempty"`
} }
+2
View File
@@ -210,6 +210,7 @@ type ParticipantParams struct {
EnableMetrics bool EnableMetrics bool
DataChannelMaxBufferedAmount uint64 DataChannelMaxBufferedAmount uint64
DatachannelSlowThreshold int DatachannelSlowThreshold int
DatachannelLossyTargetLatency time.Duration
FireOnTrackBySdp bool FireOnTrackBySdp bool
DisableCodecRegression bool DisableCodecRegression bool
LastPubReliableSeq uint32 LastPubReliableSeq uint32
@@ -2075,6 +2076,7 @@ func (p *ParticipantImpl) setupTransportManager() error {
AllowPlayoutDelay: p.params.PlayoutDelay.GetEnabled(), AllowPlayoutDelay: p.params.PlayoutDelay.GetEnabled(),
DataChannelMaxBufferedAmount: p.params.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: p.params.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: p.params.DatachannelSlowThreshold, DatachannelSlowThreshold: p.params.DatachannelSlowThreshold,
DatachannelLossyTargetLatency: p.params.DatachannelLossyTargetLatency,
Logger: p.params.Logger.WithComponent(sutils.ComponentTransport), Logger: p.params.Logger.WithComponent(sutils.ComponentTransport),
PublisherHandler: pth, PublisherHandler: pth,
SubscriberHandler: sth, SubscriberHandler: sth,
+8 -6
View File
@@ -85,6 +85,7 @@ const (
shortConnectionThreshold = 90 * time.Second shortConnectionThreshold = 90 * time.Second
dataChannelBufferSize = 65535 dataChannelBufferSize = 65535
lossyDataChannelMinBufferedAmount = 8 * 1024
) )
var ( var (
@@ -300,6 +301,7 @@ type TransportParams struct {
FireOnTrackBySdp bool FireOnTrackBySdp bool
DataChannelMaxBufferedAmount uint64 DataChannelMaxBufferedAmount uint64
DatachannelSlowThreshold int DatachannelSlowThreshold int
DatachannelLossyTargetLatency time.Duration
// for development test // for development test
DatachannelMaxReceiverBufferSize int DatachannelMaxReceiverBufferSize int
@@ -852,7 +854,7 @@ func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) {
t.lock.Lock() t.lock.Lock()
t.unlabeledDataChannels = append( t.unlabeledDataChannels = append(
t.unlabeledDataChannels, t.unlabeledDataChannels,
datachannel.NewDataChannelWriter(dc, rawDC, t.params.DatachannelSlowThreshold), datachannel.NewDataChannelWriterReliable(dc, rawDC, t.params.DatachannelSlowThreshold),
) )
t.lock.Unlock() t.lock.Unlock()
@@ -861,7 +863,7 @@ func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) {
if t.reliableDC != nil { if t.reliableDC != nil {
t.reliableDC.Close() t.reliableDC.Close()
} }
t.reliableDC = datachannel.NewDataChannelWriter(dc, rawDC, t.params.DatachannelSlowThreshold) t.reliableDC = datachannel.NewDataChannelWriterReliable(dc, rawDC, t.params.DatachannelSlowThreshold)
t.reliableDCOpened = true t.reliableDCOpened = true
t.lock.Unlock() t.lock.Unlock()
@@ -870,7 +872,7 @@ func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) {
if t.lossyDC != nil { if t.lossyDC != nil {
t.lossyDC.Close() t.lossyDC.Close()
} }
t.lossyDC = datachannel.NewDataChannelWriter(dc, rawDC, 0) t.lossyDC = datachannel.NewDataChannelWriterUnreliable(dc, rawDC, t.params.DatachannelLossyTargetLatency, uint64(lossyDataChannelMinBufferedAmount))
t.lossyDCOpened = true t.lossyDCOpened = true
t.lock.Unlock() t.lock.Unlock()
} }
@@ -1197,13 +1199,13 @@ func (t *PCTransport) CreateDataChannel(label string, dci *webrtc.DataChannelIni
if isUnlabeled { if isUnlabeled {
t.unlabeledDataChannels = append( t.unlabeledDataChannels = append(
t.unlabeledDataChannels, t.unlabeledDataChannels,
datachannel.NewDataChannelWriter(dc, rawDC, slowThreshold), datachannel.NewDataChannelWriterReliable(dc, rawDC, slowThreshold),
) )
} else { } else {
if *dcPtr != nil { if *dcPtr != nil {
(*dcPtr).Close() (*dcPtr).Close()
} }
*dcPtr = datachannel.NewDataChannelWriter(dc, rawDC, slowThreshold) *dcPtr = datachannel.NewDataChannelWriterReliable(dc, rawDC, slowThreshold)
*dcReady = true *dcReady = true
} }
t.lock.Unlock() t.lock.Unlock()
@@ -1255,7 +1257,7 @@ func (t *PCTransport) CreateReadableDataChannel(label string, dci *webrtc.DataCh
t.lock.Lock() t.lock.Lock()
t.unlabeledDataChannels = append( t.unlabeledDataChannels = append(
t.unlabeledDataChannels, t.unlabeledDataChannels,
datachannel.NewDataChannelWriter(dc, rawDC, t.params.DatachannelSlowThreshold), datachannel.NewDataChannelWriterReliable(dc, rawDC, t.params.DatachannelSlowThreshold),
) )
t.lock.Unlock() t.lock.Unlock()
+4
View File
@@ -90,6 +90,7 @@ type TransportManagerParams struct {
AllowPlayoutDelay bool AllowPlayoutDelay bool
DataChannelMaxBufferedAmount uint64 DataChannelMaxBufferedAmount uint64
DatachannelSlowThreshold int DatachannelSlowThreshold int
DatachannelLossyTargetLatency time.Duration
Logger logger.Logger Logger logger.Logger
PublisherHandler transport.Handler PublisherHandler transport.Handler
SubscriberHandler transport.Handler SubscriberHandler transport.Handler
@@ -154,6 +155,7 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
UseOneShotSignallingMode: params.UseOneShotSignallingMode, UseOneShotSignallingMode: params.UseOneShotSignallingMode,
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: params.DatachannelSlowThreshold, DatachannelSlowThreshold: params.DatachannelSlowThreshold,
DatachannelLossyTargetLatency: params.DatachannelLossyTargetLatency,
FireOnTrackBySdp: params.FireOnTrackBySdp, FireOnTrackBySdp: params.FireOnTrackBySdp,
}) })
if err != nil { if err != nil {
@@ -176,6 +178,7 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
AllowPlayoutDelay: params.AllowPlayoutDelay, AllowPlayoutDelay: params.AllowPlayoutDelay,
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: params.DatachannelSlowThreshold, DatachannelSlowThreshold: params.DatachannelSlowThreshold,
DatachannelLossyTargetLatency: params.DatachannelLossyTargetLatency,
Transport: livekit.SignalTarget_SUBSCRIBER, Transport: livekit.SignalTarget_SUBSCRIBER,
Handler: TransportManagerTransportHandler{params.SubscriberHandler, t, lgr}, Handler: TransportManagerTransportHandler{params.SubscriberHandler, t, lgr},
FireOnTrackBySdp: params.FireOnTrackBySdp, FireOnTrackBySdp: params.FireOnTrackBySdp,
@@ -341,6 +344,7 @@ func (t *TransportManager) handleSendDataResult(err error, kind string, size int
ErrTransportFailure, ErrTransportFailure,
ErrDataChannelBufferFull, ErrDataChannelBufferFull,
context.DeadlineExceeded, context.DeadlineExceeded,
datachannel.ErrDataDroppedByHighBufferedAmount,
) { ) {
if errors.Is(err, datachannel.ErrDataDroppedBySlowReader) { if errors.Is(err, datachannel.ErrDataDroppedBySlowReader) {
droppedBySlowReaderCount := t.droppedBySlowReaderCount.Inc() droppedBySlowReaderCount := t.droppedBySlowReaderCount.Inc()
+1
View File
@@ -497,6 +497,7 @@ func (r *RoomManager) StartSession(
UseOneShotSignallingMode: useOneShotSignallingMode, UseOneShotSignallingMode: useOneShotSignallingMode,
DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold, DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold,
DatachannelLossyTargetLatency: r.config.RTC.DatachannelLossyTargetLatency,
FireOnTrackBySdp: true, FireOnTrackBySdp: true,
UseSinglePeerConnection: pi.UseSinglePeerConnection, UseSinglePeerConnection: pi.UseSinglePeerConnection,
}) })
+7 -7
View File
@@ -89,23 +89,23 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
} }
rtcEgressLauncher := NewEgressLauncher(egressClient, ioInfoService, objectStore) rtcEgressLauncher := NewEgressLauncher(egressClient, ioInfoService, objectStore)
topicFormatter := rpc.NewTopicFormatter() topicFormatter := rpc.NewTopicFormatter()
v, err := rpc.NewTypedRoomClient(clientParams) roomClient, err := rpc.NewTypedRoomClient(clientParams)
if err != nil { if err != nil {
return nil, err return nil, err
} }
v2, err := rpc.NewTypedParticipantClient(clientParams) participantClient, err := rpc.NewTypedParticipantClient(clientParams)
if err != nil { if err != nil {
return nil, err return nil, err
} }
roomService, err := NewRoomService(limitConfig, apiConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, v, v2) roomService, err := NewRoomService(limitConfig, apiConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
if err != nil { if err != nil {
return nil, err return nil, err
} }
v3, err := rpc.NewTypedAgentDispatchInternalClient(clientParams) agentDispatchInternalClient, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
if err != nil { if err != nil {
return nil, err return nil, err
} }
agentDispatchService := NewAgentDispatchService(v3, topicFormatter, roomAllocator, router) agentDispatchService := NewAgentDispatchService(agentDispatchInternalClient, topicFormatter, roomAllocator, router)
egressService := NewEgressService(egressClient, rtcEgressLauncher, ioInfoService, roomService) egressService := NewEgressService(egressClient, rtcEgressLauncher, ioInfoService, roomService)
ingressConfig := getIngressConfig(conf) ingressConfig := getIngressConfig(conf)
ingressClient, err := rpc.NewIngressClient(clientParams) ingressClient, err := rpc.NewIngressClient(clientParams)
@@ -120,11 +120,11 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
} }
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService) sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
rtcService := NewRTCService(conf, roomAllocator, router, telemetryService) rtcService := NewRTCService(conf, roomAllocator, router, telemetryService)
v4, err := rpc.NewTypedWHIPParticipantClient(clientParams) whipParticipantClient, err := rpc.NewTypedWHIPParticipantClient(clientParams)
if err != nil { if err != nil {
return nil, err return nil, err
} }
serviceWHIPService, err := NewWHIPService(conf, router, roomAllocator, clientParams, topicFormatter, v4) serviceWHIPService, err := NewWHIPService(conf, router, roomAllocator, clientParams, topicFormatter, whipParticipantClient)
if err != nil { if err != nil {
return nil, err return nil, err
} }
+68 -6
View File
@@ -15,7 +15,10 @@ const (
singleWriteTimeout = 50 * time.Millisecond singleWriteTimeout = 50 * time.Millisecond
) )
var ErrDataDroppedBySlowReader = errors.New("data dropped by slow reader") var (
ErrDataDroppedBySlowReader = errors.New("data dropped by slow reader")
ErrDataDroppedByHighBufferedAmount = errors.New("data dropped due to high buffered amount")
)
type BufferedAmountGetter interface { type BufferedAmountGetter interface {
BufferedAmount() uint64 BufferedAmount() uint64
@@ -26,13 +29,16 @@ type DataChannelWriter[T BufferedAmountGetter] struct {
rawDC datachannel.ReadWriteCloserDeadliner rawDC datachannel.ReadWriteCloserDeadliner
slowThreshold int slowThreshold int
rate *BitrateCalculator rate *BitrateCalculator
reliable bool
targetLatency time.Duration
minBufferedAmount uint64
} }
// NewDataChannelWriter creates a new DataChannelWriter by detaching the data channel, when // NewDataChannelWriterReliable creates a new DataChannelWriter for reliable data channel by
// writing to the datachanel times out, it will block and retry if the receiver's bitrate is // detaching it, when writing to the datachanel times out, it will block and retry if the
// above the slowThreshold or drop the data if it's below the threshold. If the slowThreshold // receiver's bitrate is above the slowThreshold or drop the data if it's below the threshold.
// is 0, it will never retry on write timeout. // If the slowThreshold is 0, it will never retry on write timeout.
func NewDataChannelWriter[T BufferedAmountGetter](bufferGetter T, rawDC datachannel.ReadWriteCloserDeadliner, slowThreshold int) *DataChannelWriter[T] { func NewDataChannelWriterReliable[T BufferedAmountGetter](bufferGetter T, rawDC datachannel.ReadWriteCloserDeadliner, slowThreshold int) *DataChannelWriter[T] {
var rate *BitrateCalculator var rate *BitrateCalculator
if slowThreshold > 0 { if slowThreshold > 0 {
rate = NewBitrateCalculator(BitrateDuration, BitrateWindow) rate = NewBitrateCalculator(BitrateDuration, BitrateWindow)
@@ -42,6 +48,26 @@ func NewDataChannelWriter[T BufferedAmountGetter](bufferGetter T, rawDC datachan
rawDC: rawDC, rawDC: rawDC,
slowThreshold: slowThreshold, slowThreshold: slowThreshold,
rate: rate, rate: rate,
reliable: true,
}
}
// NewDataChannelWriterUnreliable creates a new DataChannelWriter for unreliable data channel.
// It will drop data when the buffered amount is too high to maintain the target latency.
// The latency is estimated based on the bitrate in past 1 second. If targetLatency is 0, no
// buffering control is applied.
func NewDataChannelWriterUnreliable[T BufferedAmountGetter](bufferGetter T, rawDC datachannel.ReadWriteCloserDeadliner, targetLatency time.Duration, minBufferedAmount uint64) *DataChannelWriter[T] {
var rate *BitrateCalculator
if targetLatency > 0 {
rate = NewBitrateCalculator(BitrateDuration, BitrateWindow)
}
return &DataChannelWriter[T]{
bufferGetter: bufferGetter,
rawDC: rawDC,
rate: rate,
targetLatency: targetLatency,
minBufferedAmount: minBufferedAmount,
reliable: false,
} }
} }
@@ -50,6 +76,14 @@ func (w *DataChannelWriter[T]) BufferedAmountGetter() T {
} }
func (w *DataChannelWriter[T]) Write(p []byte) (n int, err error) { func (w *DataChannelWriter[T]) Write(p []byte) (n int, err error) {
if w.reliable {
return w.writeReliable(p)
} else {
return w.writeUnreliable(p)
}
}
func (w *DataChannelWriter[T]) writeReliable(p []byte) (n int, err error) {
for { for {
err = w.rawDC.SetWriteDeadline(time.Now().Add(singleWriteTimeout)) err = w.rawDC.SetWriteDeadline(time.Now().Add(singleWriteTimeout))
if err != nil { if err != nil {
@@ -75,6 +109,34 @@ func (w *DataChannelWriter[T]) Write(p []byte) (n int, err error) {
} }
} }
func (w *DataChannelWriter[T]) writeUnreliable(p []byte) (n int, err error) {
if w.targetLatency == 0 {
err = w.rawDC.SetWriteDeadline(time.Now().Add(singleWriteTimeout))
if err != nil {
return 0, err
}
return w.rawDC.Write(p)
}
if bitrate, ok := w.rate.Bitrate(time.Now()); ok {
// control buffer latency to ~100ms
if w.bufferGetter.BufferedAmount() > uint64(time.Duration(bitrate)*w.targetLatency/8/time.Second) && w.bufferGetter.BufferedAmount() > w.minBufferedAmount {
return 0, ErrDataDroppedByHighBufferedAmount
}
}
err = w.rawDC.SetWriteDeadline(time.Now().Add(singleWriteTimeout))
if err != nil {
return 0, err
}
n, err = w.rawDC.Write(p)
if err != nil {
w.rate.AddBytes(n, int(w.bufferGetter.BufferedAmount()), mono.Now())
}
return
}
func (w *DataChannelWriter[T]) Close() error { func (w *DataChannelWriter[T]) Close() error {
return w.rawDC.Close() return w.rawDC.Close()
} }
+62 -2
View File
@@ -2,6 +2,7 @@ package datachannel
import ( import (
"context" "context"
"sync/atomic"
"testing" "testing"
"time" "time"
@@ -13,7 +14,7 @@ import (
func TestDataChannelWriter(t *testing.T) { func TestDataChannelWriter(t *testing.T) {
mockDC := newMockDataChannelWriter() mockDC := newMockDataChannelWriter()
// slow threshold is 1000B/s // slow threshold is 1000B/s
w := NewDataChannelWriter(mockDC, mockDC, 8000) w := NewDataChannelWriterReliable(mockDC, mockDC, 8000)
require.Equal(t, mockDC, w.BufferedAmountGetter()) require.Equal(t, mockDC, w.BufferedAmountGetter())
buf := make([]byte, 2000) buf := make([]byte, 2000)
// write 2000 bytes so it should not drop in 2 seconds // write 2000 bytes so it should not drop in 2 seconds
@@ -38,7 +39,7 @@ func TestDataChannelWriter(t *testing.T) {
func TestDataChannelWriter_NoSlowThreshold(t *testing.T) { func TestDataChannelWriter_NoSlowThreshold(t *testing.T) {
mockDC := newMockDataChannelWriter() mockDC := newMockDataChannelWriter()
w := NewDataChannelWriter(mockDC, mockDC, 0) w := NewDataChannelWriterReliable(mockDC, mockDC, 0)
buf := make([]byte, 2000) buf := make([]byte, 2000)
n, err := w.Write(buf) n, err := w.Write(buf)
require.NoError(t, err) require.NoError(t, err)
@@ -55,6 +56,24 @@ func TestDataChannelWriter_NoSlowThreshold(t *testing.T) {
require.Equal(t, 0, n) require.Equal(t, 0, n)
} }
func TestDataChannelWriter_Unreliable(t *testing.T) {
mockDC := newMockLossyDataChannelWriter(8192)
w := NewDataChannelWriterUnreliable(mockDC, mockDC, 100*time.Millisecond, 2000)
for i := 0; i < 10; i++ {
buf := make([]byte, 128)
_, err := w.Write(buf)
require.NoError(t, err)
time.Sleep(100 * time.Millisecond)
}
buf := make([]byte, 4096)
_, err := w.Write(buf)
require.NoError(t, err)
// should drop due to high buffered amount
_, err = w.Write(buf)
require.ErrorIs(t, err, ErrDataDroppedByHighBufferedAmount)
}
// mockDataChannelWriter
type mockDataChannelWriter struct { type mockDataChannelWriter struct {
datachannel.ReadWriteCloserDeadliner datachannel.ReadWriteCloserDeadliner
nextWriteCompleteAt time.Time nextWriteCompleteAt time.Time
@@ -92,3 +111,44 @@ func (m *mockDataChannelWriter) SetWriteDeadline(t time.Time) error {
func (m *mockDataChannelWriter) SetNextWriteCompleteAt(t time.Time) { func (m *mockDataChannelWriter) SetNextWriteCompleteAt(t time.Time) {
m.nextWriteCompleteAt = t m.nextWriteCompleteAt = t
} }
// mockLossyDataChannelWriter
type mockLossyDataChannelWriter struct {
datachannel.ReadWriteCloserDeadliner
bufferedAmount atomic.Int64
targetBitrate int
lastWriteAt time.Time
}
func newMockLossyDataChannelWriter(targetBitrate int) *mockLossyDataChannelWriter {
return &mockLossyDataChannelWriter{
targetBitrate: targetBitrate,
lastWriteAt: time.Now(),
}
}
func (m *mockLossyDataChannelWriter) BufferedAmount() uint64 {
return uint64(m.bufferedAmount.Load())
}
func (m *mockLossyDataChannelWriter) Write(b []byte) (int, error) {
m.bufferedAmount.Add(int64(len(b)))
if time.Now().Before(m.lastWriteAt) {
return len(b), nil
}
// drain buffer based on target bitrate
canWriteBytes := time.Since(m.lastWriteAt) * time.Duration(m.targetBitrate) / time.Second / 8
if m.bufferedAmount.Load() <= int64(canWriteBytes) {
m.lastWriteAt = m.lastWriteAt.Add(time.Duration(int64(time.Second) * int64(m.BufferedAmount()) / (int64(m.targetBitrate) / 8)))
m.bufferedAmount.Store(0)
} else {
m.lastWriteAt = time.Now()
m.bufferedAmount.Add(-int64(canWriteBytes))
}
return len(b), nil
}
func (m *mockLossyDataChannelWriter) SetWriteDeadline(t time.Time) error {
return nil
}