diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index a9ce35dde..63b93f3a4 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -284,6 +284,8 @@ type DownTrack struct { fecProtection flexfec.Protection fecNotifiedOverhead atomic.Uint32 fecState flexfec.EncoderState + // loss samples for adaptive protection, accessed only from the RTCP handler + fecLoss flexfec.LossAggregator receiverLock sync.RWMutex receiver TrackReceiver @@ -2147,7 +2149,9 @@ func (d *DownTrack) handleRTCP(bytes []byte) { if isRttChanged { rttToReport = rtt } - d.onFECReceiverReport(r.FractionLost, d.rtpStats.GetRtt()) + if fractionLost, ok := d.fecLoss.Update(r.LastSequenceNumber, r.TotalLost); ok { + d.onFECReceiverReport(fractionLost, d.rtpStats.GetRtt()) + } if d.playoutDelay != nil { d.playoutDelay.OnSeqAcked(uint16(r.LastSequenceNumber)) diff --git a/pkg/sfu/downtrack_fec.go b/pkg/sfu/downtrack_fec.go index db0d540c0..5ec42ba01 100644 --- a/pkg/sfu/downtrack_fec.go +++ b/pkg/sfu/downtrack_fec.go @@ -171,8 +171,9 @@ func (d *DownTrack) SetFECProtection(fec *livekit.FECProtection) { } } -// onFECReceiverReport feeds a reception report of the media SSRC to adaptive -// and minimum protection, and lets the allocator reserve a changed overhead. +// onFECReceiverReport feeds a loss sample aggregated from reception reports +// of the media SSRC to adaptive and minimum protection, and lets the allocator +// reserve a changed overhead. func (d *DownTrack) onFECReceiverReport(fractionLost uint8, rttMs uint32) { encoder := d.fecEncoder.Load() if encoder == nil { diff --git a/pkg/sfu/flexfec/loss_aggregator.go b/pkg/sfu/flexfec/loss_aggregator.go new file mode 100644 index 000000000..2aaa12650 --- /dev/null +++ b/pkg/sfu/flexfec/loss_aggregator.go @@ -0,0 +1,79 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package flexfec + +// Minimum number of expected packets a loss sample covers (kLimitNumPackets in +// libwebrtc's SendSideBandwidthEstimation). +const minLossSamplePackets = 20 + +// Larger jumps of the extended highest sequence number are treated as a +// stream reset rather than as packets sent. +const maxLossSampleSequenceJump = 1 << 15 + +// LossAggregator turns RTCP reception reports into loss samples for adaptive +// protection, like libwebrtc's SendSideBandwidthEstimation::UpdatePacketsLost. +// +// A receiver can send a report every few packets, for example with each NACK, +// and the fraction lost of such a report is very noisy: one lost packet out of +// four reads as 25%. Fed straight into the max-window loss filter, those +// samples overestimate the loss several times. The aggregator instead derives +// the expected and lost packets from the cumulative counters and produces a +// sample only once it covers at least minLossSamplePackets expected packets. +// +// It is not safe for concurrent use. +type LossAggregator struct { + initialized bool + highestSeq uint32 + totalLost uint32 + expected int64 + lost int64 +} + +// Update accounts a reception report, given its extended highest sequence +// number and its cumulative number of packets lost. It returns the Q8 loss +// fraction of the packets expected since the previous sample, and false while +// too few packets are expected to produce one. +func (a *LossAggregator) Update(highestSeq uint32, totalLost uint32) (uint8, bool) { + if !a.initialized { + a.reset(highestSeq, totalLost) + return 0, false + } + + expected := int64(int32(highestSeq - a.highestSeq)) + if expected < 0 || expected > maxLossSampleSequenceJump { + a.reset(highestSeq, totalLost) + return 0, false + } + // The cumulative number of packets lost is a signed 24-bit value. + lost := int64(int32((totalLost-a.totalLost)<<8) >> 8) + a.highestSeq = highestSeq + a.totalLost = totalLost + + a.expected += expected + // Duplicates can make the cumulative loss decrease. + a.lost = max(a.lost+lost, 0) + if a.expected < minLossSamplePackets { + return 0, false + } + + fraction := min(min(a.lost, a.expected)<<8/a.expected, 255) + a.expected = 0 + a.lost = 0 + return uint8(fraction), true +} + +func (a *LossAggregator) reset(highestSeq uint32, totalLost uint32) { + *a = LossAggregator{initialized: true, highestSeq: highestSeq, totalLost: totalLost} +} diff --git a/pkg/sfu/flexfec/loss_aggregator_test.go b/pkg/sfu/flexfec/loss_aggregator_test.go new file mode 100644 index 000000000..77cf249be --- /dev/null +++ b/pkg/sfu/flexfec/loss_aggregator_test.go @@ -0,0 +1,76 @@ +// Copyright 2026 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package flexfec + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestLossAggregatorWaitsForEnoughPackets(t *testing.T) { + var a LossAggregator + _, ok := a.Update(1000, 0) + require.False(t, ok, "the first report only sets the baseline") + + // Frequent reports of 4 packets with 1 lost each read as 25% loss on + // their own; aggregated, every fourth packet over 20 packets is 25% too, + // but a single loss in 20 packets is 5%, not 25%. + _, ok = a.Update(1004, 1) + require.False(t, ok) + for seq := uint32(1008); seq < 1020; seq += 4 { + _, ok = a.Update(seq, 1) + require.False(t, ok) + } + fraction, ok := a.Update(1020, 1) + require.True(t, ok) + require.EqualValues(t, 1<<8/20, fraction) + + // The next sample starts from scratch. + _, ok = a.Update(1030, 3) + require.False(t, ok) + fraction, ok = a.Update(1040, 5) + require.True(t, ok) + require.EqualValues(t, 4<<8/20, fraction) +} + +func TestLossAggregatorHandlesCounterEdgeCases(t *testing.T) { + var a LossAggregator + a.Update(0xffff_fff0, 0xff_fffe) // cumulative loss -2 as signed 24-bit + + // Sequence wrap and signed 24-bit cumulative loss wrap. + fraction, ok := a.Update(0x0000_0004, 0x00_0003) + require.True(t, ok) + require.EqualValues(t, 5<<8/20, fraction) + + // Duplicates decrease the cumulative loss; it never goes below zero. + fraction, ok = a.Update(0x0000_0018, 0x00_0001) + require.True(t, ok) + require.EqualValues(t, 0, fraction) + + // Loss above the expected packets is capped. + fraction, ok = a.Update(0x0000_002c, 0x00_0040) + require.True(t, ok) + require.EqualValues(t, 255, fraction) + + // A large jump or a step back resets the baseline. + _, ok = a.Update(0x0001_0000, 0x00_0040) + require.False(t, ok) + _, ok = a.Update(0x0000_ff00, 0x00_0040) + require.False(t, ok) + fraction, ok = a.Update(0x0000_ff14, 0x00_0042) + require.True(t, ok) + require.EqualValues(t, 2<<8/20, fraction) +} diff --git a/test/flexfec_downstream_test.go b/test/flexfec_downstream_test.go index 2ed5ae2e3..4a7d26985 100644 --- a/test/flexfec_downstream_test.go +++ b/test/flexfec_downstream_test.go @@ -128,6 +128,10 @@ type fecLossRecorder struct { fecPackets int // highest media sequence number seen, including dropped packets highestSeq uint16 + // sequence number cycles and media packets dropped since the start, + // for the cumulative counters of receiver reports + seqCycles uint32 + totalLost uint32 } func newFECLossRecorder() *fecLossRecorder { @@ -193,11 +197,15 @@ func (r *fecLossRecorder) filter(pkt *rtp.Packet) bool { return true } if r.mediaPackets == 0 || int16(pkt.SequenceNumber-r.highestSeq) > 0 { + if pkt.SequenceNumber < r.highestSeq { + r.seqCycles++ + } r.highestSeq = pkt.SequenceNumber } r.mediaPackets++ if r.dropEvery > 0 && r.mediaPackets%r.dropEvery == 0 { r.dropped[pkt.SequenceNumber] = raw + r.totalLost++ return false } r.received[pkt.SequenceNumber] = raw @@ -241,9 +249,10 @@ func (r *fecLossRecorder) result() fecWindowResult { return res } -// receiverReport reports the simulated loss pattern for the media SSRC. The -// test client does not send receiver reports itself, so the test reports what -// a receiver would see, as input for adaptive protection. +// receiverReport reports the simulated loss for the media SSRC. The test +// client does not send receiver reports itself, so the test reports what a +// receiver would see, as input for adaptive protection. The SFU derives loss +// from the cumulative counters, so they must reflect the dropped packets. func (r *fecLossRecorder) receiverReport() *rtcp.ReceiverReport { r.mu.Lock() defer r.mu.Unlock() @@ -258,7 +267,8 @@ func (r *fecLossRecorder) receiverReport() *rtcp.ReceiverReport { Reports: []rtcp.ReceptionReport{{ SSRC: r.mediaSSRC, FractionLost: fractionLost, - LastSequenceNumber: uint32(r.highestSeq), + TotalLost: r.totalLost, + LastSequenceNumber: r.seqCycles<<16 | uint32(r.highestSeq), }}, } }