Control latency of lossy data channel (#4088)
* Control latency of lossy data channel * remove log * test
This commit is contained in:
@@ -124,6 +124,9 @@ type RTCConfig struct {
|
||||
// be dropped for a slow data channel to avoid blocking the room.
|
||||
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"`
|
||||
}
|
||||
|
||||
|
||||
+26
-24
@@ -210,6 +210,7 @@ type ParticipantParams struct {
|
||||
EnableMetrics bool
|
||||
DataChannelMaxBufferedAmount uint64
|
||||
DatachannelSlowThreshold int
|
||||
DatachannelLossyTargetLatency time.Duration
|
||||
FireOnTrackBySdp bool
|
||||
DisableCodecRegression bool
|
||||
LastPubReliableSeq uint32
|
||||
@@ -2057,30 +2058,31 @@ func (p *ParticipantImpl) setupTransportManager() error {
|
||||
params := TransportManagerParams{
|
||||
// primary connection does not change, canSubscribe can change if permission was updated
|
||||
// after the participant has joined
|
||||
SubscriberAsPrimary: subscriberAsPrimary,
|
||||
UseSinglePeerConnection: p.params.UseSinglePeerConnection,
|
||||
Config: p.params.Config,
|
||||
Twcc: p.twcc,
|
||||
ProtocolVersion: p.params.ProtocolVersion,
|
||||
CongestionControlConfig: p.params.CongestionControlConfig,
|
||||
EnabledPublishCodecs: p.enabledPublishCodecs,
|
||||
EnabledSubscribeCodecs: p.enabledSubscribeCodecs,
|
||||
SimTracks: p.params.SimTracks,
|
||||
ClientInfo: p.params.ClientInfo,
|
||||
Migration: p.params.Migration,
|
||||
AllowTCPFallback: p.params.AllowTCPFallback,
|
||||
TCPFallbackRTTThreshold: p.params.TCPFallbackRTTThreshold,
|
||||
AllowUDPUnstableFallback: p.params.AllowUDPUnstableFallback,
|
||||
TURNSEnabled: p.params.TURNSEnabled,
|
||||
AllowPlayoutDelay: p.params.PlayoutDelay.GetEnabled(),
|
||||
DataChannelMaxBufferedAmount: p.params.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: p.params.DatachannelSlowThreshold,
|
||||
Logger: p.params.Logger.WithComponent(sutils.ComponentTransport),
|
||||
PublisherHandler: pth,
|
||||
SubscriberHandler: sth,
|
||||
DataChannelStats: p.dataChannelStats,
|
||||
UseOneShotSignallingMode: p.params.UseOneShotSignallingMode,
|
||||
FireOnTrackBySdp: p.params.FireOnTrackBySdp,
|
||||
SubscriberAsPrimary: subscriberAsPrimary,
|
||||
UseSinglePeerConnection: p.params.UseSinglePeerConnection,
|
||||
Config: p.params.Config,
|
||||
Twcc: p.twcc,
|
||||
ProtocolVersion: p.params.ProtocolVersion,
|
||||
CongestionControlConfig: p.params.CongestionControlConfig,
|
||||
EnabledPublishCodecs: p.enabledPublishCodecs,
|
||||
EnabledSubscribeCodecs: p.enabledSubscribeCodecs,
|
||||
SimTracks: p.params.SimTracks,
|
||||
ClientInfo: p.params.ClientInfo,
|
||||
Migration: p.params.Migration,
|
||||
AllowTCPFallback: p.params.AllowTCPFallback,
|
||||
TCPFallbackRTTThreshold: p.params.TCPFallbackRTTThreshold,
|
||||
AllowUDPUnstableFallback: p.params.AllowUDPUnstableFallback,
|
||||
TURNSEnabled: p.params.TURNSEnabled,
|
||||
AllowPlayoutDelay: p.params.PlayoutDelay.GetEnabled(),
|
||||
DataChannelMaxBufferedAmount: p.params.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: p.params.DatachannelSlowThreshold,
|
||||
DatachannelLossyTargetLatency: p.params.DatachannelLossyTargetLatency,
|
||||
Logger: p.params.Logger.WithComponent(sutils.ComponentTransport),
|
||||
PublisherHandler: pth,
|
||||
SubscriberHandler: sth,
|
||||
DataChannelStats: p.dataChannelStats,
|
||||
UseOneShotSignallingMode: p.params.UseOneShotSignallingMode,
|
||||
FireOnTrackBySdp: p.params.FireOnTrackBySdp,
|
||||
}
|
||||
if p.params.SyncStreams && p.params.PlayoutDelay.GetEnabled() && p.params.ClientInfo.isFirefox() {
|
||||
// we will disable playout delay for Firefox if the user is expecting
|
||||
|
||||
+27
-25
@@ -84,7 +84,8 @@ const (
|
||||
|
||||
shortConnectionThreshold = 90 * time.Second
|
||||
|
||||
dataChannelBufferSize = 65535
|
||||
dataChannelBufferSize = 65535
|
||||
lossyDataChannelMinBufferedAmount = 8 * 1024
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -282,24 +283,25 @@ type PCTransport struct {
|
||||
}
|
||||
|
||||
type TransportParams struct {
|
||||
Handler transport.Handler
|
||||
ProtocolVersion types.ProtocolVersion
|
||||
Config *WebRTCConfig
|
||||
Twcc *lktwcc.Responder
|
||||
DirectionConfig DirectionConfig
|
||||
CongestionControlConfig config.CongestionControlConfig
|
||||
EnabledCodecs []*livekit.Codec
|
||||
Logger logger.Logger
|
||||
Transport livekit.SignalTarget
|
||||
SimTracks map[uint32]SimulcastTrackInfo
|
||||
ClientInfo ClientInfo
|
||||
IsOfferer bool
|
||||
IsSendSide bool
|
||||
AllowPlayoutDelay bool
|
||||
UseOneShotSignallingMode bool
|
||||
FireOnTrackBySdp bool
|
||||
DataChannelMaxBufferedAmount uint64
|
||||
DatachannelSlowThreshold int
|
||||
Handler transport.Handler
|
||||
ProtocolVersion types.ProtocolVersion
|
||||
Config *WebRTCConfig
|
||||
Twcc *lktwcc.Responder
|
||||
DirectionConfig DirectionConfig
|
||||
CongestionControlConfig config.CongestionControlConfig
|
||||
EnabledCodecs []*livekit.Codec
|
||||
Logger logger.Logger
|
||||
Transport livekit.SignalTarget
|
||||
SimTracks map[uint32]SimulcastTrackInfo
|
||||
ClientInfo ClientInfo
|
||||
IsOfferer bool
|
||||
IsSendSide bool
|
||||
AllowPlayoutDelay bool
|
||||
UseOneShotSignallingMode bool
|
||||
FireOnTrackBySdp bool
|
||||
DataChannelMaxBufferedAmount uint64
|
||||
DatachannelSlowThreshold int
|
||||
DatachannelLossyTargetLatency time.Duration
|
||||
|
||||
// for development test
|
||||
DatachannelMaxReceiverBufferSize int
|
||||
@@ -852,7 +854,7 @@ func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) {
|
||||
t.lock.Lock()
|
||||
t.unlabeledDataChannels = append(
|
||||
t.unlabeledDataChannels,
|
||||
datachannel.NewDataChannelWriter(dc, rawDC, t.params.DatachannelSlowThreshold),
|
||||
datachannel.NewDataChannelWriterReliable(dc, rawDC, t.params.DatachannelSlowThreshold),
|
||||
)
|
||||
t.lock.Unlock()
|
||||
|
||||
@@ -861,7 +863,7 @@ func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) {
|
||||
if t.reliableDC != nil {
|
||||
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.lock.Unlock()
|
||||
|
||||
@@ -870,7 +872,7 @@ func (t *PCTransport) onDataChannel(dc *webrtc.DataChannel) {
|
||||
if t.lossyDC != nil {
|
||||
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.lock.Unlock()
|
||||
}
|
||||
@@ -1197,13 +1199,13 @@ func (t *PCTransport) CreateDataChannel(label string, dci *webrtc.DataChannelIni
|
||||
if isUnlabeled {
|
||||
t.unlabeledDataChannels = append(
|
||||
t.unlabeledDataChannels,
|
||||
datachannel.NewDataChannelWriter(dc, rawDC, slowThreshold),
|
||||
datachannel.NewDataChannelWriterReliable(dc, rawDC, slowThreshold),
|
||||
)
|
||||
} else {
|
||||
if *dcPtr != nil {
|
||||
(*dcPtr).Close()
|
||||
}
|
||||
*dcPtr = datachannel.NewDataChannelWriter(dc, rawDC, slowThreshold)
|
||||
*dcPtr = datachannel.NewDataChannelWriterReliable(dc, rawDC, slowThreshold)
|
||||
*dcReady = true
|
||||
}
|
||||
t.lock.Unlock()
|
||||
@@ -1255,7 +1257,7 @@ func (t *PCTransport) CreateReadableDataChannel(label string, dci *webrtc.DataCh
|
||||
t.lock.Lock()
|
||||
t.unlabeledDataChannels = append(
|
||||
t.unlabeledDataChannels,
|
||||
datachannel.NewDataChannelWriter(dc, rawDC, t.params.DatachannelSlowThreshold),
|
||||
datachannel.NewDataChannelWriterReliable(dc, rawDC, t.params.DatachannelSlowThreshold),
|
||||
)
|
||||
t.lock.Unlock()
|
||||
|
||||
|
||||
+60
-56
@@ -72,30 +72,31 @@ func (h TransportManagerTransportHandler) OnFailed(isShortLived bool, iceConnect
|
||||
// -------------------------------
|
||||
|
||||
type TransportManagerParams struct {
|
||||
SubscriberAsPrimary bool
|
||||
UseSinglePeerConnection bool
|
||||
Config *WebRTCConfig
|
||||
Twcc *twcc.Responder
|
||||
ProtocolVersion types.ProtocolVersion
|
||||
CongestionControlConfig config.CongestionControlConfig
|
||||
EnabledSubscribeCodecs []*livekit.Codec
|
||||
EnabledPublishCodecs []*livekit.Codec
|
||||
SimTracks map[uint32]SimulcastTrackInfo
|
||||
ClientInfo ClientInfo
|
||||
Migration bool
|
||||
AllowTCPFallback bool
|
||||
TCPFallbackRTTThreshold int
|
||||
AllowUDPUnstableFallback bool
|
||||
TURNSEnabled bool
|
||||
AllowPlayoutDelay bool
|
||||
DataChannelMaxBufferedAmount uint64
|
||||
DatachannelSlowThreshold int
|
||||
Logger logger.Logger
|
||||
PublisherHandler transport.Handler
|
||||
SubscriberHandler transport.Handler
|
||||
DataChannelStats *telemetry.BytesTrackStats
|
||||
UseOneShotSignallingMode bool
|
||||
FireOnTrackBySdp bool
|
||||
SubscriberAsPrimary bool
|
||||
UseSinglePeerConnection bool
|
||||
Config *WebRTCConfig
|
||||
Twcc *twcc.Responder
|
||||
ProtocolVersion types.ProtocolVersion
|
||||
CongestionControlConfig config.CongestionControlConfig
|
||||
EnabledSubscribeCodecs []*livekit.Codec
|
||||
EnabledPublishCodecs []*livekit.Codec
|
||||
SimTracks map[uint32]SimulcastTrackInfo
|
||||
ClientInfo ClientInfo
|
||||
Migration bool
|
||||
AllowTCPFallback bool
|
||||
TCPFallbackRTTThreshold int
|
||||
AllowUDPUnstableFallback bool
|
||||
TURNSEnabled bool
|
||||
AllowPlayoutDelay bool
|
||||
DataChannelMaxBufferedAmount uint64
|
||||
DatachannelSlowThreshold int
|
||||
DatachannelLossyTargetLatency time.Duration
|
||||
Logger logger.Logger
|
||||
PublisherHandler transport.Handler
|
||||
SubscriberHandler transport.Handler
|
||||
DataChannelStats *telemetry.BytesTrackStats
|
||||
UseOneShotSignallingMode bool
|
||||
FireOnTrackBySdp bool
|
||||
}
|
||||
|
||||
type TransportManager struct {
|
||||
@@ -138,23 +139,24 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
|
||||
|
||||
lgr := LoggerWithPCTarget(params.Logger, livekit.SignalTarget_PUBLISHER)
|
||||
publisher, err := NewPCTransport(TransportParams{
|
||||
ProtocolVersion: params.ProtocolVersion,
|
||||
Config: params.Config,
|
||||
Twcc: params.Twcc,
|
||||
DirectionConfig: params.Config.Publisher,
|
||||
CongestionControlConfig: params.CongestionControlConfig,
|
||||
EnabledCodecs: params.EnabledPublishCodecs,
|
||||
Logger: lgr,
|
||||
SimTracks: params.SimTracks,
|
||||
ClientInfo: params.ClientInfo,
|
||||
IsSendSide: params.UseOneShotSignallingMode || params.UseSinglePeerConnection,
|
||||
AllowPlayoutDelay: params.AllowPlayoutDelay,
|
||||
Transport: livekit.SignalTarget_PUBLISHER,
|
||||
Handler: TransportManagerTransportHandler{params.PublisherHandler, t, lgr},
|
||||
UseOneShotSignallingMode: params.UseOneShotSignallingMode,
|
||||
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: params.DatachannelSlowThreshold,
|
||||
FireOnTrackBySdp: params.FireOnTrackBySdp,
|
||||
ProtocolVersion: params.ProtocolVersion,
|
||||
Config: params.Config,
|
||||
Twcc: params.Twcc,
|
||||
DirectionConfig: params.Config.Publisher,
|
||||
CongestionControlConfig: params.CongestionControlConfig,
|
||||
EnabledCodecs: params.EnabledPublishCodecs,
|
||||
Logger: lgr,
|
||||
SimTracks: params.SimTracks,
|
||||
ClientInfo: params.ClientInfo,
|
||||
IsSendSide: params.UseOneShotSignallingMode || params.UseSinglePeerConnection,
|
||||
AllowPlayoutDelay: params.AllowPlayoutDelay,
|
||||
Transport: livekit.SignalTarget_PUBLISHER,
|
||||
Handler: TransportManagerTransportHandler{params.PublisherHandler, t, lgr},
|
||||
UseOneShotSignallingMode: params.UseOneShotSignallingMode,
|
||||
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: params.DatachannelSlowThreshold,
|
||||
DatachannelLossyTargetLatency: params.DatachannelLossyTargetLatency,
|
||||
FireOnTrackBySdp: params.FireOnTrackBySdp,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -164,21 +166,22 @@ func NewTransportManager(params TransportManagerParams) (*TransportManager, erro
|
||||
if !t.params.UseOneShotSignallingMode && !t.params.UseSinglePeerConnection {
|
||||
lgr := LoggerWithPCTarget(params.Logger, livekit.SignalTarget_SUBSCRIBER)
|
||||
subscriber, err := NewPCTransport(TransportParams{
|
||||
ProtocolVersion: params.ProtocolVersion,
|
||||
Config: params.Config,
|
||||
DirectionConfig: params.Config.Subscriber,
|
||||
CongestionControlConfig: params.CongestionControlConfig,
|
||||
EnabledCodecs: params.EnabledSubscribeCodecs,
|
||||
Logger: lgr,
|
||||
ClientInfo: params.ClientInfo,
|
||||
IsOfferer: true,
|
||||
IsSendSide: true,
|
||||
AllowPlayoutDelay: params.AllowPlayoutDelay,
|
||||
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: params.DatachannelSlowThreshold,
|
||||
Transport: livekit.SignalTarget_SUBSCRIBER,
|
||||
Handler: TransportManagerTransportHandler{params.SubscriberHandler, t, lgr},
|
||||
FireOnTrackBySdp: params.FireOnTrackBySdp,
|
||||
ProtocolVersion: params.ProtocolVersion,
|
||||
Config: params.Config,
|
||||
DirectionConfig: params.Config.Subscriber,
|
||||
CongestionControlConfig: params.CongestionControlConfig,
|
||||
EnabledCodecs: params.EnabledSubscribeCodecs,
|
||||
Logger: lgr,
|
||||
ClientInfo: params.ClientInfo,
|
||||
IsOfferer: true,
|
||||
IsSendSide: true,
|
||||
AllowPlayoutDelay: params.AllowPlayoutDelay,
|
||||
DataChannelMaxBufferedAmount: params.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: params.DatachannelSlowThreshold,
|
||||
DatachannelLossyTargetLatency: params.DatachannelLossyTargetLatency,
|
||||
Transport: livekit.SignalTarget_SUBSCRIBER,
|
||||
Handler: TransportManagerTransportHandler{params.SubscriberHandler, t, lgr},
|
||||
FireOnTrackBySdp: params.FireOnTrackBySdp,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -341,6 +344,7 @@ func (t *TransportManager) handleSendDataResult(err error, kind string, size int
|
||||
ErrTransportFailure,
|
||||
ErrDataChannelBufferFull,
|
||||
context.DeadlineExceeded,
|
||||
datachannel.ErrDataDroppedByHighBufferedAmount,
|
||||
) {
|
||||
if errors.Is(err, datachannel.ErrDataDroppedBySlowReader) {
|
||||
droppedBySlowReaderCount := t.droppedBySlowReaderCount.Inc()
|
||||
|
||||
+17
-16
@@ -483,22 +483,23 @@ func (r *RoomManager) StartSession(
|
||||
room: room,
|
||||
codecRegressionThreshold: r.config.Video.CodecRegressionThreshold,
|
||||
},
|
||||
ReconnectOnPublicationError: reconnectOnPublicationError,
|
||||
ReconnectOnSubscriptionError: reconnectOnSubscriptionError,
|
||||
ReconnectOnDataChannelError: reconnectOnDataChannelError,
|
||||
VersionGenerator: r.versionGenerator,
|
||||
SubscriberAllowPause: subscriberAllowPause,
|
||||
SubscriptionLimitAudio: r.config.Limit.SubscriptionLimitAudio,
|
||||
SubscriptionLimitVideo: r.config.Limit.SubscriptionLimitVideo,
|
||||
PlayoutDelay: roomInternal.GetPlayoutDelay(),
|
||||
SyncStreams: roomInternal.GetSyncStreams(),
|
||||
ForwardStats: r.forwardStats,
|
||||
MetricConfig: r.config.Metric,
|
||||
UseOneShotSignallingMode: useOneShotSignallingMode,
|
||||
DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold,
|
||||
FireOnTrackBySdp: true,
|
||||
UseSinglePeerConnection: pi.UseSinglePeerConnection,
|
||||
ReconnectOnPublicationError: reconnectOnPublicationError,
|
||||
ReconnectOnSubscriptionError: reconnectOnSubscriptionError,
|
||||
ReconnectOnDataChannelError: reconnectOnDataChannelError,
|
||||
VersionGenerator: r.versionGenerator,
|
||||
SubscriberAllowPause: subscriberAllowPause,
|
||||
SubscriptionLimitAudio: r.config.Limit.SubscriptionLimitAudio,
|
||||
SubscriptionLimitVideo: r.config.Limit.SubscriptionLimitVideo,
|
||||
PlayoutDelay: roomInternal.GetPlayoutDelay(),
|
||||
SyncStreams: roomInternal.GetSyncStreams(),
|
||||
ForwardStats: r.forwardStats,
|
||||
MetricConfig: r.config.Metric,
|
||||
UseOneShotSignallingMode: useOneShotSignallingMode,
|
||||
DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount,
|
||||
DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold,
|
||||
DatachannelLossyTargetLatency: r.config.RTC.DatachannelLossyTargetLatency,
|
||||
FireOnTrackBySdp: true,
|
||||
UseSinglePeerConnection: pi.UseSinglePeerConnection,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -89,23 +89,23 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
|
||||
}
|
||||
rtcEgressLauncher := NewEgressLauncher(egressClient, ioInfoService, objectStore)
|
||||
topicFormatter := rpc.NewTopicFormatter()
|
||||
v, err := rpc.NewTypedRoomClient(clientParams)
|
||||
roomClient, err := rpc.NewTypedRoomClient(clientParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v2, err := rpc.NewTypedParticipantClient(clientParams)
|
||||
participantClient, err := rpc.NewTypedParticipantClient(clientParams)
|
||||
if err != nil {
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
v3, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
|
||||
agentDispatchInternalClient, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
agentDispatchService := NewAgentDispatchService(v3, topicFormatter, roomAllocator, router)
|
||||
agentDispatchService := NewAgentDispatchService(agentDispatchInternalClient, topicFormatter, roomAllocator, router)
|
||||
egressService := NewEgressService(egressClient, rtcEgressLauncher, ioInfoService, roomService)
|
||||
ingressConfig := getIngressConfig(conf)
|
||||
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)
|
||||
rtcService := NewRTCService(conf, roomAllocator, router, telemetryService)
|
||||
v4, err := rpc.NewTypedWHIPParticipantClient(clientParams)
|
||||
whipParticipantClient, err := rpc.NewTypedWHIPParticipantClient(clientParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
serviceWHIPService, err := NewWHIPService(conf, router, roomAllocator, clientParams, topicFormatter, v4)
|
||||
serviceWHIPService, err := NewWHIPService(conf, router, roomAllocator, clientParams, topicFormatter, whipParticipantClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -15,24 +15,30 @@ const (
|
||||
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 {
|
||||
BufferedAmount() uint64
|
||||
}
|
||||
|
||||
type DataChannelWriter[T BufferedAmountGetter] struct {
|
||||
bufferGetter T
|
||||
rawDC datachannel.ReadWriteCloserDeadliner
|
||||
slowThreshold int
|
||||
rate *BitrateCalculator
|
||||
bufferGetter T
|
||||
rawDC datachannel.ReadWriteCloserDeadliner
|
||||
slowThreshold int
|
||||
rate *BitrateCalculator
|
||||
reliable bool
|
||||
targetLatency time.Duration
|
||||
minBufferedAmount uint64
|
||||
}
|
||||
|
||||
// NewDataChannelWriter creates a new DataChannelWriter by detaching the data channel, when
|
||||
// writing to the datachanel times out, it will block and retry if the receiver's bitrate is
|
||||
// above the slowThreshold or drop the data if it's below the threshold. 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] {
|
||||
// NewDataChannelWriterReliable creates a new DataChannelWriter for reliable data channel by
|
||||
// detaching it, when writing to the datachanel times out, it will block and retry if the
|
||||
// receiver's bitrate is above the slowThreshold or drop the data if it's below the threshold.
|
||||
// If the slowThreshold is 0, it will never retry on write timeout.
|
||||
func NewDataChannelWriterReliable[T BufferedAmountGetter](bufferGetter T, rawDC datachannel.ReadWriteCloserDeadliner, slowThreshold int) *DataChannelWriter[T] {
|
||||
var rate *BitrateCalculator
|
||||
if slowThreshold > 0 {
|
||||
rate = NewBitrateCalculator(BitrateDuration, BitrateWindow)
|
||||
@@ -42,6 +48,26 @@ func NewDataChannelWriter[T BufferedAmountGetter](bufferGetter T, rawDC datachan
|
||||
rawDC: rawDC,
|
||||
slowThreshold: slowThreshold,
|
||||
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) {
|
||||
if w.reliable {
|
||||
return w.writeReliable(p)
|
||||
} else {
|
||||
return w.writeUnreliable(p)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *DataChannelWriter[T]) writeReliable(p []byte) (n int, err error) {
|
||||
for {
|
||||
err = w.rawDC.SetWriteDeadline(time.Now().Add(singleWriteTimeout))
|
||||
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 {
|
||||
return w.rawDC.Close()
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package datachannel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -13,7 +14,7 @@ import (
|
||||
func TestDataChannelWriter(t *testing.T) {
|
||||
mockDC := newMockDataChannelWriter()
|
||||
// slow threshold is 1000B/s
|
||||
w := NewDataChannelWriter(mockDC, mockDC, 8000)
|
||||
w := NewDataChannelWriterReliable(mockDC, mockDC, 8000)
|
||||
require.Equal(t, mockDC, w.BufferedAmountGetter())
|
||||
buf := make([]byte, 2000)
|
||||
// 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) {
|
||||
mockDC := newMockDataChannelWriter()
|
||||
w := NewDataChannelWriter(mockDC, mockDC, 0)
|
||||
w := NewDataChannelWriterReliable(mockDC, mockDC, 0)
|
||||
buf := make([]byte, 2000)
|
||||
n, err := w.Write(buf)
|
||||
require.NoError(t, err)
|
||||
@@ -55,6 +56,24 @@ func TestDataChannelWriter_NoSlowThreshold(t *testing.T) {
|
||||
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 {
|
||||
datachannel.ReadWriteCloserDeadliner
|
||||
nextWriteCompleteAt time.Time
|
||||
@@ -92,3 +111,44 @@ func (m *mockDataChannelWriter) SetWriteDeadline(t time.Time) error {
|
||||
func (m *mockDataChannelWriter) SetNextWriteCompleteAt(t time.Time) {
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user