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"`
} }
+26 -24
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
@@ -2057,30 +2058,31 @@ func (p *ParticipantImpl) setupTransportManager() error {
params := TransportManagerParams{ params := TransportManagerParams{
// primary connection does not change, canSubscribe can change if permission was updated // primary connection does not change, canSubscribe can change if permission was updated
// after the participant has joined // after the participant has joined
SubscriberAsPrimary: subscriberAsPrimary, SubscriberAsPrimary: subscriberAsPrimary,
UseSinglePeerConnection: p.params.UseSinglePeerConnection, UseSinglePeerConnection: p.params.UseSinglePeerConnection,
Config: p.params.Config, Config: p.params.Config,
Twcc: p.twcc, Twcc: p.twcc,
ProtocolVersion: p.params.ProtocolVersion, ProtocolVersion: p.params.ProtocolVersion,
CongestionControlConfig: p.params.CongestionControlConfig, CongestionControlConfig: p.params.CongestionControlConfig,
EnabledPublishCodecs: p.enabledPublishCodecs, EnabledPublishCodecs: p.enabledPublishCodecs,
EnabledSubscribeCodecs: p.enabledSubscribeCodecs, EnabledSubscribeCodecs: p.enabledSubscribeCodecs,
SimTracks: p.params.SimTracks, SimTracks: p.params.SimTracks,
ClientInfo: p.params.ClientInfo, ClientInfo: p.params.ClientInfo,
Migration: p.params.Migration, Migration: p.params.Migration,
AllowTCPFallback: p.params.AllowTCPFallback, AllowTCPFallback: p.params.AllowTCPFallback,
TCPFallbackRTTThreshold: p.params.TCPFallbackRTTThreshold, TCPFallbackRTTThreshold: p.params.TCPFallbackRTTThreshold,
AllowUDPUnstableFallback: p.params.AllowUDPUnstableFallback, AllowUDPUnstableFallback: p.params.AllowUDPUnstableFallback,
TURNSEnabled: p.params.TURNSEnabled, TURNSEnabled: p.params.TURNSEnabled,
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,
Logger: p.params.Logger.WithComponent(sutils.ComponentTransport), DatachannelLossyTargetLatency: p.params.DatachannelLossyTargetLatency,
PublisherHandler: pth, Logger: p.params.Logger.WithComponent(sutils.ComponentTransport),
SubscriberHandler: sth, PublisherHandler: pth,
DataChannelStats: p.dataChannelStats, SubscriberHandler: sth,
UseOneShotSignallingMode: p.params.UseOneShotSignallingMode, DataChannelStats: p.dataChannelStats,
FireOnTrackBySdp: p.params.FireOnTrackBySdp, UseOneShotSignallingMode: p.params.UseOneShotSignallingMode,
FireOnTrackBySdp: p.params.FireOnTrackBySdp,
} }
if p.params.SyncStreams && p.params.PlayoutDelay.GetEnabled() && p.params.ClientInfo.isFirefox() { if p.params.SyncStreams && p.params.PlayoutDelay.GetEnabled() && p.params.ClientInfo.isFirefox() {
// we will disable playout delay for Firefox if the user is expecting // we will disable playout delay for Firefox if the user is expecting
+27 -25
View File
@@ -84,7 +84,8 @@ const (
shortConnectionThreshold = 90 * time.Second shortConnectionThreshold = 90 * time.Second
dataChannelBufferSize = 65535 dataChannelBufferSize = 65535
lossyDataChannelMinBufferedAmount = 8 * 1024
) )
var ( var (
@@ -282,24 +283,25 @@ type PCTransport struct {
} }
type TransportParams struct { type TransportParams struct {
Handler transport.Handler Handler transport.Handler
ProtocolVersion types.ProtocolVersion ProtocolVersion types.ProtocolVersion
Config *WebRTCConfig Config *WebRTCConfig
Twcc *lktwcc.Responder Twcc *lktwcc.Responder
DirectionConfig DirectionConfig DirectionConfig DirectionConfig
CongestionControlConfig config.CongestionControlConfig CongestionControlConfig config.CongestionControlConfig
EnabledCodecs []*livekit.Codec EnabledCodecs []*livekit.Codec
Logger logger.Logger Logger logger.Logger
Transport livekit.SignalTarget Transport livekit.SignalTarget
SimTracks map[uint32]SimulcastTrackInfo SimTracks map[uint32]SimulcastTrackInfo
ClientInfo ClientInfo ClientInfo ClientInfo
IsOfferer bool IsOfferer bool
IsSendSide bool IsSendSide bool
AllowPlayoutDelay bool AllowPlayoutDelay bool
UseOneShotSignallingMode bool UseOneShotSignallingMode bool
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()
+60 -56
View File
@@ -72,30 +72,31 @@ func (h TransportManagerTransportHandler) OnFailed(isShortLived bool, iceConnect
// ------------------------------- // -------------------------------
type TransportManagerParams struct { type TransportManagerParams struct {
SubscriberAsPrimary bool SubscriberAsPrimary bool
UseSinglePeerConnection bool UseSinglePeerConnection bool
Config *WebRTCConfig Config *WebRTCConfig
Twcc *twcc.Responder Twcc *twcc.Responder
ProtocolVersion types.ProtocolVersion ProtocolVersion types.ProtocolVersion
CongestionControlConfig config.CongestionControlConfig CongestionControlConfig config.CongestionControlConfig
EnabledSubscribeCodecs []*livekit.Codec EnabledSubscribeCodecs []*livekit.Codec
EnabledPublishCodecs []*livekit.Codec EnabledPublishCodecs []*livekit.Codec
SimTracks map[uint32]SimulcastTrackInfo SimTracks map[uint32]SimulcastTrackInfo
ClientInfo ClientInfo ClientInfo ClientInfo
Migration bool Migration bool
AllowTCPFallback bool AllowTCPFallback bool
TCPFallbackRTTThreshold int TCPFallbackRTTThreshold int
AllowUDPUnstableFallback bool AllowUDPUnstableFallback bool
TURNSEnabled bool TURNSEnabled bool
AllowPlayoutDelay bool AllowPlayoutDelay bool
DataChannelMaxBufferedAmount uint64 DataChannelMaxBufferedAmount uint64
DatachannelSlowThreshold int DatachannelSlowThreshold int
Logger logger.Logger DatachannelLossyTargetLatency time.Duration
PublisherHandler transport.Handler Logger logger.Logger
SubscriberHandler transport.Handler PublisherHandler transport.Handler
DataChannelStats *telemetry.BytesTrackStats SubscriberHandler transport.Handler
UseOneShotSignallingMode bool DataChannelStats *telemetry.BytesTrackStats
FireOnTrackBySdp bool UseOneShotSignallingMode bool
FireOnTrackBySdp bool
} }
type TransportManager struct { type TransportManager struct {
@@ -138,23 +139,24 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
lgr := LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER) lgr := LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER)
publisher, err := NewPCTransport(TransportParams{ publisher, err := NewPCTransport(TransportParams{
ProtocolVersion: params.ProtocolVersion, ProtocolVersion: params.ProtocolVersion,
Config: params.Config, Config: params.Config,
Twcc: params.Twcc, Twcc: params.Twcc,
DirectionConfig: params.Config.Publisher, DirectionConfig: params.Config.Publisher,
CongestionControlConfig: params.CongestionControlConfig, CongestionControlConfig: params.CongestionControlConfig,
EnabledCodecs: params.EnabledPublishCodecs, EnabledCodecs: params.EnabledPublishCodecs,
Logger: lgr, Logger: lgr,
SimTracks: params.SimTracks, SimTracks: params.SimTracks,
ClientInfo: params.ClientInfo, ClientInfo: params.ClientInfo,
IsSendSide: params.UseOneShotSignallingMode || params.UseSinglePeerConnection, IsSendSide: params.UseOneShotSignallingMode || params.UseSinglePeerConnection,
AllowPlayoutDelay: params.AllowPlayoutDelay, AllowPlayoutDelay: params.AllowPlayoutDelay,
Transport: livekit.SignalTarget_PUBLISHER, Transport: livekit.SignalTarget_PUBLISHER,
Handler: TransportManagerTransportHandler{params.PublisherHandler, t, lgr}, Handler: TransportManagerTransportHandler{params.PublisherHandler, t, lgr},
UseOneShotSignallingMode: params.UseOneShotSignallingMode, UseOneShotSignallingMode: params.UseOneShotSignallingMode,
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: params.DatachannelSlowThreshold, DatachannelSlowThreshold: params.DatachannelSlowThreshold,
FireOnTrackBySdp: params.FireOnTrackBySdp, DatachannelLossyTargetLatency: params.DatachannelLossyTargetLatency,
FireOnTrackBySdp: params.FireOnTrackBySdp,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
@@ -164,21 +166,22 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
if !t.params.UseOneShotSignallingMode && !t.params.UseSinglePeerConnection { if !t.params.UseOneShotSignallingMode && !t.params.UseSinglePeerConnection {
lgr := LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER) lgr := LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER)
subscriber, err := NewPCTransport(TransportParams{ subscriber, err := NewPCTransport(TransportParams{
ProtocolVersion: params.ProtocolVersion, ProtocolVersion: params.ProtocolVersion,
Config: params.Config, Config: params.Config,
DirectionConfig: params.Config.Subscriber, DirectionConfig: params.Config.Subscriber,
CongestionControlConfig: params.CongestionControlConfig, CongestionControlConfig: params.CongestionControlConfig,
EnabledCodecs: params.EnabledSubscribeCodecs, EnabledCodecs: params.EnabledSubscribeCodecs,
Logger: lgr, Logger: lgr,
ClientInfo: params.ClientInfo, ClientInfo: params.ClientInfo,
IsOfferer: true, IsOfferer: true,
IsSendSide: true, IsSendSide: true,
AllowPlayoutDelay: params.AllowPlayoutDelay, AllowPlayoutDelay: params.AllowPlayoutDelay,
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: params.DatachannelSlowThreshold, DatachannelSlowThreshold: params.DatachannelSlowThreshold,
Transport: livekit.SignalTarget_SUBSCRIBER, DatachannelLossyTargetLatency: params.DatachannelLossyTargetLatency,
Handler: TransportManagerTransportHandler{params.SubscriberHandler, t, lgr}, Transport: livekit.SignalTarget_SUBSCRIBER,
FireOnTrackBySdp: params.FireOnTrackBySdp, Handler: TransportManagerTransportHandler{params.SubscriberHandler, t, lgr},
FireOnTrackBySdp: params.FireOnTrackBySdp,
}) })
if err != nil { if err != nil {
return nil, err return nil, err
@@ -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()
+17 -16
View File
@@ -483,22 +483,23 @@ func (r *RoomManager) StartSession(
room: room, room: room,
codecRegressionThreshold: r.config.Video.CodecRegressionThreshold, codecRegressionThreshold: r.config.Video.CodecRegressionThreshold,
}, },
ReconnectOnPublicationError: reconnectOnPublicationError, ReconnectOnPublicationError: reconnectOnPublicationError,
ReconnectOnSubscriptionError: reconnectOnSubscriptionError, ReconnectOnSubscriptionError: reconnectOnSubscriptionError,
ReconnectOnDataChannelError: reconnectOnDataChannelError, ReconnectOnDataChannelError: reconnectOnDataChannelError,
VersionGenerator: r.versionGenerator, VersionGenerator: r.versionGenerator,
SubscriberAllowPause: subscriberAllowPause, SubscriberAllowPause: subscriberAllowPause,
SubscriptionLimitAudio: r.config.Limit.SubscriptionLimitAudio, SubscriptionLimitAudio: r.config.Limit.SubscriptionLimitAudio,
SubscriptionLimitVideo: r.config.Limit.SubscriptionLimitVideo, SubscriptionLimitVideo: r.config.Limit.SubscriptionLimitVideo,
PlayoutDelay: roomInternal.GetPlayoutDelay(), PlayoutDelay: roomInternal.GetPlayoutDelay(),
SyncStreams: roomInternal.GetSyncStreams(), SyncStreams: roomInternal.GetSyncStreams(),
ForwardStats: r.forwardStats, ForwardStats: r.forwardStats,
MetricConfig: r.config.Metric, MetricConfig: r.config.Metric,
UseOneShotSignallingMode: useOneShotSignallingMode, UseOneShotSignallingMode: useOneShotSignallingMode,
DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount, DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold, DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold,
FireOnTrackBySdp: true, DatachannelLossyTargetLatency: r.config.RTC.DatachannelLossyTargetLatency,
UseSinglePeerConnection: pi.UseSinglePeerConnection, FireOnTrackBySdp: true,
UseSinglePeerConnection: pi.UseSinglePeerConnection,
}) })
if err != nil { if err != nil {
return err return err
+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
} }
+72 -10
View File
@@ -15,24 +15,30 @@ 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
} }
type DataChannelWriter[T BufferedAmountGetter] struct { type DataChannelWriter[T BufferedAmountGetter] struct {
bufferGetter T bufferGetter T
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
}