From a26c48304acaf94f085b67acb3160887329e5c29 Mon Sep 17 00:00:00 2001 From: Raja Subramanian Date: Tue, 16 Dec 2025 13:21:39 +0530 Subject: [PATCH] Add support for RTP stream restart. (#4161) * Add support for RTP stream restart. When an unhandled packet is encountered, try a restart sequence. Restart happens when 5 packets with contiguous sequence numbers and same or increasing time stamps are received. Note that this does not work for B-frame type of scenarios, but that is true for receive path handling even before this. As WebRTC does not use B-frames, it is fine. But, needs to be looked at again if B-frames are necessary. It is controlled by a config that is disabled by default. * clean up * debug log --- pkg/config/config.go | 3 + pkg/rtc/mediatrack.go | 40 ++-- pkg/rtc/participant.go | 98 +++++----- pkg/service/roommanager.go | 37 ++-- pkg/sfu/buffer/buffer.go | 63 +++++-- pkg/sfu/downtrack.go | 23 ++- pkg/sfu/receiver.go | 28 ++- pkg/sfu/redprimaryreceiver.go | 6 + pkg/sfu/redreceiver.go | 6 + pkg/sfu/rtpstats/rtpstats_receiver.go | 208 +++++++++++++++++---- pkg/sfu/rtpstats/rtpstats_receiver_test.go | 36 +++- pkg/sfu/utils/rangemap.go | 5 +- pkg/utils/opsqueue.go | 2 +- 13 files changed, 395 insertions(+), 160 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 67e8470e..91b5919a 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -130,6 +130,9 @@ type RTCConfig struct { DatachannelLossyTargetLatency time.Duration `yaml:"datachannel_lossy_target_latency,omitempty"` ForwardStats ForwardStatsConfig `yaml:"forward_stats,omitempty"` + + // enable rtp stream restart detection for published tracks + EnableRTPStreamRestartDetection bool `yaml:"enable_rtp_stream_restart_detection,omitempty"` } type TURNServer struct { diff --git a/pkg/rtc/mediatrack.go b/pkg/rtc/mediatrack.go index 6357971d..ae95a260 100644 --- a/pkg/rtc/mediatrack.go +++ b/pkg/rtc/mediatrack.go @@ -74,25 +74,26 @@ type MediaTrack struct { } type MediaTrackParams struct { - ParticipantID func() livekit.ParticipantID - ParticipantIdentity livekit.ParticipantIdentity - ParticipantVersion uint32 - ParticipantCountry string - BufferFactory *buffer.Factory - ReceiverConfig ReceiverConfig - SubscriberConfig DirectionConfig - PLIThrottleConfig sfu.PLIThrottleConfig - AudioConfig sfu.AudioConfig - VideoConfig config.VideoConfig - Telemetry telemetry.TelemetryService - Logger logger.Logger - Reporter roomobs.TrackReporter - SimTracks map[uint32]SimulcastTrackInfo - OnRTCP func([]rtcp.Packet) - ForwardStats *sfu.ForwardStats - OnTrackEverSubscribed func(livekit.TrackID) - ShouldRegressCodec func() bool - PreferVideoSizeFromMedia bool + ParticipantID func() livekit.ParticipantID + ParticipantIdentity livekit.ParticipantIdentity + ParticipantVersion uint32 + ParticipantCountry string + BufferFactory *buffer.Factory + ReceiverConfig ReceiverConfig + SubscriberConfig DirectionConfig + PLIThrottleConfig sfu.PLIThrottleConfig + AudioConfig sfu.AudioConfig + VideoConfig config.VideoConfig + Telemetry telemetry.TelemetryService + Logger logger.Logger + Reporter roomobs.TrackReporter + SimTracks map[uint32]SimulcastTrackInfo + OnRTCP func([]rtcp.Packet) + ForwardStats *sfu.ForwardStats + OnTrackEverSubscribed func(livekit.TrackID) + ShouldRegressCodec func() bool + PreferVideoSizeFromMedia bool + EnableRTPStreamRestartDetection bool } func NewMediaTrack(params MediaTrackParams, ti *livekit.TrackInfo) *MediaTrack { @@ -403,6 +404,7 @@ func (t *MediaTrack) AddReceiver(receiver *webrtc.RTPReceiver, track sfu.TrackRe sfu.WithAudioConfig(t.params.AudioConfig), sfu.WithLoadBalanceThreshold(20), sfu.WithForwardStats(t.params.ForwardStats), + sfu.WithEnableRTPStreamRestartDetection(t.params.EnableRTPStreamRestartDetection), ) newWR.OnCloseHandler(func() { t.MediaTrackReceiver.SetClosing(false) diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index af669e91..698282d6 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -172,53 +172,54 @@ type ParticipantParams struct { PLIThrottleConfig sfu.PLIThrottleConfig CongestionControlConfig config.CongestionControlConfig // codecs that are enabled for this room - PublishEnabledCodecs []*livekit.Codec - SubscribeEnabledCodecs []*livekit.Codec - Logger logger.Logger - LoggerResolver logger.DeferredFieldResolver - Reporter roomobs.ParticipantSessionReporter - ReporterResolver roomobs.ParticipantReporterResolver - SimTracks map[uint32]SimulcastTrackInfo - Grants *auth.ClaimGrants - InitialVersion uint32 - ClientConf *livekit.ClientConfiguration - ClientInfo ClientInfo - Region string - Migration bool - Reconnect bool - AdaptiveStream bool - AllowTCPFallback bool - TCPFallbackRTTThreshold int - AllowUDPUnstableFallback bool - TURNSEnabled bool - ParticipantListener types.LocalParticipantListener - ParticipantHelper types.LocalParticipantHelper - DisableSupervisor bool - ReconnectOnPublicationError bool - ReconnectOnSubscriptionError bool - ReconnectOnDataChannelError bool - VersionGenerator utils.TimedVersionGenerator - DisableDynacast bool - SubscriberAllowPause bool - SubscriptionLimitAudio int32 - SubscriptionLimitVideo int32 - PlayoutDelay *livekit.PlayoutDelay - SyncStreams bool - ForwardStats *sfu.ForwardStats - DisableSenderReportPassThrough bool - MetricConfig metric.MetricConfig - UseOneShotSignallingMode bool - EnableMetrics bool - DataChannelMaxBufferedAmount uint64 - DatachannelSlowThreshold int - DatachannelLossyTargetLatency time.Duration - FireOnTrackBySdp bool - DisableCodecRegression bool - LastPubReliableSeq uint32 - Country string - PreferVideoSizeFromMedia bool - UseSinglePeerConnection bool - EnableDataTracks bool + PublishEnabledCodecs []*livekit.Codec + SubscribeEnabledCodecs []*livekit.Codec + Logger logger.Logger + LoggerResolver logger.DeferredFieldResolver + Reporter roomobs.ParticipantSessionReporter + ReporterResolver roomobs.ParticipantReporterResolver + SimTracks map[uint32]SimulcastTrackInfo + Grants *auth.ClaimGrants + InitialVersion uint32 + ClientConf *livekit.ClientConfiguration + ClientInfo ClientInfo + Region string + Migration bool + Reconnect bool + AdaptiveStream bool + AllowTCPFallback bool + TCPFallbackRTTThreshold int + AllowUDPUnstableFallback bool + TURNSEnabled bool + ParticipantListener types.LocalParticipantListener + ParticipantHelper types.LocalParticipantHelper + DisableSupervisor bool + ReconnectOnPublicationError bool + ReconnectOnSubscriptionError bool + ReconnectOnDataChannelError bool + VersionGenerator utils.TimedVersionGenerator + DisableDynacast bool + SubscriberAllowPause bool + SubscriptionLimitAudio int32 + SubscriptionLimitVideo int32 + PlayoutDelay *livekit.PlayoutDelay + SyncStreams bool + ForwardStats *sfu.ForwardStats + DisableSenderReportPassThrough bool + MetricConfig metric.MetricConfig + UseOneShotSignallingMode bool + EnableMetrics bool + DataChannelMaxBufferedAmount uint64 + DatachannelSlowThreshold int + DatachannelLossyTargetLatency time.Duration + FireOnTrackBySdp bool + DisableCodecRegression bool + LastPubReliableSeq uint32 + Country string + PreferVideoSizeFromMedia bool + UseSinglePeerConnection bool + EnableDataTracks bool + EnableRTPStreamRestartDetection bool } type ParticipantImpl struct { @@ -3256,7 +3257,8 @@ func (p *ParticipantImpl) addMediaTrack(signalCid string, ti *livekit.TrackInfo) ShouldRegressCodec: func() bool { return p.helper().ShouldRegressCodec() }, - PreferVideoSizeFromMedia: p.params.PreferVideoSizeFromMedia, + PreferVideoSizeFromMedia: p.params.PreferVideoSizeFromMedia, + EnableRTPStreamRestartDetection: p.params.EnableRTPStreamRestartDetection, }, ti) mt.OnSubscribedMaxQualityChange(p.onSubscribedMaxQualityChange) diff --git a/pkg/service/roommanager.go b/pkg/service/roommanager.go index 0bdbf66e..62c80b90 100644 --- a/pkg/service/roommanager.go +++ b/pkg/service/roommanager.go @@ -486,24 +486,25 @@ 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, - DatachannelLossyTargetLatency: r.config.RTC.DatachannelLossyTargetLatency, - FireOnTrackBySdp: true, - UseSinglePeerConnection: pi.UseSinglePeerConnection, - EnableDataTracks: r.config.EnableDataTracks, + 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, + EnableDataTracks: r.config.EnableDataTracks, + EnableRTPStreamRestartDetection: r.config.RTC.EnableRTPStreamRestartDetection, }) if err != nil { return err diff --git a/pkg/sfu/buffer/buffer.go b/pkg/sfu/buffer/buffer.go index 7c3fb7c8..3c62d13c 100644 --- a/pkg/sfu/buffer/buffer.go +++ b/pkg/sfu/buffer/buffer.go @@ -85,6 +85,7 @@ type ExtPacket struct { AbsCaptureTimeExt *act.AbsCaptureTime IsOutOfOrder bool IsBuffered bool + IsRestart bool } // VideoSize represents video resolution @@ -123,10 +124,11 @@ type Buffer struct { latestTSForAudioLevelInitialized bool latestTSForAudioLevel uint32 - twcc *twcc.Responder - audioLevelParams audio.AudioLevelParams - audioLevel *audio.AudioLevel - enableAudioLossProxying bool + twcc *twcc.Responder + audioLevelParams audio.AudioLevelParams + audioLevel *audio.AudioLevel + enableAudioLossProxying bool + enableStreamRestartDetection bool lastPacketRead int @@ -229,6 +231,13 @@ func (b *Buffer) SetAudioLossProxying(enable bool) { b.enableAudioLossProxying = enable } +func (b *Buffer) SetStreamRestartDetection(enable bool) { + b.Lock() + defer b.Unlock() + + b.enableStreamRestartDetection = enable +} + func (b *Buffer) Bind(params webrtc.RTPParameters, codec webrtc.RTPCodecCapability, bitrates int) error { b.Lock() defer b.Unlock() @@ -242,13 +251,7 @@ func (b *Buffer) Bind(params webrtc.RTPParameters, codec webrtc.RTPCodecCapabili return errInvalidCodec } - b.rtpStats = rtpstats.NewRTPStatsReceiver(rtpstats.RTPStatsParams{ - ClockRate: codec.ClockRate, - Logger: b.logger, - }) - b.rrSnapshotId = b.rtpStats.NewSnapshotId() - b.deltaStatsSnapshotId = b.rtpStats.NewSnapshotId() - b.ppsSnapshotId = b.rtpStats.NewSnapshotId() + b.setupRTPStats(codec.ClockRate) b.clockRate = codec.ClockRate b.lastReport = mono.UnixNano() @@ -356,6 +359,16 @@ func (b *Buffer) OnCodecChange(fn func(webrtc.RTPCodecParameters)) { b.Unlock() } +func (b *Buffer) setupRTPStats(clockRate uint32) { + b.rtpStats = rtpstats.NewRTPStatsReceiver(rtpstats.RTPStatsParams{ + ClockRate: clockRate, + Logger: b.logger, + }) + b.rrSnapshotId = b.rtpStats.NewSnapshotId() + b.deltaStatsSnapshotId = b.rtpStats.NewSnapshotId() + b.ppsSnapshotId = b.rtpStats.NewSnapshotId() +} + func (b *Buffer) createDDParserAndFrameRateCalculator() { if mime.IsMimeTypeSVCCapable(b.mime) || b.mime == mime.MimeTypeVP8 { frc := NewFrameRateCalculatorDD(b.clockRate, b.logger) @@ -663,8 +676,29 @@ func (b *Buffer) calc(rawPkt []byte, rtpPacket *rtp.Packet, arrivalTime int64, i // process header extensions always as padding packets could be used for probing b.processHeaderExtensions(rtpPacket, arrivalTime, isRTX) + isRestart := false flowState := b.updateStreamState(rtpPacket, arrivalTime) - if flowState.IsNotHandled { + switch flowState.UnhandledReason { + case rtpstats.RTPFlowUnhandledReasonNone: + case rtpstats.RTPFlowUnhandledReasonRestart: + if !b.enableStreamRestartDetection { + return + } + + b.rtpStats.Stop() + b.logger.Infow("stream restart - rtp stats", b.rtpStats) + + b.snRangeMap = utils.NewRangeMap[uint64, uint64](100) + b.setupRTPStats(b.clockRate) + b.bucket.ResyncOnNextPacket() + if b.nacker != nil { + b.nacker = nack.NewNACKQueue(nack.NackQueueParamsDefault) + } + b.extPackets.Clear() + + flowState = b.updateStreamState(rtpPacket, arrivalTime) + isRestart = true + default: return } @@ -748,7 +782,7 @@ func (b *Buffer) calc(rawPkt []byte, rtpPacket *rtp.Packet, arrivalTime int64, i return } - ep := b.getExtPacket(rtpPacket, arrivalTime, isBuffered, flowState) + ep := b.getExtPacket(rtpPacket, arrivalTime, isBuffered, isRestart, flowState) if ep == nil { return } @@ -920,7 +954,7 @@ func (b *Buffer) processHeaderExtensions(p *rtp.Packet, arrivalTime int64, isRTX } } -func (b *Buffer) getExtPacket(rtpPacket *rtp.Packet, arrivalTime int64, isBuffered bool, flowState rtpstats.RTPFlowState) *ExtPacket { +func (b *Buffer) getExtPacket(rtpPacket *rtp.Packet, arrivalTime int64, isBuffered bool, isRestart bool, flowState rtpstats.RTPFlowState) *ExtPacket { ep := ExtPacketFactory.Get().(*ExtPacket) *ep = ExtPacket{ Arrival: arrivalTime, @@ -933,6 +967,7 @@ func (b *Buffer) getExtPacket(rtpPacket *rtp.Packet, arrivalTime int64, isBuffer }, IsOutOfOrder: flowState.IsOutOfOrder, IsBuffered: isBuffered, + IsRestart: isRestart, } if len(rtpPacket.Payload) == 0 { diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index 7eebbf0d..c0e3a1ac 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -70,6 +70,7 @@ type TrackSender interface { ) error Resync() SetReceiver(TrackReceiver) + ReceiverRestart() } // ------------------------------------------------------------------- @@ -669,7 +670,7 @@ func (d *DownTrack) handleUpstreamCodecChange(mimeType string) { return } - oldPT, oldRtxPT, oldCodec := d.payloadType.Load(), d.payloadTypeRTX.Load(), d.codec + oldPT, oldRtxPT, oldCodec := d.payloadType.Load(), d.payloadTypeRTX.Load(), d.codec.Load().(webrtc.RTPCodecCapability) var codec webrtc.RTPCodecParameters for _, c := range d.upstreamCodecs { @@ -908,13 +909,7 @@ func (d *DownTrack) postKeyFrameRequestEvent() { func (d *DownTrack) keyFrameRequester() { getInterval := func() time.Duration { - interval := 2 * d.rtpStats.GetRtt() - if interval < keyFrameIntervalMin { - interval = keyFrameIntervalMin - } - if interval > keyFrameIntervalMax { - interval = keyFrameIntervalMax - } + interval := min(max(2*d.rtpStats.GetRtt(), keyFrameIntervalMin), keyFrameIntervalMax) return time.Duration(interval) * time.Millisecond } @@ -1640,6 +1635,18 @@ func (d *DownTrack) Resync() { d.forwarder.Resync() } +func (d *DownTrack) ReceiverRestart() { + d.bindLock.Lock() + codec := d.codec.Load().(webrtc.RTPCodecCapability) + d.bindLock.Unlock() + + d.params.Logger.Infow("upstream receiver restart") + + receiver := d.Receiver() + d.forwarder.Restart() + d.forwarder.DetermineCodec(codec, receiver.HeaderExtensions(), receiver.VideoLayerMode()) +} + func (d *DownTrack) CreateSourceDescriptionChunks() []rtcp.SourceDescriptionChunk { transceiver := d.transceiver.Load() if d.bindState.Load() != bindStateBound || transceiver == nil { diff --git a/pkg/sfu/receiver.go b/pkg/sfu/receiver.go index a0017501..f459b103 100644 --- a/pkg/sfu/receiver.go +++ b/pkg/sfu/receiver.go @@ -122,7 +122,7 @@ type TrackReceiver interface { DeleteDownTrack(participantID livekit.ParticipantID) GetDownTracks() []TrackSender - DebugInfo() map[string]interface{} + DebugInfo() map[string]any TrackInfo() *livekit.TrackInfo UpdateTrackInfo(ti *livekit.TrackInfo) @@ -156,6 +156,7 @@ type REDTransformer interface { publisherSRData *livekit.RTCPSenderReportState, ) ResyncDownTracks() + OnStreamRestart() CanClose() bool Close() } @@ -166,8 +167,9 @@ var _ TrackReceiver = (*WebRTCReceiver)(nil) type WebRTCReceiver struct { logger logger.Logger - pliThrottleConfig PLIThrottleConfig - audioConfig AudioConfig + pliThrottleConfig PLIThrottleConfig + audioConfig AudioConfig + enableRTPStreamRestartDetection bool trackID livekit.TrackID streamID string @@ -228,6 +230,13 @@ func WithAudioConfig(audioConfig AudioConfig) ReceiverOpts { } } +func WithEnableRTPStreamRestartDetection(enable bool) ReceiverOpts { + return func(w *WebRTCReceiver) *WebRTCReceiver { + w.enableRTPStreamRestartDetection = enable + return w + } +} + // WithLoadBalanceThreshold enables parallelization of packet writes when downTracks exceeds threshold // Value should be between 3 and 150. // For a server handling a few large rooms, use a smaller value (required to handle very large (250+ participant) rooms). @@ -412,6 +421,7 @@ func (w *WebRTCReceiver) AddUpTrack(track TrackRemote, buff *buffer.Buffer) erro Config: w.audioConfig.AudioLevelConfig, }) buff.SetAudioLossProxying(w.audioConfig.EnableLossProxying) + buff.SetStreamRestartDetection(w.enableRTPStreamRestartDetection) buff.OnRtcpFeedback(w.sendRTCP) buff.OnRtcpSenderReport(func() { srData := buff.GetSenderReportData() @@ -438,7 +448,6 @@ func (w *WebRTCReceiver) AddUpTrack(track TrackRemote, buff *buffer.Buffer) erro cb() } }) - if w.Kind() == webrtc.RTPCodecTypeVideo && layer == 0 { buff.OnCodecChange(w.handleCodecChange) } @@ -795,6 +804,17 @@ func (w *WebRTCReceiver) forwardRTP(layer int32, buff *buffer.Buffer) { } dequeuedAt := mono.UnixNano() + if pkt.IsRestart { + w.logger.Infow("stream restarted", "layer", layer) + w.downTrackSpreader.Broadcast(func(dt TrackSender) { + dt.ReceiverRestart() + }) + + if rt := w.redTransformer.Load(); rt != nil { + rt.(REDTransformer).OnStreamRestart() + } + } + if pkt.Packet.PayloadType != uint8(w.codec.PayloadType) { // drop packets as we don't support codec fallback directly w.logger.Debugw( diff --git a/pkg/sfu/redprimaryreceiver.go b/pkg/sfu/redprimaryreceiver.go index 18674f94..6c679b4d 100644 --- a/pkg/sfu/redprimaryreceiver.go +++ b/pkg/sfu/redprimaryreceiver.go @@ -141,6 +141,12 @@ func (r *RedPrimaryReceiver) ResyncDownTracks() { }) } +func (r *RedPrimaryReceiver) OnStreamRestart() { + r.downTrackSpreader.Broadcast(func(dt TrackSender) { + dt.ReceiverRestart() + }) +} + func (r *RedPrimaryReceiver) IsClosed() bool { return r.closed.Load() } diff --git a/pkg/sfu/redreceiver.go b/pkg/sfu/redreceiver.go index 4d67c710..65168c84 100644 --- a/pkg/sfu/redreceiver.go +++ b/pkg/sfu/redreceiver.go @@ -138,6 +138,12 @@ func (r *RedReceiver) ResyncDownTracks() { }) } +func (r *RedReceiver) OnStreamRestart() { + r.downTrackSpreader.Broadcast(func(dt TrackSender) { + dt.ReceiverRestart() + }) +} + func (r *RedReceiver) CanClose() bool { return r.closed.Load() || r.downTrackSpreader.DownTrackCount() == 0 } diff --git a/pkg/sfu/rtpstats/rtpstats_receiver.go b/pkg/sfu/rtpstats/rtpstats_receiver.go index d4afa828..8576fc27 100644 --- a/pkg/sfu/rtpstats/rtpstats_receiver.go +++ b/pkg/sfu/rtpstats/rtpstats_receiver.go @@ -38,12 +38,50 @@ const ( cReportSlack = float64(60.0) cTSJumpTooHighFactor = float64(1.5) + + restartThreshold = 5 ) // --------------------------------------------------------------------- +type RTPFlowUnhandledReason int + +const ( + RTPFlowUnhandledReasonNone RTPFlowUnhandledReason = iota + RTPFlowUnhandledReasonEnded + RTPFlowUnhandledReasonPaddingOnly + RTPFlowUnhandledReasonPreStartTimestamp + RTPFlowUnhandledReasonOldTimestamp + RTPFlowUnhandledReasonPreStartSequenceNumber + RTPFlowUnhandledReasonOldSequenceNumber + RTPFlowUnhandledReasonRestart +) + +func (r RTPFlowUnhandledReason) String() string { + switch r { + case RTPFlowUnhandledReasonNone: + return "NONE" + case RTPFlowUnhandledReasonEnded: + return "ENDED" + case RTPFlowUnhandledReasonPaddingOnly: + return "PADDING_ONLY" + case RTPFlowUnhandledReasonPreStartTimestamp: + return "PRE_START_TIMESTAMP" + case RTPFlowUnhandledReasonOldTimestamp: + return "OLD_TIMESTAMP" + case RTPFlowUnhandledReasonPreStartSequenceNumber: + return "PRE_START_SEQUENCE_NUMBER" + case RTPFlowUnhandledReasonOldSequenceNumber: + return "OLD_SEQUENCE_NUMBER" + case RTPFlowUnhandledReasonRestart: + return "RESTART" + default: + return fmt.Sprintf("UNKNOWN: %d", int(r)) + } +} + type RTPFlowState struct { - IsNotHandled bool + UnhandledReason RTPFlowUnhandledReason LossStartInclusive uint64 LossEndExclusive uint64 @@ -60,7 +98,7 @@ func (r *RTPFlowState) MarshalLogObject(e zapcore.ObjectEncoder) error { return nil } - e.AddBool("IsNotHandled", r.IsNotHandled) + e.AddString("UnhandledReason", r.UnhandledReason.String()) e.AddUint64("LossStartInclusive", r.LossStartInclusive) e.AddUint64("LossEndExclusive", r.LossEndExclusive) e.AddBool("IsDuplicate", r.IsDuplicate) @@ -72,6 +110,19 @@ func (r *RTPFlowState) MarshalLogObject(e zapcore.ObjectEncoder) error { // --------------------------------------------------------------------- +type packet struct { + sequenceNumber uint16 + timestamp uint32 +} + +func (p packet) MarshalLogObject(e zapcore.ObjectEncoder) error { + e.AddUint16("sequenceNumber", p.sequenceNumber) + e.AddUint32("timestamp", p.timestamp) + return nil +} + +// --------------------------------------------------------------------- + type RTPStatsReceiver struct { *rtpStatsBase @@ -90,6 +141,13 @@ type RTPStatsReceiver struct { largeJumpCount int largeJumpNegativeCount int timeReversedCount int + + packetsDroppedPreStartTimestamp int + packetsDroppedOldTimestamp int + packetsDroppedPreStartSequenceNumber int + packetsDroppedOldSequenceNumber int + + restartPackets []packet } func NewRTPStatsReceiver(params RTPStatsParams) *RTPStatsReceiver { @@ -137,7 +195,7 @@ func (r *RTPStatsReceiver) Update( defer r.lock.Unlock() if r.endTime != 0 { - flowState.IsNotHandled = true + flowState.UnhandledReason = RTPFlowUnhandledReasonEnded return } @@ -179,7 +237,7 @@ func (r *RTPStatsReceiver) Update( if !r.initialized { if payloadSize == 0 { // do not start on a padding only packet - flowState.IsNotHandled = true + flowState.UnhandledReason = RTPFlowUnhandledReasonPaddingOnly return } @@ -215,44 +273,71 @@ func (r *RTPStatsReceiver) Update( if resTS.IsUnhandled { undoUpdates() - flowState.IsNotHandled = true + r.packetsDroppedPreStartTimestamp++ + logger().Warnw("dropping packet, pre-start timestamp", nil) + + if r.maybeRestart(sequenceNumber, timestamp, payloadSize) { + logger().Infow("potential restart") + r.resetRestart() + flowState.UnhandledReason = RTPFlowUnhandledReasonRestart + } else { + flowState.UnhandledReason = RTPFlowUnhandledReasonPreStartTimestamp + } return } gapTS = int64(resTS.ExtendedVal - resTS.PreExtendedHighest) - // it is possible to receive old packets in two different scenarios - // as it is not possible to detect how far to roll back, ignore old packets - // - // Case 1: - // Very old time stamp, happens under the following conditions - // - resume after long mute, big time stamp jump - // - an out of order packet from before the mute arrives (unsure what causes this - // very old packet to be transmitted from remote), causing time stamp to jump back - // to before mute, but it appears like it has rolled over. - // Use a threshold against expected to ignore these. - if gapSN < 0 && gapTS > 0 { - expectedTSJump = int64(r.rtpConverter.ToRTPExt(time.Duration(timeSinceHighest))) - if gapTS > int64(float64(expectedTSJump)*cTSJumpTooHighFactor) { + if !resSN.IsUnhandled { + // it is possible to receive old packets in two different scenarios + // as it is not possible to detect how far to roll back, ignore old packets + // + // Case 1: + // Very old time stamp, happens under the following conditions + // - resume after long mute, this casues big time stamp jump ahead for the packets + // after unmute + // - an out of order packet from before the mute arrives (unsure what causes this + // very old packet to be transmitted from remote), causing time stamp to jump back + // to before mute, but it appears like it has rolled over. + // Use a threshold against expected to ignore these. + if gapSN < 0 && gapTS > 0 { + expectedTSJump = int64(r.rtpConverter.ToRTPExt(time.Duration(timeSinceHighest))) + if gapTS > int64(float64(expectedTSJump)*cTSJumpTooHighFactor) { + undoUpdates() + + r.packetsDroppedOldTimestamp++ + logger().Warnw("dropping packet, old timestamp", nil) + + if r.maybeRestart(sequenceNumber, timestamp, payloadSize) { + logger().Infow("potential restart") + r.resetRestart() + flowState.UnhandledReason = RTPFlowUnhandledReasonRestart + } else { + flowState.UnhandledReason = RTPFlowUnhandledReasonOldTimestamp + } + return + } + } + + // Case 2: + // Sequence number looks like it is moving forward, but it is actually a very old packet. + if gapTS < 0 && gapSN > 0 { undoUpdates() - logger().Warnw("dropping old packet, timestamp", nil) + r.packetsDroppedOldSequenceNumber++ + expectedTSJump = int64(r.rtpConverter.ToRTPExt(time.Duration(timeSinceHighest))) + logger().Warnw("dropping packet, old sequence number", nil) - flowState.IsNotHandled = true + if r.maybeRestart(sequenceNumber, timestamp, payloadSize) { + logger().Infow("potential restart") + r.resetRestart() + flowState.UnhandledReason = RTPFlowUnhandledReasonRestart + } else { + flowState.UnhandledReason = RTPFlowUnhandledReasonOldSequenceNumber + } return } } - // Case 2: - // Sequence number looks like it is moving forward, but it is actually a very old packet. - if gapTS < 0 && gapSN > 0 { - undoUpdates() - - logger().Warnw("dropping old packet, sequence number", nil) - - flowState.IsNotHandled = true - return - } - // it is possible that sequence number has rolled over too if (gapSN < 0 || gapSN > (1<<15)) && gapTS > 0 && payloadSize > 0 { // not possible to know how many cycles of sequence number roll over could have happened, @@ -270,9 +355,16 @@ func (r *RTPStatsReceiver) Update( if resSN.IsUnhandled { undoUpdates() - logger().Warnw("dropping packet, cannot find sequence", nil) + r.packetsDroppedPreStartSequenceNumber++ + logger().Warnw("dropping packet, pre-start sequence number", nil) - flowState.IsNotHandled = true + if r.maybeRestart(sequenceNumber, timestamp, payloadSize) { + logger().Infow("potential restart") + r.resetRestart() + flowState.UnhandledReason = RTPFlowUnhandledReasonRestart + } else { + flowState.UnhandledReason = RTPFlowUnhandledReasonPreStartSequenceNumber + } return } } @@ -364,6 +456,7 @@ func (r *RTPStatsReceiver) Update( r.updateJitter(resTS.ExtendedVal, packetTime) } } + r.resetRestart() return } @@ -605,15 +698,9 @@ func (r *RTPStatsReceiver) GetRtcpReceptionReport(ssrc uint32, proxyFracLost uin packetsLost = 0 } lossRate := float32(packetsLost) / float32(packetsExpected) - fracLost := uint8(lossRate * 256.0) - if proxyFracLost > fracLost { - fracLost = proxyFracLost - } + fracLost := max(proxyFracLost, uint8(lossRate*256.0)) - totalLost := r.packetsLost - if totalLost > 0xffffff { // 24-bits max - totalLost = 0xffffff - } + totalLost := min(r.packetsLost, 0xffffff) // 24-bits max lastSR := uint32(0) dlsr := uint32(0) @@ -707,6 +794,31 @@ func (r *RTPStatsReceiver) ExtendedHighestSequenceNumber() uint64 { return r.sequenceNumber.GetExtendedHighest() } +func (r *RTPStatsReceiver) maybeRestart(sn uint16, ts uint32, payloadSize int) bool { + if payloadSize > 0 { + r.restartPackets = append(r.restartPackets, packet{sn, ts}) + } + if len(r.restartPackets) < restartThreshold { + return false + } + + r.restartPackets = r.restartPackets[max(len(r.restartPackets)-restartThreshold, 0):] + // check for contiguous sequence numbers and equal or increasing timestamps + for i := 1; i < len(r.restartPackets); i++ { + p := &r.restartPackets[i] + prev := &r.restartPackets[i-1] + if p.sequenceNumber != prev.sequenceNumber+1 || (p.timestamp-prev.timestamp) > (1<<31) { + return false + } + } + + return true +} + +func (r *RTPStatsReceiver) resetRestart() { + r.restartPackets = r.restartPackets[:0] +} + // ---------------------------------- type lockedRTPStatsReceiverLogEncoder struct { @@ -736,6 +848,20 @@ func (r lockedRTPStatsReceiverLogEncoder) MarshalLogObject(e zapcore.ObjectEncod e.AddUint64("extHighestTS", extHighestTS) e.AddObject("propagationDelayEstimator", r.propagationDelayEstimator) + + e.AddInt("clockSkewCount", r.clockSkewCount) + e.AddInt("clockSkewMediaPathCount", r.clockSkewMediaPathCount) + e.AddInt("outOfOrderSenderReportCount", r.outOfOrderSenderReportCount) + e.AddInt("largeJumpCount", r.largeJumpCount) + e.AddInt("largeJumpNegativeCount", r.largeJumpNegativeCount) + e.AddInt("timeReversedCount", r.timeReversedCount) + + e.AddInt("packetsDroppedBadTimestamp", r.packetsDroppedPreStartTimestamp) + e.AddInt("packetsDroppedOldTimestamp", r.packetsDroppedOldTimestamp) + e.AddInt("packetsDroppedOldSequenceNumber", r.packetsDroppedOldSequenceNumber) + e.AddInt("packetsDroppedBadSequenceNumber", r.packetsDroppedPreStartSequenceNumber) + + e.AddArray("restartPackets", logger.ObjectSlice(r.restartPackets)) return nil } diff --git a/pkg/sfu/rtpstats/rtpstats_receiver_test.go b/pkg/sfu/rtpstats/rtpstats_receiver_test.go index d895b57c..32ca8198 100644 --- a/pkg/sfu/rtpstats/rtpstats_receiver_test.go +++ b/pkg/sfu/rtpstats/rtpstats_receiver_test.go @@ -89,7 +89,7 @@ func Test_RTPStatsReceiver_Update(t *testing.T) { len(packet.Payload), 0, ) - require.True(t, flowState.IsNotHandled) + require.Equal(t, RTPFlowUnhandledReasonPreStartTimestamp, flowState.UnhandledReason) require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest()) require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest())) require.Equal(t, timestamp, r.timestamp.GetHighest()) @@ -108,7 +108,7 @@ func Test_RTPStatsReceiver_Update(t *testing.T) { len(packet.Payload), 0, ) - require.True(t, flowState.IsNotHandled) + require.Equal(t, RTPFlowUnhandledReasonPreStartTimestamp, flowState.UnhandledReason) require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest()) require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest())) require.Equal(t, timestamp, r.timestamp.GetHighest()) @@ -218,7 +218,7 @@ func Test_RTPStatsReceiver_Update(t *testing.T) { len(packet.Payload), 0, ) - require.True(t, flowState.IsNotHandled) + require.Equal(t, RTPFlowUnhandledReasonOldSequenceNumber, flowState.UnhandledReason) require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest()) require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest())) require.Equal(t, timestamp, r.timestamp.GetHighest()) @@ -226,3 +226,33 @@ func Test_RTPStatsReceiver_Update(t *testing.T) { r.Stop() } + +func Test_RTPStatsReceiver_Restart(t *testing.T) { + clockRate := uint32(90000) + r := NewRTPStatsReceiver(RTPStatsParams{ + ClockRate: clockRate, + Logger: logger.GetLogger(), + }) + + // should not restart till there are at least threshold packets + require.False(t, r.maybeRestart(10, 20, 1000)) + require.False(t, r.maybeRestart(11, 20, 1000)) + require.False(t, r.maybeRestart(13, 20, 1000)) + require.False(t, r.maybeRestart(14, 20, 1000)) + // although adding 5th packet should have enough packets for a check, + // still should not restart as there is a sequence number gap between 11 and 13 + require.False(t, r.maybeRestart(15, 20, 1000)) + require.False(t, r.maybeRestart(16, 19, 1000)) + // has enough packets, but still cannot restart because timestamps are not increasing + require.False(t, r.maybeRestart(17, 21, 1000)) + require.False(t, r.maybeRestart(18, 21, 1000)) + require.False(t, r.maybeRestart(19, 21, 1000)) + // can restart as there are enough packets with proper sequencing + require.True(t, r.maybeRestart(20, 21, 1000)) + require.Equal(t, restartThreshold, len(r.restartPackets)) + + r.resetRestart() + require.Zero(t, len(r.restartPackets)) + + r.Stop() +} diff --git a/pkg/sfu/utils/rangemap.go b/pkg/sfu/utils/rangemap.go index 6ca2332e..8fb36d54 100644 --- a/pkg/sfu/utils/rangemap.go +++ b/pkg/sfu/utils/rangemap.go @@ -80,10 +80,7 @@ func (r *RangeMap[RT, VT]) MarshalLogObject(e zapcore.ObjectEncoder) error { e.AddInt("numRanges", len(r.ranges)) // just the last 10 ranges max - startIdx := len(r.ranges) - 10 - if startIdx < 0 { - startIdx = 0 - } + startIdx := max(len(r.ranges)-10, 0) for i := startIdx; i < len(r.ranges); i++ { e.AddObject(fmt.Sprintf("range[%d]", i), r.ranges[i]) } diff --git a/pkg/utils/opsqueue.go b/pkg/utils/opsqueue.go index 5e88b959..7236165e 100644 --- a/pkg/utils/opsqueue.go +++ b/pkg/utils/opsqueue.go @@ -128,7 +128,7 @@ func (oq *opsQueueBase[T]) Enqueue(op T) { select { case oq.wake <- struct{}{}: default: - oq.params.Logger.Infow("could not wake ops queue", "name", oq.params.Name) + oq.params.Logger.Debugw("could not wake ops queue", "name", oq.params.Name) } } }