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
This commit is contained in:
@@ -130,6 +130,9 @@ type RTCConfig struct {
|
|||||||
DatachannelLossyTargetLatency time.Duration `yaml:"datachannel_lossy_target_latency,omitempty"`
|
DatachannelLossyTargetLatency time.Duration `yaml:"datachannel_lossy_target_latency,omitempty"`
|
||||||
|
|
||||||
ForwardStats ForwardStatsConfig `yaml:"forward_stats,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 {
|
type TURNServer struct {
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ type MediaTrackParams struct {
|
|||||||
OnTrackEverSubscribed func(livekit.TrackID)
|
OnTrackEverSubscribed func(livekit.TrackID)
|
||||||
ShouldRegressCodec func() bool
|
ShouldRegressCodec func() bool
|
||||||
PreferVideoSizeFromMedia bool
|
PreferVideoSizeFromMedia bool
|
||||||
|
EnableRTPStreamRestartDetection bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMediaTrack(params MediaTrackParams, ti *livekit.TrackInfo) *MediaTrack {
|
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.WithAudioConfig(t.params.AudioConfig),
|
||||||
sfu.WithLoadBalanceThreshold(20),
|
sfu.WithLoadBalanceThreshold(20),
|
||||||
sfu.WithForwardStats(t.params.ForwardStats),
|
sfu.WithForwardStats(t.params.ForwardStats),
|
||||||
|
sfu.WithEnableRTPStreamRestartDetection(t.params.EnableRTPStreamRestartDetection),
|
||||||
)
|
)
|
||||||
newWR.OnCloseHandler(func() {
|
newWR.OnCloseHandler(func() {
|
||||||
t.MediaTrackReceiver.SetClosing(false)
|
t.MediaTrackReceiver.SetClosing(false)
|
||||||
|
|||||||
@@ -219,6 +219,7 @@ type ParticipantParams struct {
|
|||||||
PreferVideoSizeFromMedia bool
|
PreferVideoSizeFromMedia bool
|
||||||
UseSinglePeerConnection bool
|
UseSinglePeerConnection bool
|
||||||
EnableDataTracks bool
|
EnableDataTracks bool
|
||||||
|
EnableRTPStreamRestartDetection bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type ParticipantImpl struct {
|
type ParticipantImpl struct {
|
||||||
@@ -3257,6 +3258,7 @@ func (p *ParticipantImpl) addMediaTrack(signalCid string, ti *livekit.TrackInfo)
|
|||||||
return p.helper().ShouldRegressCodec()
|
return p.helper().ShouldRegressCodec()
|
||||||
},
|
},
|
||||||
PreferVideoSizeFromMedia: p.params.PreferVideoSizeFromMedia,
|
PreferVideoSizeFromMedia: p.params.PreferVideoSizeFromMedia,
|
||||||
|
EnableRTPStreamRestartDetection: p.params.EnableRTPStreamRestartDetection,
|
||||||
}, ti)
|
}, ti)
|
||||||
|
|
||||||
mt.OnSubscribedMaxQualityChange(p.onSubscribedMaxQualityChange)
|
mt.OnSubscribedMaxQualityChange(p.onSubscribedMaxQualityChange)
|
||||||
|
|||||||
@@ -504,6 +504,7 @@ func (r *RoomManager) StartSession(
|
|||||||
FireOnTrackBySdp: true,
|
FireOnTrackBySdp: true,
|
||||||
UseSinglePeerConnection: pi.UseSinglePeerConnection,
|
UseSinglePeerConnection: pi.UseSinglePeerConnection,
|
||||||
EnableDataTracks: r.config.EnableDataTracks,
|
EnableDataTracks: r.config.EnableDataTracks,
|
||||||
|
EnableRTPStreamRestartDetection: r.config.RTC.EnableRTPStreamRestartDetection,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
+45
-10
@@ -85,6 +85,7 @@ type ExtPacket struct {
|
|||||||
AbsCaptureTimeExt *act.AbsCaptureTime
|
AbsCaptureTimeExt *act.AbsCaptureTime
|
||||||
IsOutOfOrder bool
|
IsOutOfOrder bool
|
||||||
IsBuffered bool
|
IsBuffered bool
|
||||||
|
IsRestart bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// VideoSize represents video resolution
|
// VideoSize represents video resolution
|
||||||
@@ -127,6 +128,7 @@ type Buffer struct {
|
|||||||
audioLevelParams audio.AudioLevelParams
|
audioLevelParams audio.AudioLevelParams
|
||||||
audioLevel *audio.AudioLevel
|
audioLevel *audio.AudioLevel
|
||||||
enableAudioLossProxying bool
|
enableAudioLossProxying bool
|
||||||
|
enableStreamRestartDetection bool
|
||||||
|
|
||||||
lastPacketRead int
|
lastPacketRead int
|
||||||
|
|
||||||
@@ -229,6 +231,13 @@ func (b *Buffer) SetAudioLossProxying(enable bool) {
|
|||||||
b.enableAudioLossProxying = enable
|
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 {
|
func (b *Buffer) Bind(params webrtc.RTPParameters, codec webrtc.RTPCodecCapability, bitrates int) error {
|
||||||
b.Lock()
|
b.Lock()
|
||||||
defer b.Unlock()
|
defer b.Unlock()
|
||||||
@@ -242,13 +251,7 @@ func (b *Buffer) Bind(params webrtc.RTPParameters, codec webrtc.RTPCodecCapabili
|
|||||||
return errInvalidCodec
|
return errInvalidCodec
|
||||||
}
|
}
|
||||||
|
|
||||||
b.rtpStats = rtpstats.NewRTPStatsReceiver(rtpstats.RTPStatsParams{
|
b.setupRTPStats(codec.ClockRate)
|
||||||
ClockRate: codec.ClockRate,
|
|
||||||
Logger: b.logger,
|
|
||||||
})
|
|
||||||
b.rrSnapshotId = b.rtpStats.NewSnapshotId()
|
|
||||||
b.deltaStatsSnapshotId = b.rtpStats.NewSnapshotId()
|
|
||||||
b.ppsSnapshotId = b.rtpStats.NewSnapshotId()
|
|
||||||
|
|
||||||
b.clockRate = codec.ClockRate
|
b.clockRate = codec.ClockRate
|
||||||
b.lastReport = mono.UnixNano()
|
b.lastReport = mono.UnixNano()
|
||||||
@@ -356,6 +359,16 @@ func (b *Buffer) OnCodecChange(fn func(webrtc.RTPCodecParameters)) {
|
|||||||
b.Unlock()
|
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() {
|
func (b *Buffer) createDDParserAndFrameRateCalculator() {
|
||||||
if mime.IsMimeTypeSVCCapable(b.mime) || b.mime == mime.MimeTypeVP8 {
|
if mime.IsMimeTypeSVCCapable(b.mime) || b.mime == mime.MimeTypeVP8 {
|
||||||
frc := NewFrameRateCalculatorDD(b.clockRate, b.logger)
|
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
|
// process header extensions always as padding packets could be used for probing
|
||||||
b.processHeaderExtensions(rtpPacket, arrivalTime, isRTX)
|
b.processHeaderExtensions(rtpPacket, arrivalTime, isRTX)
|
||||||
|
|
||||||
|
isRestart := false
|
||||||
flowState := b.updateStreamState(rtpPacket, arrivalTime)
|
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
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -748,7 +782,7 @@ func (b *Buffer) calc(rawPkt []byte, rtpPacket *rtp.Packet, arrivalTime int64, i
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ep := b.getExtPacket(rtpPacket, arrivalTime, isBuffered, flowState)
|
ep := b.getExtPacket(rtpPacket, arrivalTime, isBuffered, isRestart, flowState)
|
||||||
if ep == nil {
|
if ep == nil {
|
||||||
return
|
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 := ExtPacketFactory.Get().(*ExtPacket)
|
||||||
*ep = ExtPacket{
|
*ep = ExtPacket{
|
||||||
Arrival: arrivalTime,
|
Arrival: arrivalTime,
|
||||||
@@ -933,6 +967,7 @@ func (b *Buffer) getExtPacket(rtpPacket *rtp.Packet, arrivalTime int64, isBuffer
|
|||||||
},
|
},
|
||||||
IsOutOfOrder: flowState.IsOutOfOrder,
|
IsOutOfOrder: flowState.IsOutOfOrder,
|
||||||
IsBuffered: isBuffered,
|
IsBuffered: isBuffered,
|
||||||
|
IsRestart: isRestart,
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(rtpPacket.Payload) == 0 {
|
if len(rtpPacket.Payload) == 0 {
|
||||||
|
|||||||
+15
-8
@@ -70,6 +70,7 @@ type TrackSender interface {
|
|||||||
) error
|
) error
|
||||||
Resync()
|
Resync()
|
||||||
SetReceiver(TrackReceiver)
|
SetReceiver(TrackReceiver)
|
||||||
|
ReceiverRestart()
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------
|
// -------------------------------------------------------------------
|
||||||
@@ -669,7 +670,7 @@ func (d *DownTrack) handleUpstreamCodecChange(mimeType string) {
|
|||||||
return
|
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
|
var codec webrtc.RTPCodecParameters
|
||||||
for _, c := range d.upstreamCodecs {
|
for _, c := range d.upstreamCodecs {
|
||||||
@@ -908,13 +909,7 @@ func (d *DownTrack) postKeyFrameRequestEvent() {
|
|||||||
|
|
||||||
func (d *DownTrack) keyFrameRequester() {
|
func (d *DownTrack) keyFrameRequester() {
|
||||||
getInterval := func() time.Duration {
|
getInterval := func() time.Duration {
|
||||||
interval := 2 * d.rtpStats.GetRtt()
|
interval := min(max(2*d.rtpStats.GetRtt(), keyFrameIntervalMin), keyFrameIntervalMax)
|
||||||
if interval < keyFrameIntervalMin {
|
|
||||||
interval = keyFrameIntervalMin
|
|
||||||
}
|
|
||||||
if interval > keyFrameIntervalMax {
|
|
||||||
interval = keyFrameIntervalMax
|
|
||||||
}
|
|
||||||
return time.Duration(interval) * time.Millisecond
|
return time.Duration(interval) * time.Millisecond
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1640,6 +1635,18 @@ func (d *DownTrack) Resync() {
|
|||||||
d.forwarder.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 {
|
func (d *DownTrack) CreateSourceDescriptionChunks() []rtcp.SourceDescriptionChunk {
|
||||||
transceiver := d.transceiver.Load()
|
transceiver := d.transceiver.Load()
|
||||||
if d.bindState.Load() != bindStateBound || transceiver == nil {
|
if d.bindState.Load() != bindStateBound || transceiver == nil {
|
||||||
|
|||||||
+22
-2
@@ -122,7 +122,7 @@ type TrackReceiver interface {
|
|||||||
DeleteDownTrack(participantID livekit.ParticipantID)
|
DeleteDownTrack(participantID livekit.ParticipantID)
|
||||||
GetDownTracks() []TrackSender
|
GetDownTracks() []TrackSender
|
||||||
|
|
||||||
DebugInfo() map[string]interface{}
|
DebugInfo() map[string]any
|
||||||
|
|
||||||
TrackInfo() *livekit.TrackInfo
|
TrackInfo() *livekit.TrackInfo
|
||||||
UpdateTrackInfo(ti *livekit.TrackInfo)
|
UpdateTrackInfo(ti *livekit.TrackInfo)
|
||||||
@@ -156,6 +156,7 @@ type REDTransformer interface {
|
|||||||
publisherSRData *livekit.RTCPSenderReportState,
|
publisherSRData *livekit.RTCPSenderReportState,
|
||||||
)
|
)
|
||||||
ResyncDownTracks()
|
ResyncDownTracks()
|
||||||
|
OnStreamRestart()
|
||||||
CanClose() bool
|
CanClose() bool
|
||||||
Close()
|
Close()
|
||||||
}
|
}
|
||||||
@@ -168,6 +169,7 @@ type WebRTCReceiver struct {
|
|||||||
|
|
||||||
pliThrottleConfig PLIThrottleConfig
|
pliThrottleConfig PLIThrottleConfig
|
||||||
audioConfig AudioConfig
|
audioConfig AudioConfig
|
||||||
|
enableRTPStreamRestartDetection bool
|
||||||
|
|
||||||
trackID livekit.TrackID
|
trackID livekit.TrackID
|
||||||
streamID string
|
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
|
// WithLoadBalanceThreshold enables parallelization of packet writes when downTracks exceeds threshold
|
||||||
// Value should be between 3 and 150.
|
// 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).
|
// 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,
|
Config: w.audioConfig.AudioLevelConfig,
|
||||||
})
|
})
|
||||||
buff.SetAudioLossProxying(w.audioConfig.EnableLossProxying)
|
buff.SetAudioLossProxying(w.audioConfig.EnableLossProxying)
|
||||||
|
buff.SetStreamRestartDetection(w.enableRTPStreamRestartDetection)
|
||||||
buff.OnRtcpFeedback(w.sendRTCP)
|
buff.OnRtcpFeedback(w.sendRTCP)
|
||||||
buff.OnRtcpSenderReport(func() {
|
buff.OnRtcpSenderReport(func() {
|
||||||
srData := buff.GetSenderReportData()
|
srData := buff.GetSenderReportData()
|
||||||
@@ -438,7 +448,6 @@ func (w *WebRTCReceiver) AddUpTrack(track TrackRemote, buff *buffer.Buffer) erro
|
|||||||
cb()
|
cb()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if w.Kind() == webrtc.RTPCodecTypeVideo && layer == 0 {
|
if w.Kind() == webrtc.RTPCodecTypeVideo && layer == 0 {
|
||||||
buff.OnCodecChange(w.handleCodecChange)
|
buff.OnCodecChange(w.handleCodecChange)
|
||||||
}
|
}
|
||||||
@@ -795,6 +804,17 @@ func (w *WebRTCReceiver) forwardRTP(layer int32, buff *buffer.Buffer) {
|
|||||||
}
|
}
|
||||||
dequeuedAt := mono.UnixNano()
|
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) {
|
if pkt.Packet.PayloadType != uint8(w.codec.PayloadType) {
|
||||||
// drop packets as we don't support codec fallback directly
|
// drop packets as we don't support codec fallback directly
|
||||||
w.logger.Debugw(
|
w.logger.Debugw(
|
||||||
|
|||||||
@@ -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 {
|
func (r *RedPrimaryReceiver) IsClosed() bool {
|
||||||
return r.closed.Load()
|
return r.closed.Load()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 {
|
func (r *RedReceiver) CanClose() bool {
|
||||||
return r.closed.Load() || r.downTrackSpreader.DownTrackCount() == 0
|
return r.closed.Load() || r.downTrackSpreader.DownTrackCount() == 0
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,12 +38,50 @@ const (
|
|||||||
cReportSlack = float64(60.0)
|
cReportSlack = float64(60.0)
|
||||||
|
|
||||||
cTSJumpTooHighFactor = float64(1.5)
|
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 {
|
type RTPFlowState struct {
|
||||||
IsNotHandled bool
|
UnhandledReason RTPFlowUnhandledReason
|
||||||
|
|
||||||
LossStartInclusive uint64
|
LossStartInclusive uint64
|
||||||
LossEndExclusive uint64
|
LossEndExclusive uint64
|
||||||
@@ -60,7 +98,7 @@ func (r *RTPFlowState) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
e.AddBool("IsNotHandled", r.IsNotHandled)
|
e.AddString("UnhandledReason", r.UnhandledReason.String())
|
||||||
e.AddUint64("LossStartInclusive", r.LossStartInclusive)
|
e.AddUint64("LossStartInclusive", r.LossStartInclusive)
|
||||||
e.AddUint64("LossEndExclusive", r.LossEndExclusive)
|
e.AddUint64("LossEndExclusive", r.LossEndExclusive)
|
||||||
e.AddBool("IsDuplicate", r.IsDuplicate)
|
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 {
|
type RTPStatsReceiver struct {
|
||||||
*rtpStatsBase
|
*rtpStatsBase
|
||||||
|
|
||||||
@@ -90,6 +141,13 @@ type RTPStatsReceiver struct {
|
|||||||
largeJumpCount int
|
largeJumpCount int
|
||||||
largeJumpNegativeCount int
|
largeJumpNegativeCount int
|
||||||
timeReversedCount int
|
timeReversedCount int
|
||||||
|
|
||||||
|
packetsDroppedPreStartTimestamp int
|
||||||
|
packetsDroppedOldTimestamp int
|
||||||
|
packetsDroppedPreStartSequenceNumber int
|
||||||
|
packetsDroppedOldSequenceNumber int
|
||||||
|
|
||||||
|
restartPackets []packet
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRTPStatsReceiver(params RTPStatsParams) *RTPStatsReceiver {
|
func NewRTPStatsReceiver(params RTPStatsParams) *RTPStatsReceiver {
|
||||||
@@ -137,7 +195,7 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
defer r.lock.Unlock()
|
defer r.lock.Unlock()
|
||||||
|
|
||||||
if r.endTime != 0 {
|
if r.endTime != 0 {
|
||||||
flowState.IsNotHandled = true
|
flowState.UnhandledReason = RTPFlowUnhandledReasonEnded
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +237,7 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
if !r.initialized {
|
if !r.initialized {
|
||||||
if payloadSize == 0 {
|
if payloadSize == 0 {
|
||||||
// do not start on a padding only packet
|
// do not start on a padding only packet
|
||||||
flowState.IsNotHandled = true
|
flowState.UnhandledReason = RTPFlowUnhandledReasonPaddingOnly
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -215,17 +273,28 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
if resTS.IsUnhandled {
|
if resTS.IsUnhandled {
|
||||||
undoUpdates()
|
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
|
return
|
||||||
}
|
}
|
||||||
gapTS = int64(resTS.ExtendedVal - resTS.PreExtendedHighest)
|
gapTS = int64(resTS.ExtendedVal - resTS.PreExtendedHighest)
|
||||||
|
|
||||||
|
if !resSN.IsUnhandled {
|
||||||
// it is possible to receive old packets in two different scenarios
|
// 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
|
// as it is not possible to detect how far to roll back, ignore old packets
|
||||||
//
|
//
|
||||||
// Case 1:
|
// Case 1:
|
||||||
// Very old time stamp, happens under the following conditions
|
// Very old time stamp, happens under the following conditions
|
||||||
// - resume after long mute, big time stamp jump
|
// - 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
|
// - 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
|
// 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.
|
// to before mute, but it appears like it has rolled over.
|
||||||
@@ -235,9 +304,16 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
if gapTS > int64(float64(expectedTSJump)*cTSJumpTooHighFactor) {
|
if gapTS > int64(float64(expectedTSJump)*cTSJumpTooHighFactor) {
|
||||||
undoUpdates()
|
undoUpdates()
|
||||||
|
|
||||||
logger().Warnw("dropping old packet, timestamp", nil)
|
r.packetsDroppedOldTimestamp++
|
||||||
|
logger().Warnw("dropping packet, old timestamp", nil)
|
||||||
|
|
||||||
flowState.IsNotHandled = true
|
if r.maybeRestart(sequenceNumber, timestamp, payloadSize) {
|
||||||
|
logger().Infow("potential restart")
|
||||||
|
r.resetRestart()
|
||||||
|
flowState.UnhandledReason = RTPFlowUnhandledReasonRestart
|
||||||
|
} else {
|
||||||
|
flowState.UnhandledReason = RTPFlowUnhandledReasonOldTimestamp
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -247,11 +323,20 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
if gapTS < 0 && gapSN > 0 {
|
if gapTS < 0 && gapSN > 0 {
|
||||||
undoUpdates()
|
undoUpdates()
|
||||||
|
|
||||||
logger().Warnw("dropping old packet, sequence number", 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
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// it is possible that sequence number has rolled over too
|
// it is possible that sequence number has rolled over too
|
||||||
if (gapSN < 0 || gapSN > (1<<15)) && gapTS > 0 && payloadSize > 0 {
|
if (gapSN < 0 || gapSN > (1<<15)) && gapTS > 0 && payloadSize > 0 {
|
||||||
@@ -270,9 +355,16 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
if resSN.IsUnhandled {
|
if resSN.IsUnhandled {
|
||||||
undoUpdates()
|
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
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -364,6 +456,7 @@ func (r *RTPStatsReceiver) Update(
|
|||||||
r.updateJitter(resTS.ExtendedVal, packetTime)
|
r.updateJitter(resTS.ExtendedVal, packetTime)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
r.resetRestart()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -605,15 +698,9 @@ func (r *RTPStatsReceiver) GetRtcpReceptionReport(ssrc uint32, proxyFracLost uin
|
|||||||
packetsLost = 0
|
packetsLost = 0
|
||||||
}
|
}
|
||||||
lossRate := float32(packetsLost) / float32(packetsExpected)
|
lossRate := float32(packetsLost) / float32(packetsExpected)
|
||||||
fracLost := uint8(lossRate * 256.0)
|
fracLost := max(proxyFracLost, uint8(lossRate*256.0))
|
||||||
if proxyFracLost > fracLost {
|
|
||||||
fracLost = proxyFracLost
|
|
||||||
}
|
|
||||||
|
|
||||||
totalLost := r.packetsLost
|
totalLost := min(r.packetsLost, 0xffffff) // 24-bits max
|
||||||
if totalLost > 0xffffff { // 24-bits max
|
|
||||||
totalLost = 0xffffff
|
|
||||||
}
|
|
||||||
|
|
||||||
lastSR := uint32(0)
|
lastSR := uint32(0)
|
||||||
dlsr := uint32(0)
|
dlsr := uint32(0)
|
||||||
@@ -707,6 +794,31 @@ func (r *RTPStatsReceiver) ExtendedHighestSequenceNumber() uint64 {
|
|||||||
return r.sequenceNumber.GetExtendedHighest()
|
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 {
|
type lockedRTPStatsReceiverLogEncoder struct {
|
||||||
@@ -736,6 +848,20 @@ func (r lockedRTPStatsReceiverLogEncoder) MarshalLogObject(e zapcore.ObjectEncod
|
|||||||
e.AddUint64("extHighestTS", extHighestTS)
|
e.AddUint64("extHighestTS", extHighestTS)
|
||||||
|
|
||||||
e.AddObject("propagationDelayEstimator", r.propagationDelayEstimator)
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ func Test_RTPStatsReceiver_Update(t *testing.T) {
|
|||||||
len(packet.Payload),
|
len(packet.Payload),
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
require.True(t, flowState.IsNotHandled)
|
require.Equal(t, RTPFlowUnhandledReasonPreStartTimestamp, flowState.UnhandledReason)
|
||||||
require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest())
|
require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest())
|
||||||
require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest()))
|
require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest()))
|
||||||
require.Equal(t, timestamp, r.timestamp.GetHighest())
|
require.Equal(t, timestamp, r.timestamp.GetHighest())
|
||||||
@@ -108,7 +108,7 @@ func Test_RTPStatsReceiver_Update(t *testing.T) {
|
|||||||
len(packet.Payload),
|
len(packet.Payload),
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
require.True(t, flowState.IsNotHandled)
|
require.Equal(t, RTPFlowUnhandledReasonPreStartTimestamp, flowState.UnhandledReason)
|
||||||
require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest())
|
require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest())
|
||||||
require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest()))
|
require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest()))
|
||||||
require.Equal(t, timestamp, r.timestamp.GetHighest())
|
require.Equal(t, timestamp, r.timestamp.GetHighest())
|
||||||
@@ -218,7 +218,7 @@ func Test_RTPStatsReceiver_Update(t *testing.T) {
|
|||||||
len(packet.Payload),
|
len(packet.Payload),
|
||||||
0,
|
0,
|
||||||
)
|
)
|
||||||
require.True(t, flowState.IsNotHandled)
|
require.Equal(t, RTPFlowUnhandledReasonOldSequenceNumber, flowState.UnhandledReason)
|
||||||
require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest())
|
require.Equal(t, sequenceNumber, r.sequenceNumber.GetHighest())
|
||||||
require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest()))
|
require.Equal(t, sequenceNumber, uint16(r.sequenceNumber.GetExtendedHighest()))
|
||||||
require.Equal(t, timestamp, r.timestamp.GetHighest())
|
require.Equal(t, timestamp, r.timestamp.GetHighest())
|
||||||
@@ -226,3 +226,33 @@ func Test_RTPStatsReceiver_Update(t *testing.T) {
|
|||||||
|
|
||||||
r.Stop()
|
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()
|
||||||
|
}
|
||||||
|
|||||||
@@ -80,10 +80,7 @@ func (r *RangeMap[RT, VT]) MarshalLogObject(e zapcore.ObjectEncoder) error {
|
|||||||
e.AddInt("numRanges", len(r.ranges))
|
e.AddInt("numRanges", len(r.ranges))
|
||||||
|
|
||||||
// just the last 10 ranges max
|
// just the last 10 ranges max
|
||||||
startIdx := len(r.ranges) - 10
|
startIdx := max(len(r.ranges)-10, 0)
|
||||||
if startIdx < 0 {
|
|
||||||
startIdx = 0
|
|
||||||
}
|
|
||||||
for i := startIdx; i < len(r.ranges); i++ {
|
for i := startIdx; i < len(r.ranges); i++ {
|
||||||
e.AddObject(fmt.Sprintf("range[%d]", i), r.ranges[i])
|
e.AddObject(fmt.Sprintf("range[%d]", i), r.ranges[i])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ func (oq *opsQueueBase[T]) Enqueue(op T) {
|
|||||||
select {
|
select {
|
||||||
case oq.wake <- struct{}{}:
|
case oq.wake <- struct{}{}:
|
||||||
default:
|
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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user