diff --git a/config-sample.yaml b/config-sample.yaml index d2eccbf96..e1b30f1ba 100644 --- a/config-sample.yaml +++ b/config-sample.yaml @@ -140,10 +140,16 @@ rtc: # flexfec: # upstream_enabled: false # # Allow repairs for subscribers that negotiate FlexFEC. Clients select fec - # # per track in UpdateTrackSettings: FEC_NONE (default), FEC_LOW (15%), - # # FEC_MEDIUM (25%), or FEC_HIGH (35%) repair packet overhead, matching publish - # # track presets. These are approximate: each protected frame/block gets at - # # least one repair, so small frames can exceed the nominal percentage. + # # per track in UpdateTrackSettings with a mode and a level: + # # - FEC_MODE_DISABLED (default): no repairs + # # - FEC_MODE_ADAPTIVE: follows the subscriber's reported loss and RTT like + # # libwebrtc's hybrid NACK/FEC (no delta frame repairs below 20ms RTT) + # # - FEC_MODE_FIXED: the level's repair packet overhead + # # - FEC_MODE_MINIMUM: at least the level, rising adaptively with loss + # # Levels are FEC_LEVEL_LOW (15%, also the default), FEC_LEVEL_MEDIUM (25%) + # # or FEC_LEVEL_HIGH (35%), matching publish track presets. These are + # # approximate: each protected frame/block gets at least one repair, so + # # small frames can exceed the nominal percentage. # # Media is sent immediately; repairs follow the end of each frame, with # # large frames split into blocks of at most 48 packets. Stale partial frames # # spanning more than 200ms and packets without room for repair headers are skipped. diff --git a/pkg/rtc/signalling/signalhandler_fec_test.go b/pkg/rtc/signalling/signalhandler_fec_test.go index 5fe755150..be2e9825a 100644 --- a/pkg/rtc/signalling/signalhandler_fec_test.go +++ b/pkg/rtc/signalling/signalhandler_fec_test.go @@ -25,7 +25,13 @@ import ( ) func TestSignalTrackFECProtection(t *testing.T) { - for _, level := range []*livekit.FECProtection{nil, livekit.FECProtection_FEC_NONE.Enum(), livekit.FECProtection_FEC_LOW.Enum(), livekit.FECProtection_FEC_MEDIUM.Enum(), livekit.FECProtection_FEC_HIGH.Enum()} { + for _, level := range []*livekit.FECProtection{ + nil, + {}, + {Mode: livekit.FECProtectionMode_FEC_MODE_ADAPTIVE}, + {Mode: livekit.FECProtectionMode_FEC_MODE_FIXED, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, + {Mode: livekit.FECProtectionMode_FEC_MODE_MINIMUM, Level: livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM}, + } { participant := &typesfakes.FakeLocalParticipant{} handler := NewSignalHandler(SignalHandlerParams{Participant: participant, Logger: logger.GetLogger()}) signal := &livekit.SignalRequest{Message: &livekit.SignalRequest_TrackSetting{TrackSetting: &livekit.UpdateTrackSettings{ @@ -40,7 +46,7 @@ func TestSignalTrackFECProtection(t *testing.T) { for i, sid := range []livekit.TrackID{"track-a", "track-b"} { actualSID, settings := participant.UpdateSubscribedTrackSettingsArgsForCall(i) require.Equal(t, sid, actualSID) - require.Equal(t, level, settings.Fec) + require.True(t, proto.Equal(level, settings.Fec)) } } } diff --git a/pkg/rtc/subscribedtrack.go b/pkg/rtc/subscribedtrack.go index ca7c63726..a22a3de4e 100644 --- a/pkg/rtc/subscribedtrack.go +++ b/pkg/rtc/subscribedtrack.go @@ -386,7 +386,7 @@ func (t *SubscribedTrack) applySettings() { t.logger.Debugw("applying subscriber track settings", "settings", logger.Proto(settings)) if settings.Fec != nil { - dt.SetFECProtection(*settings.Fec) + dt.SetFECProtection(settings.Fec) } if settings.Disabled { dt.Mute(true) diff --git a/pkg/rtc/subscribedtrack_fec.go b/pkg/rtc/subscribedtrack_fec.go index bc4c2574b..4dfff25de 100644 --- a/pkg/rtc/subscribedtrack_fec.go +++ b/pkg/rtc/subscribedtrack_fec.go @@ -19,23 +19,22 @@ import ( "github.com/livekit/protocol/utils" ) -// mergeSubscriberSettings retains an explicitly requested FEC level across -// legacy clients' quality/mute updates, which omit the new optional field. Clone +// mergeSubscriberSettings retains the FEC protection across updates that omit +// the optional field, such as legacy clients' quality/mute updates, and +// normalizes unknown modes to disabled and unknown levels to unspecified. Clone // both the incoming message and inherited value so cached settings are immutable. func mergeSubscriberSettings(previous, next *livekit.UpdateTrackSettings) *livekit.UpdateTrackSettings { settings := utils.CloneProto(next) - fec := settings.Fec - if fec == nil && previous != nil { - fec = previous.Fec + if settings.Fec == nil && previous.GetFec() != nil { + settings.Fec = utils.CloneProto(previous.Fec) } - if fec != nil { - level := *fec - switch level { - case livekit.FECProtection_FEC_NONE, livekit.FECProtection_FEC_LOW, livekit.FECProtection_FEC_MEDIUM, livekit.FECProtection_FEC_HIGH: - default: - level = livekit.FECProtection_FEC_NONE + if fec := settings.Fec; fec != nil { + if _, ok := livekit.FECProtectionMode_name[int32(fec.Mode)]; !ok { + fec.Mode = livekit.FECProtectionMode_FEC_MODE_DISABLED + } + if _, ok := livekit.FECProtectionLevel_name[int32(fec.Level)]; !ok { + fec.Level = livekit.FECProtectionLevel_FEC_LEVEL_UNSPECIFIED } - settings.Fec = level.Enum() } return settings } diff --git a/pkg/rtc/subscribedtrack_fec_test.go b/pkg/rtc/subscribedtrack_fec_test.go index 3ad390518..0a2d4ed81 100644 --- a/pkg/rtc/subscribedtrack_fec_test.go +++ b/pkg/rtc/subscribedtrack_fec_test.go @@ -20,6 +20,7 @@ import ( "github.com/pion/webrtc/v4" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" "github.com/livekit/protocol/codecs/mime" "github.com/livekit/protocol/livekit" @@ -32,54 +33,73 @@ import ( "github.com/livekit/livekit-server/pkg/sfu/sfufakes" ) +func fecDisabled() *livekit.FECProtection { + return &livekit.FECProtection{} +} + +func fecFixed(level livekit.FECProtectionLevel) *livekit.FECProtection { + return &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_FIXED, Level: level} +} + func TestSubscriberFECSettings(t *testing.T) { require.Nil(t, mergeSubscriberSettings(nil, &livekit.UpdateTrackSettings{}).Fec) for _, tc := range []struct { - requested, want livekit.FECProtection + requested, want *livekit.FECProtection }{ - {livekit.FECProtection_FEC_NONE, livekit.FECProtection_FEC_NONE}, - {livekit.FECProtection_FEC_LOW, livekit.FECProtection_FEC_LOW}, - {livekit.FECProtection_FEC_MEDIUM, livekit.FECProtection_FEC_MEDIUM}, - {livekit.FECProtection_FEC_HIGH, livekit.FECProtection_FEC_HIGH}, - {-1, livekit.FECProtection_FEC_NONE}, - {99, livekit.FECProtection_FEC_NONE}, + {fecDisabled(), fecDisabled()}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW)}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM)}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH)}, + { + &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_ADAPTIVE}, + &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_ADAPTIVE}, + }, + { + &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_MINIMUM, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, + &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_MINIMUM, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, + }, + // unknown modes disable FEC, unknown levels are unspecified + {&livekit.FECProtection{Mode: -1, Level: livekit.FECProtectionLevel_FEC_LEVEL_LOW}, &livekit.FECProtection{Level: livekit.FECProtectionLevel_FEC_LEVEL_LOW}}, + {&livekit.FECProtection{Mode: 99}, fecDisabled()}, + {fecFixed(99), fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_UNSPECIFIED)}, } { - requested := &livekit.UpdateTrackSettings{Fec: tc.requested.Enum()} + requested := &livekit.UpdateTrackSettings{Fec: tc.requested} + original := utils.CloneProto(tc.requested) cached := mergeSubscriberSettings(nil, requested) require.NotNil(t, cached.Fec) - require.Equal(t, tc.want, *cached.Fec) - require.Equal(t, tc.requested, *requested.Fec, "do not change caller-owned messages") + require.True(t, proto.Equal(tc.want, cached.Fec), "got %v, want %v", cached.Fec, tc.want) + require.True(t, proto.Equal(original, requested.Fec), "do not change caller-owned messages") legacyUpdate := &livekit.UpdateTrackSettings{Disabled: true, Width: 640} merged := mergeSubscriberSettings(cached, legacyUpdate) require.True(t, merged.Disabled) require.EqualValues(t, 640, merged.Width) - require.Equal(t, cached.Fec, merged.Fec) + require.True(t, proto.Equal(cached.Fec, merged.Fec)) require.Nil(t, legacyUpdate.Fec) - *merged.Fec = 42 - require.Equal(t, tc.want, *cached.Fec, "cached option must not alias later settings") + merged.Fec.Level = 42 + require.True(t, proto.Equal(tc.want, cached.Fec), "cached option must not alias later settings") } } func TestSubscriberFECPersistsAcrossResubscription(t *testing.T) { sub := newMediaTrackSubscription("subscriber", "track", logger.GetLogger()) - sub.setSettings(&livekit.UpdateTrackSettings{Fec: livekit.FECProtection_FEC_MEDIUM.Enum()}) + sub.setSettings(&livekit.UpdateTrackSettings{Fec: fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM)}) first := &typesfakes.FakeSubscribedTrack{} sub.setSubscribedTrack(first) got, immediate := first.UpdateSubscriberSettingsArgsForCall(0) - require.Equal(t, livekit.FECProtection_FEC_MEDIUM, *got.Fec) + require.True(t, proto.Equal(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), got.Fec)) require.True(t, immediate) sub.setSettings(&livekit.UpdateTrackSettings{Width: 640, Height: 360}) got, immediate = first.UpdateSubscriberSettingsArgsForCall(1) - require.Equal(t, livekit.FECProtection_FEC_MEDIUM, *got.Fec) + require.True(t, proto.Equal(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), got.Fec)) require.False(t, immediate) - sub.setSettings(&livekit.UpdateTrackSettings{Fec: livekit.FECProtection_FEC_NONE.Enum()}) + sub.setSettings(&livekit.UpdateTrackSettings{Fec: fecDisabled()}) sub.setSettings(&livekit.UpdateTrackSettings{Quality: livekit.VideoQuality_HIGH}) sub.setSubscribedTrack(nil) second := &typesfakes.FakeSubscribedTrack{} sub.setSubscribedTrack(second) got, immediate = second.UpdateSubscriberSettingsArgsForCall(0) require.NotNil(t, got.Fec) - require.Zero(t, *got.Fec, "explicit off must survive resubscription and quality updates") + require.True(t, proto.Equal(fecDisabled(), got.Fec), "explicit off must survive resubscription and quality updates") require.True(t, immediate) } @@ -91,13 +111,16 @@ func TestSubscriberFECAppliesToDownTrack(t *testing.T) { want int64 }{ {nil, 100_000}, - {livekit.FECProtection_FEC_MEDIUM.Enum(), 125_000}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), 125_000}, {nil, 125_000}, - {livekit.FECProtection_FEC_NONE.Enum(), 100_000}, + {fecDisabled(), 100_000}, {nil, 100_000}, - {livekit.FECProtection_FEC_LOW.Enum(), 115_000}, - {livekit.FECProtection_FEC_HIGH.Enum(), 135_000}, - {livekit.FECProtection(99).Enum(), 100_000}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), 115_000}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 135_000}, + {&livekit.FECProtection{Mode: 99, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, 100_000}, + {&livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_MINIMUM}, 115_000}, + {nil, 115_000}, + {&livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_ADAPTIVE}, 100_000}, } { sub.UpdateSubscriberSettings(&livekit.UpdateTrackSettings{Quality: livekit.VideoQuality_HIGH, Fec: tc.level}, true) dt.AllocateOptimal(false, false) @@ -114,13 +137,13 @@ func TestSubscriberFECSettingsSupersededDuringApply(t *testing.T) { // A settings update can arrive while layer selection runs without settingsLock. sub.UpdateSubscriberSettings(&livekit.UpdateTrackSettings{ Quality: livekit.VideoQuality_HIGH, - Fec: livekit.FECProtection_FEC_HIGH.Enum(), + Fec: fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), }, false) return livekit.VideoQuality_HIGH }) sub.UpdateSubscriberSettings(&livekit.UpdateTrackSettings{ Width: 640, - Fec: livekit.FECProtection_FEC_MEDIUM.Enum(), + Fec: fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), }, true) dt := sub.DownTrack() dt.AllocateOptimal(false, false) @@ -139,7 +162,7 @@ func TestSubscriberFECConcurrentSettings(t *testing.T) { for range 100 { sub.UpdateSubscriberSettings(&livekit.UpdateTrackSettings{ Width: 640, - Fec: livekit.FECProtection(level).Enum(), + Fec: &livekit.FECProtection{Mode: livekit.FECProtectionMode(level), Level: livekit.FECProtectionLevel(level)}, }, true) } }) diff --git a/pkg/sfu/downtrack.go b/pkg/sfu/downtrack.go index eb4aab6d7..a9ce35dde 100644 --- a/pkg/sfu/downtrack.go +++ b/pkg/sfu/downtrack.go @@ -279,11 +279,11 @@ type DownTrack struct { rtxSequenceNumber atomic.Uint64 rtxBudget *rtxBudget - fecLock sync.Mutex - fecEncoder atomic.Pointer[flexfec.Encoder] - fecProtectionPercent atomic.Uint32 - fecNotifiedOverhead atomic.Uint32 - fecState flexfec.EncoderState + fecLock sync.Mutex + fecEncoder atomic.Pointer[flexfec.Encoder] + fecProtection flexfec.Protection + fecNotifiedOverhead atomic.Uint32 + fecState flexfec.EncoderState receiverLock sync.RWMutex receiver TrackReceiver @@ -398,7 +398,6 @@ func NewDownTrack(params DownTrackParams) (*DownTrack, error) { receiver: params.Receiver, rtxBudget: newRTXBudget(params.RTXBudget.forKind(kind)), } - d.fecProtectionPercent.Store(flexfec.DefaultProtectionPercent) d.lastUnmutedAt.Store(time.Now()) d.codec.Store(codec) @@ -1115,6 +1114,7 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 { HeaderPool: RTPHeaderFactory, Payload: payload, FEC: d.fecEncoder.Load(), + IsKeyFrame: extPkt.IsKeyFrame, ProbeClusterId: ccutils.ProbeClusterId(d.probeClusterId.Load()), AbsSendTimeExtID: uint8(d.absSendTimeExtID), TransportWideExtID: uint8(d.transportWideExtID), @@ -2147,6 +2147,7 @@ func (d *DownTrack) handleRTCP(bytes []byte) { if isRttChanged { rttToReport = rtt } + d.onFECReceiverReport(r.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 b545df9e1..db0d540c0 100644 --- a/pkg/sfu/downtrack_fec.go +++ b/pkg/sfu/downtrack_fec.go @@ -16,11 +16,13 @@ package sfu import ( "strings" + "time" "github.com/pion/webrtc/v4" "github.com/livekit/protocol/livekit" + "github.com/livekit/livekit-server/pkg/sfu/buffer" "github.com/livekit/livekit-server/pkg/sfu/flexfec" ) @@ -37,7 +39,7 @@ func (d *DownTrack) bindFEC(t webrtc.TrackLocalContext) { if strings.EqualFold(codec.MimeType, webrtc.MimeTypeFlexFEC03) { encoder := flexfec.NewEncoder(uint8(codec.PayloadType), uint32(t.SSRCForwardErrorCorrection()), d.onFECSent) encoder.SeedState(d.fecState) - encoder.SetProtectionPercent(d.fecProtectionPercent.Load()) + encoder.SetProtection(d.fecProtection) d.fecNotifiedOverhead.Store(encoder.OverheadPercent()) d.fecEncoder.Store(encoder) return @@ -113,30 +115,53 @@ func (d *DownTrack) getLayeredBitrateWithFEC() ([]int32, Bitrates) { return layers, bitrates } -// SetFECProtection updates a subscriber's video FEC preset, using the same -// 0/15/25/35 percent levels as the publish-track options. Unknown levels disable FEC. +// Repair-to-media packet ratios of the protection levels, matching the +// publish-track options. FEC_LEVEL_UNSPECIFIED is the server default, low. +var fecLevelPercent = map[livekit.FECProtectionLevel]uint32{ + livekit.FECProtectionLevel_FEC_LEVEL_UNSPECIFIED: 15, + livekit.FECProtectionLevel_FEC_LEVEL_LOW: 15, + livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM: 25, + livekit.FECProtectionLevel_FEC_LEVEL_HIGH: 35, +} + +// fecProtectionFromProto maps a subscriber's setting to encoder protection. +// nil and unknown modes disable FEC; unknown levels are treated as unspecified. +func fecProtectionFromProto(fec *livekit.FECProtection) flexfec.Protection { + var mode flexfec.ProtectionMode + switch fec.GetMode() { + case livekit.FECProtectionMode_FEC_MODE_ADAPTIVE: + return flexfec.Protection{Mode: flexfec.ProtectionAdaptive} + case livekit.FECProtectionMode_FEC_MODE_FIXED: + mode = flexfec.ProtectionFixed + case livekit.FECProtectionMode_FEC_MODE_MINIMUM: + mode = flexfec.ProtectionMinimum + default: + return flexfec.Protection{} + } + percent, ok := fecLevelPercent[fec.GetLevel()] + if !ok { + percent = fecLevelPercent[livekit.FECProtectionLevel_FEC_LEVEL_UNSPECIFIED] + } + return flexfec.Protection{Mode: mode, Factor: flexfec.ProtectionFactorFromPercent(percent)} +} + +// SetFECProtection updates a subscriber's video FEC protection. Fixed and +// minimum levels use the same 15/25/35 percent ratios as the publish-track +// options; adaptive protection follows receiver reports like libwebrtc. // It can run before Bind and never enables FEC unless it was negotiated and // permitted by the server. Changes take effect without SDP renegotiation. -func (d *DownTrack) SetFECProtection(level livekit.FECProtection) { - var percent uint32 - switch level { - case livekit.FECProtection_FEC_LOW: - percent = 15 - case livekit.FECProtection_FEC_MEDIUM: - percent = 25 - case livekit.FECProtection_FEC_HIGH: - percent = 35 - } +func (d *DownTrack) SetFECProtection(fec *livekit.FECProtection) { + protection := fecProtectionFromProto(fec) d.fecLock.Lock() - previous := d.fecProtectionPercent.Swap(percent) - if previous == percent { + if d.fecProtection == protection { d.fecLock.Unlock() return } + d.fecProtection = protection encoder := d.fecEncoder.Load() if encoder != nil { - encoder.SetProtectionPercent(percent) - d.fecNotifiedOverhead.Store(percent) + encoder.SetProtection(protection) + d.fecNotifiedOverhead.Store(encoder.OverheadPercent()) } d.fecLock.Unlock() if encoder != nil { @@ -145,3 +170,43 @@ func (d *DownTrack) SetFECProtection(level livekit.FECProtection) { } } } + +// onFECReceiverReport feeds a reception report 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 { + return + } + width, height := d.getForwardedVideoDimensions() + encoder.OnReceiverReport(flexfec.NetworkStats{ + FractionLost: fractionLost, + RTT: time.Duration(rttMs) * time.Millisecond, + Width: width, + Height: height, + }) + percent := encoder.OverheadPercent() + if d.fecNotifiedOverhead.Swap(percent) != percent { + if listener := d.getStreamAllocatorListener(); listener != nil { + listener.OnSubscriptionChanged(d) + } + } +} + +// getForwardedVideoDimensions returns the published dimensions of the layer +// currently forwarded, or zeros when they are unknown. +func (d *DownTrack) getForwardedVideoDimensions() (uint32, uint32) { + spatial := d.forwarder.CurrentLayer().Spatial + if spatial < 0 { + return 0, 0 + } + mimeType := d.Mime() + trackInfo := d.Receiver().TrackInfo() + quality := buffer.SpatialLayerToVideoQuality(mimeType, spatial, trackInfo) + for _, layer := range buffer.GetVideoLayersForMimeType(mimeType, trackInfo) { + if layer.GetQuality() == quality { + return layer.GetWidth(), layer.GetHeight() + } + } + return 0, 0 +} diff --git a/pkg/sfu/downtrack_fec_integration_test.go b/pkg/sfu/downtrack_fec_integration_test.go index 0301030c0..10c197a7b 100644 --- a/pkg/sfu/downtrack_fec_integration_test.go +++ b/pkg/sfu/downtrack_fec_integration_test.go @@ -70,6 +70,14 @@ func (c *fecWireCapture) Write(raw []byte) (int, error) { return c.ReadWriteCloser.Write(raw) } +func fecDisabled() *livekit.FECProtection { + return &livekit.FECProtection{} +} + +func fecFixed(level livekit.FECProtectionLevel) *livekit.FECProtection { + return &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_FIXED, Level: level} +} + func TestDownTrackFlexFECOnWire(t *testing.T) { for _, tc := range []struct { name string @@ -79,18 +87,18 @@ func TestDownTrackFlexFECOnWire(t *testing.T) { protectionPercent uint32 framePackets, frameRepairs int }{ - {"pass through", true, true, false, "pass", livekit.FECProtection_FEC_MEDIUM.Enum(), 25, 20, 5}, - {"queued", true, true, false, "queue", livekit.FECProtection_FEC_MEDIUM.Enum(), 25, 20, 5}, - {"low", true, true, false, "queue", livekit.FECProtection_FEC_LOW.Enum(), 15, 20, 3}, - {"high", true, true, false, "leaky", livekit.FECProtection_FEC_HIGH.Enum(), 35, 20, 7}, - {"none", true, true, false, "pass", livekit.FECProtection_FEC_NONE.Enum(), 0, 20, 0}, + {"pass through", true, true, false, "pass", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), 25, 20, 5}, + {"queued", true, true, false, "queue", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), 25, 20, 5}, + {"low", true, true, false, "queue", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), 15, 20, 3}, + {"high", true, true, false, "leaky", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 35, 20, 7}, + {"none", true, true, false, "pass", fecDisabled(), 0, 20, 0}, {"default none", true, true, false, "pass", nil, 0, 20, 0}, - {"paced encrypted", true, true, true, "leaky", livekit.FECProtection_FEC_MEDIUM.Enum(), 25, 20, 5}, - {"subscriber declines", true, false, false, "pass", livekit.FECProtection_FEC_HIGH.Enum(), 35, 20, 0}, - {"disabled", false, true, false, "pass", livekit.FECProtection_FEC_HIGH.Enum(), 35, 20, 0}, - {"single packet frames", true, true, false, "pass", livekit.FECProtection_FEC_LOW.Enum(), 15, 1, 1}, - {"small frames", true, true, false, "queue", livekit.FECProtection_FEC_LOW.Enum(), 15, 2, 1}, - {"large frames", true, true, false, "leaky", livekit.FECProtection_FEC_HIGH.Enum(), 35, 99, 35}, + {"paced encrypted", true, true, true, "leaky", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), 25, 20, 5}, + {"subscriber declines", true, false, false, "pass", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 35, 20, 0}, + {"disabled", false, true, false, "pass", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 35, 20, 0}, + {"single packet frames", true, true, false, "pass", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), 15, 1, 1}, + {"small frames", true, true, false, "queue", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), 15, 2, 1}, + {"large frames", true, true, false, "leaky", fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 35, 99, 35}, } { t.Run(tc.name, func(t *testing.T) { h := vnettest.NewHosts(t) @@ -148,7 +156,7 @@ func TestDownTrackFlexFECOnWire(t *testing.T) { }) require.NoError(t, err) if tc.level != nil { - dt.SetFECProtection(*tc.level) + dt.SetFECProtection(tc.level) } tr, err := sender.AddTransceiverFromTrack(dt, webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionSendonly}) require.NoError(t, err) @@ -246,12 +254,12 @@ func TestDownTrackFlexFECOnWire(t *testing.T) { sequence := repair[len(repair)-1].SequenceNumber start := mediaCount for _, update := range []struct { - level livekit.FECProtection + level *livekit.FECProtection repairsPerFrame int }{ - {livekit.FECProtection_FEC_HIGH, 7}, - {livekit.FECProtection_FEC_NONE, 0}, - {livekit.FECProtection_FEC_LOW, 3}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 7}, + {fecDisabled(), 0}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), 3}, } { before := capture.count() dt.SetFECProtection(update.level) @@ -293,7 +301,7 @@ func TestDownTrackFlexFECOnWire(t *testing.T) { } }) next.SetTransceiver(tr) - next.SetFECProtection(livekit.FECProtection_FEC_MEDIUM) + next.SetFECProtection(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM)) require.NoError(t, tr.Sender().ReplaceTrack(next)) dt = next dt.SetConnected() diff --git a/pkg/sfu/downtrack_fec_test.go b/pkg/sfu/downtrack_fec_test.go index 378f25af1..751fc746b 100644 --- a/pkg/sfu/downtrack_fec_test.go +++ b/pkg/sfu/downtrack_fec_test.go @@ -26,6 +26,14 @@ import ( "github.com/livekit/livekit-server/pkg/sfu/flexfec" ) +func fecDisabled() *livekit.FECProtection { + return &livekit.FECProtection{} +} + +func fecFixed(level livekit.FECProtectionLevel) *livekit.FECProtection { + return &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_FIXED, Level: level} +} + type fecTrackContext struct { webrtc.TrackLocalContext ssrcFEC webrtc.SSRC @@ -47,7 +55,7 @@ func TestDownTrackFECNegotiationAndLifecycle(t *testing.T) { case "no ssrc": c.ssrcFEC = 0 } - d.SetFECProtection(livekit.FECProtection_FEC_MEDIUM) + d.SetFECProtection(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM)) d.bindFEC(c) if name != "enabled" { require.Nil(t, d.fecEncoder.Load()) @@ -60,7 +68,7 @@ func TestDownTrackFECNegotiationAndLifecycle(t *testing.T) { for i := range 5 { p.SequenceNumber++ p.Marker = i == 4 - repair := old.Encode(&p, []byte{1, 2, 3}) + repair := old.Encode(&p, []byte{1, 2, 3}, false) if i == 4 { require.Len(t, repair, 1) require.EqualValues(t, 456, repair[0].SSRC) @@ -73,8 +81,8 @@ func TestDownTrackFECNegotiationAndLifecycle(t *testing.T) { for i := range 5 { p.SequenceNumber++ p.Marker = i == 4 - require.Empty(t, old.Encode(&p, []byte{1, 2, 3}), "old queued writes cannot generate repair") - for _, repair := range d.fecEncoder.Load().Encode(&p, []byte{1, 2, 3}) { + require.Empty(t, old.Encode(&p, []byte{1, 2, 3}, false), "old queued writes cannot generate repair") + for _, repair := range d.fecEncoder.Load().Encode(&p, []byte{1, 2, 3}, false) { require.Equal(t, lastSequenceNumber+1, repair.SequenceNumber, "reusing an SSRC must preserve repair sequencing") } } @@ -90,7 +98,7 @@ func TestDownTrackFECBandwidthReservation(t *testing.T) { d := &DownTrack{receiver: receiver} _, got := d.getLayeredBitrateWithFEC() require.Equal(t, rates, got) - d.SetFECProtection(livekit.FECProtection_FEC_MEDIUM) + d.SetFECProtection(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM)) encoder := flexfec.NewEncoder(115, 456, nil) encoder.SetProtectionPercent(25) d.fecEncoder.Store(encoder) @@ -124,20 +132,20 @@ func TestDownTrackFECMeasuredBandwidthReservation(t *testing.T) { negotiatedCodecParameters: []webrtc.RTPCodecParameters{{RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeFlexFEC03}, PayloadType: 115}}, streamAllocatorListener: listener, } - d.SetFECProtection(livekit.FECProtection_FEC_LOW) + d.SetFECProtection(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW)) d.bindFEC(fecTrackContext{ssrcFEC: 456}) e := d.fecEncoder.Load() p := rtp.Header{Version: 2, SSRC: 123, PayloadType: 96, Marker: true} for range 2 { p.SequenceNumber++ - repairs := e.Encode(&p, make([]byte, 100)) + repairs := e.Encode(&p, make([]byte, 100), false) require.Len(t, repairs, 1) e.RecordSent(1, len(repairs[0].Payload), repairs[0].MarshalSize()) } _, rates := d.getLayeredBitrateWithFEC() require.EqualValues(t, 218_000, rates[0][0], "reserve actual small-frame overhead, including RTP/FEC headers") require.Equal(t, 1, listener.changes, "reallocate on an overhead change, not on every repair") - d.SetFECProtection(livekit.FECProtection_FEC_NONE) + d.SetFECProtection(fecDisabled()) _, rates = d.getLayeredBitrateWithFEC() require.EqualValues(t, 100_000, rates[0][0]) require.Equal(t, 2, listener.changes) @@ -151,7 +159,7 @@ func TestDownTrackFECProtectionChanges(t *testing.T) { negotiatedCodecParameters: []webrtc.RTPCodecParameters{{RTPCodecCapability: webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeFlexFEC03}, PayloadType: 115}}, } // Cached settings can arrive before Pion binds the track. - d.SetFECProtection(livekit.FECProtection_FEC_MEDIUM) + d.SetFECProtection(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM)) d.bindFEC(fecTrackContext{ssrcFEC: 456}) encoder := d.fecEncoder.Load() require.NotNil(t, encoder) @@ -163,21 +171,29 @@ func TestDownTrackFECProtectionChanges(t *testing.T) { for i := range 20 { p.SequenceNumber++ p.Marker = i == 19 - count += len(d.fecEncoder.Load().Encode(&p, []byte{1, 2, 3})) + count += len(d.fecEncoder.Load().Encode(&p, []byte{1, 2, 3}, false)) } return count } require.Equal(t, 5, send()) for _, tc := range []struct { - level livekit.FECProtection + level *livekit.FECProtection percent int64 }{ - {livekit.FECProtection_FEC_NONE, 0}, - {livekit.FECProtection_FEC_LOW, 15}, - {livekit.FECProtection_FEC_MEDIUM, 25}, - {livekit.FECProtection_FEC_HIGH, 35}, - {-1, 0}, - {99, 0}, + {fecDisabled(), 0}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), 15}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), 25}, + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), 35}, + {nil, 0}, + {&livekit.FECProtection{Mode: -1, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, 0}, + {&livekit.FECProtection{Mode: 99, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, 0}, + // an unspecified or unknown level is the server default, low + {fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_UNSPECIFIED), 15}, + {fecFixed(99), 15}, + // without receiver reports, adaptive protection is off and minimum + // protection is at its floor + {&livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_ADAPTIVE, Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH}, 0}, + {&livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_MINIMUM, Level: livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM}, 25}, } { d.SetFECProtection(tc.level) require.Same(t, encoder, d.fecEncoder.Load(), "updates do not rebind or reset repair sequencing") @@ -186,7 +202,7 @@ func TestDownTrackFECProtectionChanges(t *testing.T) { require.EqualValues(t, tc.percent/5, send()) } d.closeFEC() - d.SetFECProtection(livekit.FECProtection_FEC_HIGH) + d.SetFECProtection(fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH)) d.bindFEC(fecTrackContext{ssrcFEC: 456}) require.NotSame(t, encoder, d.fecEncoder.Load()) require.Equal(t, 7, send(), "rebind retains the subscriber's preset") diff --git a/pkg/sfu/flexfec/encoder.go b/pkg/sfu/flexfec/encoder.go index e0e863c28..2193dbdf4 100644 --- a/pkg/sfu/flexfec/encoder.go +++ b/pkg/sfu/flexfec/encoder.go @@ -28,9 +28,7 @@ import ( ) const ( - // DefaultProtectionPercent is the repair-to-media packet ratio when unspecified. - DefaultProtectionPercent uint32 = 0 - MaxProtectionPercent uint32 = 100 + MaxProtectionPercent uint32 = 100 // MaxMediaPacketsPerGroup bounds memory and work for large frames. Like // libwebrtc, use at most 48 media packets in a protection block. MaxMediaPacketsPerGroup = 48 @@ -64,19 +62,31 @@ type encoderMediaGroup struct { // payloads as soon as Encode returns. It does not delay media or start workers. // Methods are safe to call from concurrent pass-through pacer writes. type Encoder struct { - mu sync.Mutex - encoder *pionflexfec.FlexEncoder03 - media *encoderMediaGroup - count int - startedAt int64 - sequenceNumber uint16 - ssrc uint32 - closed bool - onSent func(packets int, bytes int) - protectionPercent uint32 - protectionFactor uint32 + mu sync.Mutex + encoder *pionflexfec.FlexEncoder03 + media *encoderMediaGroup + count int + startedAt int64 + sequenceNumber uint16 + ssrc uint32 + closed bool + onSent func(packets int, bytes int) + + protection Protection + // adaptive is updated in every mode, like libwebrtc runs its adaptive + // computation before applying a protection override, so that switching + // to adaptive or minimum protection starts from the current loss history. + adaptive *adaptiveState + // effective Q8 repair-to-media packet ratios for delta and key frames + deltaFactor uint8 + keyFactor uint8 + // whether the frame with frameTimestamp contains key frame packets + frameTimestamp uint32 + frameKey bool overheadPercent atomic.Uint32 + configuredPercent uint32 + measuredPercent uint32 overheadUpdatedAt int64 sentMediaBytes uint64 sentRepairBytes uint64 @@ -84,11 +94,11 @@ type Encoder struct { func NewEncoder(payloadType uint8, ssrc uint32, onSent func(packets int, bytes int)) *Encoder { return &Encoder{ - encoder: pionflexfec.NewFlexEncoder03(payloadType, ssrc), - sequenceNumber: uint16(rand.Uint32()), - ssrc: ssrc, - onSent: onSent, - protectionPercent: DefaultProtectionPercent, + encoder: pionflexfec.NewFlexEncoder03(payloadType, ssrc), + sequenceNumber: uint16(rand.Uint32()), + ssrc: ssrc, + onSent: onSent, + adaptive: newAdaptiveState(mono.UnixNano()), } } @@ -115,18 +125,36 @@ func (e *Encoder) SeedState(state EncoderState) { // changes discard an incomplete previous frame. Gaps, codec switches and stale // groups also reset the block; Pion requires consecutive sequence numbers. // Media is never delayed. No timer or worker is needed for sparse frames. +// keyFrame marks packets of key frames, which use the key frame protection +// factor; it is enough to mark one packet of each key frame. // Call after the media write, including any interceptor header modifications. -func (e *Encoder) Encode(header *rtp.Header, payload []byte) []rtp.Packet { +func (e *Encoder) Encode(header *rtp.Header, payload []byte, keyFrame bool) []rtp.Packet { + return e.encode(mono.UnixNano(), header, payload, keyFrame) +} + +func (e *Encoder) encode(now int64, header *rtp.Header, payload []byte, keyFrame bool) []rtp.Packet { e.mu.Lock() defer e.mu.Unlock() - if e.closed || e.protectionPercent == 0 { + if e.closed { return nil } - now := mono.UnixNano() size := header.MarshalSize() + len(payload) - e.sentMediaBytes += uint64(size) - if header.Padding || len(payload) == 0 || size > maxEncoderMediaPacketSize { + if header.Timestamp != e.frameTimestamp { + e.frameTimestamp = header.Timestamp + e.frameKey = false + } + e.frameKey = e.frameKey || keyFrame + e.adaptive.onMediaPacket(now, len(payload), header.Marker, e.frameKey) + factor := e.deltaFactor + if e.frameKey { + factor = e.keyFactor + } + if factor != 0 { + // Measure overhead only over media that is protected. + e.sentMediaBytes += uint64(size) + } + if factor == 0 || header.Padding || len(payload) == 0 || size > maxEncoderMediaPacketSize { e.count = 0 return nil } @@ -173,7 +201,7 @@ func (e *Encoder) Encode(header *rtp.Header, payload []byte) []rtp.Packet { // Match libwebrtc's ForwardErrorCorrection::NumFecPackets: round the Q8 // protection factor, with at least one repair for every protected block. // In particular, a one-packet frame is protected immediately at every preset. - numRepair := max(uint32(1), (uint32(count)*e.protectionFactor+128)>>8) + numRepair := max(uint32(1), (uint32(count)*uint32(factor)+128)>>8) repair := e.encoder.EncodeFec(e.media.packets[:count], numRepair) for i := range repair { // Pion's encoder uses a constant timestamp and a fixed initial sequence number. @@ -185,23 +213,104 @@ func (e *Encoder) Encode(header *rtp.Header, payload []byte) []rtp.Packet { return repair } -// SetProtectionPercent updates the packet ratio without changing the repair -// SSRC or sequence number. A new value discards partial groups and measurements. -// Values above 100 are capped; zero disables encoding before any packet copies. -func (e *Encoder) SetProtectionPercent(percent uint32) { - percent = min(percent, MaxProtectionPercent) +// SetProtection updates the requested protection without changing the repair +// SSRC or sequence number. Like libwebrtc, a group that is already +// accumulating is kept and protected with the new rate when it completes, and +// the adaptive state keeps its history. Overhead measurements restart. +// Disabling stops encoding before any packet copies. +func (e *Encoder) SetProtection(protection Protection) { e.mu.Lock() - if e.protectionPercent != percent { - e.protectionPercent = percent - // Publish-track presets use the same conversion to libwebrtc's Q8 rate. - e.protectionFactor = percent * 255 / 100 + defer e.mu.Unlock() + if protection.Mode < ProtectionDisabled || protection.Mode > ProtectionMinimum { + protection = Protection{} + } + if protection.Mode != ProtectionFixed && protection.Mode != ProtectionMinimum { + protection.Factor = 0 + } + if e.protection == protection { + return + } + e.protection = protection + e.measuredPercent = 0 + e.overheadUpdatedAt = 0 + e.sentMediaBytes = 0 + e.sentRepairBytes = 0 + e.setFactorsLocked(e.effectiveFactorsLocked()) +} + +// SetProtectionPercent sets a fixed repair-to-media packet percentage; values +// above 100 are capped and zero disables encoding. +func (e *Encoder) SetProtectionPercent(percent uint32) { + if percent == 0 { + e.SetProtection(Protection{}) + return + } + e.SetProtection(Protection{Mode: ProtectionFixed, Factor: ProtectionFactorFromPercent(percent)}) +} + +// NetworkStats are the receiver-side inputs of adaptive protection. +type NetworkStats struct { + // FractionLost is the Q8 loss fraction from an RTCP reception report. + FractionLost uint8 + RTT time.Duration + // Width and Height of the forwarded video, zero when unknown. + Width uint32 + Height uint32 +} + +// OnReceiverReport updates the adaptive state from a reception report of the +// protected media stream. It changes the effective rates only in adaptive and +// minimum modes, but is tracked in every mode. +func (e *Encoder) OnReceiverReport(stats NetworkStats) { + e.onReceiverReport(mono.UnixNano(), stats) +} + +func (e *Encoder) onReceiverReport(now int64, stats NetworkStats) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return + } + e.adaptive.update(now, stats) + e.setFactorsLocked(e.effectiveFactorsLocked()) +} + +// ProtectionFactors returns the effective Q8 repair-to-media packet ratios for +// delta and key frames. +func (e *Encoder) ProtectionFactors() (delta uint8, key uint8) { + e.mu.Lock() + defer e.mu.Unlock() + return e.deltaFactor, e.keyFactor +} + +// effectiveFactorsLocked applies the requested mode on top of the adaptive +// factors, like libwebrtc's ApplyProtectionOverride. +func (e *Encoder) effectiveFactorsLocked() (uint8, uint8) { + switch e.protection.Mode { + case ProtectionFixed: + return e.protection.Factor, e.protection.Factor + case ProtectionAdaptive: + return e.adaptive.deltaFactor, e.adaptive.keyFactor + case ProtectionMinimum: + return max(e.adaptive.deltaFactor, e.protection.Factor), max(e.adaptive.keyFactor, e.protection.Factor) + default: + return 0, 0 + } +} + +func (e *Encoder) setFactorsLocked(delta uint8, key uint8) { + e.deltaFactor, e.keyFactor = delta, key + if delta == 0 && key == 0 { + // Nothing will be sent, so measurements would never refresh. e.count = 0 - e.overheadPercent.Store(percent) + e.measuredPercent = 0 e.overheadUpdatedAt = 0 e.sentMediaBytes = 0 e.sentRepairBytes = 0 } - e.mu.Unlock() + // Reserve for delta frames; key frames are rare and are not reserved for. + e.configuredPercent = protectionFactorToPercent(delta) + e.overheadPercent.Store(max(e.configuredPercent, e.measuredPercent)) } // OverheadPercent reserves at least the configured rate, using measured RTP @@ -220,12 +329,12 @@ func (e *Encoder) RecordSent(packets int, payloadBytes int, rtpBytes int) { return } e.mu.Lock() - if !e.closed && e.protectionPercent != 0 { + if !e.closed && e.protection.Mode != ProtectionDisabled { e.sentRepairBytes += uint64(rtpBytes) now := mono.UnixNano() if e.sentMediaBytes != 0 && (e.overheadUpdatedAt == 0 || now-e.overheadUpdatedAt >= int64(overheadUpdateInterval)) { - percent := uint32((e.sentRepairBytes*100 + e.sentMediaBytes - 1) / e.sentMediaBytes) - e.overheadPercent.Store(max(e.protectionPercent, percent)) + e.measuredPercent = uint32((e.sentRepairBytes*100 + e.sentMediaBytes - 1) / e.sentMediaBytes) + e.overheadPercent.Store(max(e.configuredPercent, e.measuredPercent)) e.overheadUpdatedAt = now e.sentMediaBytes = 0 e.sentRepairBytes = 0 @@ -246,3 +355,78 @@ func (e *Encoder) Close() { e.encoder = nil e.mu.Unlock() } + +// adaptiveState holds the inputs of libwebrtc's loss protection logic that +// the encoder measures itself: sent bit rate, frame rate and packets per frame. +type adaptiveState struct { + loss lossFilter + + packetsPerFrame expFilter + packetsPerFrameKey expFilter + packetsPerFrameAt int64 + packetsPerFrameKeyAt int64 + frameBytes int + windowStart int64 + windowBytes uint64 + windowFrames uint64 + bitrateKbps float64 + frameRate float64 + deltaFactor uint8 + keyFactor uint8 +} + +// Use at least this window to measure the sent bit and frame rates. +const minRateWindow = 500 * time.Millisecond + +func newAdaptiveState(now int64) *adaptiveState { + return &adaptiveState{ + loss: newLossFilter(), + packetsPerFrame: newExpFilter(packetsPerFrameAlpha), + packetsPerFrameKey: newExpFilter(packetsPerFrameAlpha), + packetsPerFrameAt: now, + packetsPerFrameKeyAt: now, + windowStart: now, + } +} + +func (a *adaptiveState) onMediaPacket(now int64, payloadSize int, marker bool, keyFrame bool) { + a.windowBytes += uint64(payloadSize) + a.frameBytes += payloadSize + if !marker { + return + } + a.windowFrames++ + // Like FecControllerDefault::UpdateWithEncodedData, estimate packets from + // the frame size so that the key/delta ratio does not depend on packetization. + packets := float64(a.frameBytes) / adaptiveMaxPayloadSize + a.frameBytes = 0 + if keyFrame { + a.packetsPerFrameKey.apply(float64(now-a.packetsPerFrameKeyAt)/1e6, packets) + a.packetsPerFrameKeyAt = now + } else { + a.packetsPerFrame.apply(float64(now-a.packetsPerFrameAt)/1e6, packets) + a.packetsPerFrameAt = now + } +} + +func (a *adaptiveState) update(now int64, stats NetworkStats) { + if elapsed := now - a.windowStart; elapsed >= int64(minRateWindow) { + elapsedMs := float64(elapsed) / 1e6 + // bits per millisecond is kbps + a.bitrateKbps = float64(a.windowBytes) * 8 / elapsedMs + a.frameRate = float64(a.windowFrames) * 1000 / elapsedMs + a.windowStart = now + a.windowBytes = 0 + a.windowFrames = 0 + } + a.deltaFactor, a.keyFactor = adaptiveProtectionFactors(adaptiveParams{ + loss: a.loss.filteredLoss(now/1e6, stats.FractionLost), + rttMs: stats.RTT.Milliseconds(), + bitrateKbps: a.bitrateKbps, + frameRate: a.frameRate, + packetsPerFrame: a.packetsPerFrame.filtered, + packetsPerFrameKey: a.packetsPerFrameKey.filtered, + width: int(stats.Width), + height: int(stats.Height), + }) +} diff --git a/pkg/sfu/flexfec/encoder_test.go b/pkg/sfu/flexfec/encoder_test.go index e4394e5ff..25f95da88 100644 --- a/pkg/sfu/flexfec/encoder_test.go +++ b/pkg/sfu/flexfec/encoder_test.go @@ -39,7 +39,7 @@ func TestEncoderDefaultsToNoProtection(t *testing.T) { p := rtp.Header{Version: 2, SSRC: testMediaSSRC, PayloadType: testMediaPT, Marker: true} for range 100 { p.SequenceNumber++ - require.Empty(t, e.Encode(&p, []byte{1, 2, 3})) + require.Empty(t, e.Encode(&p, []byte{1, 2, 3}, false)) } require.Zero(t, e.count) require.Nil(t, e.media, "negotiation alone must not allocate packet storage") @@ -62,7 +62,7 @@ func TestEncoderFrameProtectionCounts(t *testing.T) { e := NewEncoder(testFECPT, testFECSSRC, nil) e.SetProtectionPercent(level.percent) for i, p := range makeEncoderFrame(t, 100, tc.packets) { - repairs := e.Encode(&p.Header, p.Payload) + repairs := e.Encode(&p.Header, p.Payload, false) if i == tc.packets-1 { require.Len(t, repairs, level.want) for _, repair := range repairs { @@ -86,7 +86,7 @@ func TestEncoderSparseFrames(t *testing.T) { for i := range 3 { e.startedAt -= int64(10 * maxEncoderGroupAge) p := makeEncoderFrame(t, uint16(100+i), 1)[0] - repairs := e.Encode(&p.Header, p.Payload) + repairs := e.Encode(&p.Header, p.Payload, false) require.Len(t, repairs, 1, "even the first isolated frame needs immediate protection") decoder := newTestDecoder(testFECSSRC, testMediaSSRC, logger.GetLogger()) recovered := decoder.DecodeFEC(&repairs[0]) @@ -101,7 +101,7 @@ func TestEncoderState(t *testing.T) { e.SeedState(EncoderState{SSRC: testFECSSRC, NextSequenceNumber: 65535}) for _, sn := range []uint16{65535, 0} { p := makeEncoderFrame(t, 100, 1)[0] - repair := e.Encode(&p.Header, p.Payload) + repair := e.Encode(&p.Header, p.Payload, false) require.Len(t, repair, 1) require.Equal(t, sn, repair[0].SequenceNumber) e.Close() @@ -129,7 +129,7 @@ func TestEncoderRecoveryWithReusedMemory(t *testing.T) { require.NoError(t, media[i].SetExtension(3, []byte{byte(i), 2, 3})) require.NoError(t, media[i].SetExtension(5, []byte{7, byte(i)})) packet := media[i].Clone() - repair = append(repair, e.Encode(&packet.Header, packet.Payload)...) + repair = append(repair, e.Encode(&packet.Header, packet.Payload, false)...) clear(packet.Payload) clear(packet.CSRC) clear(packet.GetExtension(3)) @@ -156,7 +156,7 @@ func TestEncoderGroupBoundaries(t *testing.T) { e.SetProtectionPercent(20) media := makeEncoderFrame(t, 100, 5) for i := 0; i < 3; i++ { - require.Empty(t, e.Encode(&media[i].Header, media[i].Payload)) + require.Empty(t, e.Encode(&media[i].Header, media[i].Payload, false)) } p := &media[3] switch name { @@ -181,10 +181,10 @@ func TestEncoderGroupBoundaries(t *testing.T) { case "empty": p.Payload = nil } - require.Empty(t, e.Encode(&p.Header, p.Payload)) + require.Empty(t, e.Encode(&p.Header, p.Payload, false)) require.LessOrEqual(t, e.count, 1, "discard the previous partial block") fresh := makeEncoderFrame(t, 200, 1)[0] - repairs := e.Encode(&fresh.Header, fresh.Payload) + repairs := e.Encode(&fresh.Header, fresh.Payload, false) require.Len(t, repairs, 1) decoder := newTestDecoder(testFECSSRC, testMediaSSRC, logger.GetLogger()) recovered := decoder.DecodeFEC(&repairs[0]) @@ -201,7 +201,7 @@ func TestEncoderLargeFrame(t *testing.T) { decoder := newTestDecoder(testFECSSRC, testMediaSSRC, logger.GetLogger()) var repair []rtp.Packet for i := range media { - out := e.Encode(&media[i].Header, media[i].Payload) + out := e.Encode(&media[i].Header, media[i].Payload, false) switch i { case 47, 95: require.Len(t, out, 17) @@ -233,7 +233,7 @@ func TestEncoderSizeLimitAndClose(t *testing.T) { payload := make([]byte, maxEncoderMediaPacketSize-12) for i := range MaxMediaPacketsPerGroup { p.SequenceNumber++ - out := e.Encode(&p, payload) + out := e.Encode(&p, payload, false) if i == MaxMediaPacketsPerGroup-1 { require.Len(t, out, 1) out[0].Extension = true @@ -247,7 +247,7 @@ func TestEncoderSizeLimitAndClose(t *testing.T) { p.Marker = true for range 10 { p.SequenceNumber++ - require.Empty(t, e.Encode(&p, payload)) + require.Empty(t, e.Encode(&p, payload, false)) } require.Nil(t, e.media) } @@ -258,14 +258,14 @@ func TestEncoderAccumulationReusesStorage(t *testing.T) { p := rtp.Header{Version: 2, SSRC: testMediaSSRC} require.NoError(t, p.SetExtension(3, []byte{1, 2, 3})) payload := make([]byte, 1200) - require.Empty(t, e.Encode(&p, payload)) + require.Empty(t, e.Encode(&p, payload, false)) require.NotNil(t, e.media.storage[0]) require.Nil(t, e.media.storage[1], "small frames do not allocate large-frame payload storage") allocs := testing.AllocsPerRun(100, func() { e.count = 0 for range MaxMediaPacketsPerGroup - 1 { p.SequenceNumber++ - e.Encode(&p, payload) + e.Encode(&p, payload, false) } }) require.Zero(t, allocs) @@ -275,32 +275,33 @@ func TestEncoderProtectionPercentChanges(t *testing.T) { e := NewEncoder(testFECPT, testFECSSRC, nil) e.SetProtectionPercent(20) p := makeEncoderFrame(t, 100, 1)[0] - first := e.Encode(&p.Header, p.Payload) + first := e.Encode(&p.Header, p.Payload, false) require.Len(t, first, 1) p.Marker = false for range 3 { p.SequenceNumber++ - require.Empty(t, e.Encode(&p.Header, p.Payload)) + require.Empty(t, e.Encode(&p.Header, p.Payload, false)) } e.SetProtectionPercent(40) p.SequenceNumber++ p.Marker = true - repairs := e.Encode(&p.Header, p.Payload) - require.Len(t, repairs, 1, "discard the old partial frame on a setting change") + repairs := e.Encode(&p.Header, p.Payload, false) + require.Len(t, repairs, 2, "like libwebrtc, keep the partial frame and protect it at the new rate") require.Equal(t, first[0].SequenceNumber+1, repairs[0].SequenceNumber) + repairs = repairs[1:] e.SetProtectionPercent(0) - require.Empty(t, e.Encode(&p.Header, p.Payload)) + require.Empty(t, e.Encode(&p.Header, p.Payload, false)) require.Zero(t, e.OverheadPercent()) e.SetProtectionPercent(40) p.Marker = false for range 4 { p.SequenceNumber++ - require.Empty(t, e.Encode(&p.Header, p.Payload)) + require.Empty(t, e.Encode(&p.Header, p.Payload, false)) } e.SetProtectionPercent(40) p.SequenceNumber++ p.Marker = true - last := e.Encode(&p.Header, p.Payload) + last := e.Encode(&p.Header, p.Payload, false) require.Len(t, last, 2, "unchanged settings retain the partial frame") require.Equal(t, repairs[0].SequenceNumber+1, last[0].SequenceNumber) } @@ -316,7 +317,7 @@ func TestEncoderMeasuredOverhead(t *testing.T) { require.EqualValues(t, 15, e.OverheadPercent()) p := rtp.Header{Version: 2, SSRC: testMediaSSRC, Marker: true} payload := make([]byte, 100) - repairs := e.Encode(&p, payload) + repairs := e.Encode(&p, payload, false) require.Len(t, repairs, 1) e.RecordSent(1, len(repairs[0].Payload), repairs[0].MarshalSize()) require.EqualValues(t, 118, e.OverheadPercent(), "132 repair bytes / 112 media bytes, rounded up") @@ -324,7 +325,7 @@ func TestEncoderMeasuredOverhead(t *testing.T) { for i := range 20 { p.SequenceNumber++ p.Marker = i == 19 - repairs = e.Encode(&p, payload) + repairs = e.Encode(&p, payload, false) } require.Len(t, repairs, 3) e.overheadUpdatedAt -= int64(overheadUpdateInterval) @@ -349,7 +350,7 @@ func TestEncoderConcurrentProtectionChangesAndClose(t *testing.T) { p := rtp.Header{Version: 2, SSRC: testMediaSSRC, Marker: true} for range 1000 { p.SequenceNumber++ - repair := e.Encode(&p, []byte{1, 2, 3}) + repair := e.Encode(&p, []byte{1, 2, 3}, false) for _, packet := range repair { e.RecordSent(1, len(packet.Payload), packet.MarshalSize()) } @@ -373,7 +374,7 @@ func BenchmarkEncoder(b *testing.B) { for i := range packets { p.SequenceNumber++ p.Marker = i == packets-1 - e.Encode(&p, payload) + e.Encode(&p, payload, false) } } send() diff --git a/pkg/sfu/flexfec/fec_rate_table.go b/pkg/sfu/flexfec/fec_rate_table.go new file mode 100644 index 000000000..f265d8135 --- /dev/null +++ b/pkg/sfu/flexfec/fec_rate_table.go @@ -0,0 +1,428 @@ +// 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 + +// fecRateTable is libwebrtc's kFecRateTable (modules/video_coding/fec_rate_table.h), +// Copyright (c) 2011 The WebRTC project authors, used under its BSD-style license. +// +// It holds the delta-frame protection factor (Q8, relative to source plus +// repair packets) indexed by rateIndex*packetLossMax + lossQ8, where lossQ8 is +// in [0, 128] and rateIndex in [0, 49] is derived from the effective bits per frame. +var fecRateTable = [fecRateTableSize]uint8{ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, + 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, + 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, 39, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, + 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, + 8, 8, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, + 30, 56, 56, 56, 56, 56, 56, 56, 65, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, + 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, + 65, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, 87, + 87, 87, 87, 87, 87, 87, 87, 87, 87, 78, 78, 78, 78, 78, 78, 78, + 78, 78, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 6, 6, 6, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, + 23, 23, 23, 44, 44, 44, 44, 44, 44, 50, 50, 50, 50, 50, 50, 50, + 50, 50, 68, 68, 68, 68, 68, 68, 68, 85, 85, 85, 85, 85, 85, 85, + 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, + 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, + 85, 85, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, + 105, 105, 105, 105, 105, 105, 105, 105, 105, 105, 88, 88, 88, 88, 88, 88, + 88, 88, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, + 5, 5, 19, 19, 19, 36, 41, 41, 41, 41, 41, 41, 41, 41, 41, 41, + 41, 41, 41, 41, 55, 55, 55, 55, 55, 55, 69, 69, 69, 69, 69, 69, + 69, 69, 69, 75, 75, 80, 80, 80, 80, 80, 97, 97, 97, 97, 97, 97, + 97, 97, 97, 97, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, + 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, 102, + 102, 102, 102, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, + 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 116, 100, 100, 100, 100, 100, + 100, 100, 100, 100, 0, 0, 0, 0, 0, 0, 0, 0, 4, 16, 16, 16, + 16, 16, 16, 30, 35, 35, 47, 58, 58, 58, 58, 58, 58, 58, 58, 58, + 58, 58, 58, 58, 58, 63, 63, 63, 63, 63, 63, 77, 77, 77, 77, 77, + 77, 77, 82, 82, 82, 82, 94, 94, 94, 94, 94, 105, 105, 105, 105, 110, + 110, 110, 110, 110, 110, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, + 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, + 122, 122, 122, 122, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 115, 115, 115, 115, + 115, 115, 115, 115, 115, 0, 0, 0, 0, 0, 0, 0, 4, 14, 27, 27, + 27, 27, 27, 31, 41, 52, 52, 56, 69, 69, 69, 69, 69, 69, 69, 69, + 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 69, 79, 79, 79, 79, + 83, 83, 83, 94, 94, 94, 94, 106, 106, 106, 106, 106, 115, 115, 115, 115, + 125, 125, 125, 125, 125, 125, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 0, 0, 0, 0, 3, 3, 3, 17, 28, 38, + 38, 38, 38, 38, 47, 51, 63, 63, 63, 72, 72, 72, 72, 72, 72, 72, + 76, 76, 76, 76, 80, 80, 80, 80, 80, 80, 80, 80, 80, 84, 84, 84, + 84, 93, 93, 93, 105, 105, 105, 105, 114, 114, 114, 114, 114, 124, 124, 124, + 124, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 0, 12, 12, 12, 35, 43, + 47, 47, 47, 47, 47, 58, 58, 66, 66, 66, 70, 70, 70, 70, 70, 73, + 73, 82, 82, 82, 86, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, + 94, 94, 105, 105, 105, 114, 114, 114, 114, 117, 117, 117, 117, 117, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 0, 24, 24, 24, 49, + 53, 53, 53, 53, 53, 53, 61, 61, 64, 64, 64, 64, 70, 70, 70, 70, + 78, 78, 88, 88, 88, 96, 106, 106, 106, 106, 106, 106, 106, 106, 106, 106, + 112, 112, 112, 120, 120, 120, 124, 124, 124, 124, 124, 124, 124, 124, 124, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 5, 36, 36, 36, + 55, 55, 55, 55, 55, 55, 55, 58, 58, 58, 58, 58, 64, 78, 78, 78, + 78, 87, 87, 94, 94, 94, 103, 110, 110, 110, 110, 110, 110, 110, 110, 116, + 116, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 18, 43, 43, + 43, 53, 53, 53, 53, 53, 53, 53, 53, 58, 58, 58, 58, 71, 87, 87, + 87, 87, 94, 94, 97, 97, 97, 109, 111, 111, 111, 111, 111, 111, 111, 111, + 125, 125, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 0, 31, 46, + 46, 46, 48, 48, 48, 48, 48, 48, 48, 48, 66, 66, 66, 66, 80, 93, + 93, 93, 93, 95, 95, 95, 95, 100, 115, 115, 115, 115, 115, 115, 115, 115, + 115, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 4, 40, + 45, 45, 45, 45, 45, 45, 45, 45, 49, 49, 49, 74, 74, 74, 74, 86, + 90, 90, 90, 90, 95, 95, 95, 95, 106, 120, 120, 120, 120, 120, 120, 120, + 120, 120, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, 14, + 42, 42, 42, 42, 42, 42, 42, 42, 46, 56, 56, 56, 80, 80, 80, 80, + 84, 84, 84, 84, 88, 99, 99, 99, 99, 111, 122, 122, 122, 122, 122, 122, + 122, 122, 122, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 0, + 26, 40, 40, 40, 40, 40, 40, 40, 40, 54, 66, 66, 66, 80, 80, 80, + 80, 80, 80, 80, 84, 94, 106, 106, 106, 106, 116, 120, 120, 120, 120, 120, + 120, 120, 120, 124, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, + 3, 34, 38, 38, 38, 38, 38, 42, 42, 42, 63, 72, 72, 76, 80, 80, + 80, 80, 80, 80, 80, 89, 101, 114, 114, 114, 114, 118, 118, 118, 118, 118, + 118, 118, 118, 118, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 0, 12, 36, 36, 36, 36, 36, 36, 49, 49, 49, 69, 73, 76, 86, 86, + 86, 86, 86, 86, 86, 86, 97, 109, 122, 122, 122, 122, 122, 122, 122, 122, + 122, 122, 122, 122, 122, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 0, 22, 34, 34, 34, 34, 38, 38, 57, 57, 57, 69, 73, 82, 92, + 92, 92, 92, 92, 92, 96, 96, 104, 117, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 0, 29, 33, 33, 33, 33, 44, 44, 62, 62, 62, 69, 77, 87, + 95, 95, 95, 95, 95, 95, 107, 107, 110, 120, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 0, 31, 31, 31, 31, 31, 51, 51, 62, 65, 65, 73, 83, + 91, 94, 94, 94, 94, 97, 97, 114, 114, 114, 122, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 0, 29, 29, 29, 29, 29, 56, 56, 59, 70, 70, 79, + 86, 89, 89, 89, 89, 89, 100, 100, 116, 116, 116, 122, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 0, 28, 28, 28, 28, 28, 57, 57, 57, 76, 76, + 83, 86, 86, 86, 86, 86, 89, 104, 104, 114, 114, 114, 124, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 0, 27, 27, 27, 27, 30, 55, 55, 55, 80, + 80, 83, 86, 86, 86, 86, 86, 93, 108, 108, 111, 111, 111, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 0, 26, 26, 26, 26, 36, 53, 53, 53, + 80, 80, 80, 90, 90, 90, 90, 90, 98, 107, 107, 107, 107, 107, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 0, 26, 26, 26, 28, 42, 52, 54, + 54, 78, 78, 78, 95, 95, 95, 97, 97, 104, 106, 106, 106, 106, 106, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 24, 24, 24, 33, 47, 49, + 58, 58, 74, 74, 74, 97, 97, 97, 106, 106, 108, 108, 108, 108, 108, 108, + 124, 124, 124, 124, 124, 124, 124, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 24, 24, 24, 39, 48, + 50, 63, 63, 72, 74, 74, 96, 96, 96, 109, 111, 111, 111, 111, 111, 111, + 111, 119, 119, 122, 122, 122, 122, 122, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 23, 23, 23, 43, + 46, 54, 66, 66, 69, 77, 77, 92, 92, 92, 105, 113, 113, 113, 113, 113, + 113, 113, 115, 117, 123, 123, 123, 123, 123, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 22, 22, 22, + 44, 44, 59, 67, 67, 67, 81, 81, 89, 89, 89, 97, 112, 112, 112, 112, + 112, 112, 112, 112, 119, 126, 126, 126, 126, 126, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 21, 21, + 24, 43, 45, 63, 65, 65, 67, 85, 85, 87, 87, 87, 91, 109, 109, 109, + 111, 111, 111, 111, 111, 123, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 21, + 21, 28, 42, 50, 63, 63, 66, 71, 85, 85, 85, 85, 87, 92, 106, 106, + 108, 114, 114, 114, 114, 114, 125, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, + 20, 20, 34, 41, 54, 62, 62, 69, 75, 82, 82, 82, 82, 92, 98, 105, + 105, 110, 117, 117, 117, 117, 117, 124, 124, 126, 126, 126, 126, 126, 126, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 0, 20, 20, 38, 40, 58, 60, 60, 73, 78, 80, 80, 80, 80, 100, 105, + 107, 107, 113, 118, 118, 118, 118, 118, 120, 120, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 0, 19, 21, 38, 40, 58, 58, 60, 75, 77, 77, 77, 81, 81, 107, + 109, 109, 109, 114, 116, 116, 116, 116, 116, 116, 116, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 0, 18, 25, 37, 44, 56, 56, 63, 75, 75, 75, 75, 88, 88, + 111, 111, 111, 111, 112, 112, 112, 112, 112, 112, 112, 114, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 0, 18, 30, 36, 48, 55, 55, 67, 73, 73, 73, 73, 97, + 97, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 116, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 0, 18, 34, 36, 52, 55, 55, 70, 72, 73, 73, 73, + 102, 104, 108, 108, 108, 108, 109, 109, 109, 109, 109, 109, 109, 119, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 0, 17, 35, 35, 52, 59, 59, 70, 70, 76, 76, + 76, 99, 105, 105, 105, 105, 105, 111, 111, 111, 111, 111, 111, 111, 121, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 0, 17, 34, 36, 51, 61, 62, 70, 70, 80, + 80, 80, 93, 103, 103, 103, 103, 103, 112, 112, 112, 112, 112, 116, 118, 124, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 0, 16, 33, 39, 50, 59, 65, 72, 72, + 82, 82, 82, 91, 100, 100, 100, 100, 100, 109, 109, 109, 109, 109, 121, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 0, 16, 32, 43, 48, 54, 66, 75, + 75, 81, 83, 83, 92, 97, 97, 97, 99, 99, 105, 105, 105, 105, 105, 123, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 15, 31, 46, 47, 49, 69, + 77, 77, 81, 85, 85, 93, 95, 95, 95, 100, 100, 102, 102, 102, 102, 102, + 120, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 15, 30, 46, 48, 48, + 70, 75, 79, 82, 87, 87, 92, 94, 94, 94, 103, 103, 103, 103, 103, 104, + 104, 115, 120, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 15, 30, 45, 50, + 50, 68, 70, 80, 85, 89, 89, 90, 95, 95, 95, 104, 104, 104, 104, 104, + 109, 109, 112, 114, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 14, 29, 44, + 54, 54, 64, 64, 83, 87, 88, 88, 88, 98, 98, 98, 103, 103, 103, 103, + 103, 113, 113, 113, 113, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 14, 29, + 43, 56, 56, 61, 61, 84, 85, 88, 88, 88, 100, 100, 100, 102, 102, 102, + 102, 102, 113, 116, 116, 116, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, 14, + 28, 42, 57, 57, 62, 62, 80, 80, 91, 91, 91, 100, 100, 100, 100, 100, + 100, 100, 100, 109, 119, 119, 119, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 0, + 14, 28, 42, 56, 56, 65, 66, 76, 76, 92, 92, 92, 97, 97, 97, 101, + 101, 101, 101, 101, 106, 121, 121, 121, 126, 126, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 0, 13, 27, 41, 55, 55, 67, 72, 74, 74, 90, 90, 90, 91, 91, 91, + 105, 105, 105, 105, 105, 107, 122, 122, 122, 123, 123, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 0, 13, 27, 40, 54, 54, 67, 76, 76, 76, 85, 85, 85, 85, 85, + 85, 112, 112, 112, 112, 112, 112, 121, 121, 121, 121, 121, 126, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, +} diff --git a/pkg/sfu/flexfec/protection.go b/pkg/sfu/flexfec/protection.go new file mode 100644 index 000000000..270243879 --- /dev/null +++ b/pkg/sfu/flexfec/protection.go @@ -0,0 +1,370 @@ +// 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 ( + "math" +) + +// ProtectionMode selects how the repair rate of a protected stream is chosen. +// The modes follow libwebrtc's RtpFecProtection::Mode. +type ProtectionMode int + +const ( + // ProtectionDisabled generates no repairs. + ProtectionDisabled ProtectionMode = iota + // ProtectionAdaptive follows observed packet loss, RTT, bits per frame and + // resolution, using libwebrtc's hybrid NACK/FEC protection logic. + ProtectionAdaptive + // ProtectionFixed uses Protection.Factor regardless of network conditions. + ProtectionFixed + // ProtectionMinimum uses the larger of the adaptive rate and Protection.Factor. + ProtectionMinimum +) + +func (m ProtectionMode) String() string { + switch m { + case ProtectionDisabled: + return "disabled" + case ProtectionAdaptive: + return "adaptive" + case ProtectionFixed: + return "fixed" + case ProtectionMinimum: + return "minimum" + default: + return "unknown" + } +} + +// Protection is a requested protection setting. +type Protection struct { + Mode ProtectionMode + // Factor is the Q8 repair-to-media packet ratio used by ProtectionFixed and + // ProtectionMinimum for both delta and key frames. It is ignored otherwise. + Factor uint8 +} + +func (p Protection) usesAdaptive() bool { + return p.Mode == ProtectionAdaptive || p.Mode == ProtectionMinimum +} + +// ProtectionFactorFromPercent converts a repair-to-media percentage to the Q8 +// FEC rate, truncating like the publish-track presets (38/63/89 for 15/25/35). +// Values above 100 are capped. +func ProtectionFactorFromPercent(percent uint32) uint8 { + return uint8(min(percent, MaxProtectionPercent) * 255 / 100) +} + +// protectionFactorToPercent rounds to the nearest percentage, so that a +// percentage converted with ProtectionFactorFromPercent maps back to itself. +func protectionFactorToPercent(factor uint8) uint32 { + return (uint32(factor)*100 + 127) / 255 +} + +// The constants and functions below port libwebrtc's VCMNackFecMethod and +// VCMLossProtectionLogic (modules/video_coding/media_opt_util.{h,cc}) as used +// by FecControllerDefault with NACK and FEC both enabled, which is always the +// case for SFU subscribers that negotiate FlexFEC. +const ( + // Max value of loss rates in the off-line model; the table has this many columns. + packetLossMax = 129 + fecRateTableSize = 6450 + + // The SFU protects every forwarded frame, so all forwarded temporal layers + // are accounted for as one layer. + adaptiveNumLayers = 1 + // VCMProtectionMethod::_maxPayloadSize + adaptiveMaxPayloadSize = 1460 + // Default VCMLossProtectionLogic resolution, used until one is known. + adaptiveDefaultWidth = 704 + adaptiveDefaultHeight = 576 + + // kLowRttNackMs: below this RTT, NACK alone protects delta frames. + lowRttNackMs = 20 + // Max RTT for BitRateTooLowForFec to turn off FEC. + maxRttTurnOffFecMs = 200 + // Bytes-per-frame thresholds below which FEC is turned off. + maxBytesPerFrameForFec = 700 + maxBytesPerFrameForFecLow = 400 + maxBytesPerFrameForFecHigh = 1000 + + // kLossPrHistorySize and kLossPrShortFilterWinMs for the max-window loss filter. + lossPrHistorySize = 10 + lossPrShortFilterWinMs = 1000 + packetsPerFrameAlpha = 0.9999 + expFilterValueUndefined = -1.0 +) + +type adaptiveParams struct { + // filtered loss, Q8 + loss uint8 + rttMs int64 + bitrateKbps float64 + frameRate float64 + // average packets per delta and key frame, or expFilterValueUndefined + packetsPerFrame float64 + packetsPerFrameKey float64 + width int + height int +} + +// bitsPerFrame returns the average kbits per frame (VCMFecMethod::BitsPerFrame). +func (p *adaptiveParams) bitsPerFrame() int { + frameRate := max(p.frameRate, 1) + return saturateInt(p.bitrateKbps / frameRate) +} + +// adaptiveProtectionFactors returns the Q8 delta and key frame protection +// factors relative to the number of media packets, which is what the encoder +// uses (VCMNackFecMethod::UpdateParameters). +func adaptiveProtectionFactors(p adaptiveParams) (delta uint8, key uint8) { + delta, key = protectionFactor(&p) + // Hybrid NACK/FEC: below kLowRttNackMs NACK alone recovers delta frames. + // Above it libwebrtc keeps the full rate (its RTT adjustment is 1.0). + if p.rttMs < lowRttNackMs { + delta = 0 + } + if bitRateTooLowForFec(&p) { + delta, key = 0, 0 + } + return convertFECRate(delta), convertFECRate(key) +} + +// protectionFactor ports VCMFecMethod::ProtectionFactor. The factors are +// relative to the total number of source and repair packets. +func protectionFactor(p *adaptiveParams) (codeRateDelta uint8, codeRateKey uint8) { + packetLoss := int(p.loss) + if packetLoss == 0 { + return 0, 0 + } + + // First partition protection: ~ 20% + const firstPartitionProt = 51 // 255 * 0.20 + // Threshold on packetLoss and bitRate/frameRate (=average #packets), + // above which protection covers at least the first partition. + const lossThr = 0 + const packetNumThr = 1 + // Parameters for the range of the rate index of the table. + const ratePar1 = 5 + const ratePar2 = 49 + + // Spatial resolution size, relative to a reference size. + width, height := p.width, p.height + if width <= 0 || height <= 0 { + width, height = adaptiveDefaultWidth, adaptiveDefaultHeight + } + spatialSizeToRef := float32(width*height) / float32(704*576) + // resolnFac generally increases/decreases the FEC rate (for a fixed bit + // rate and packet loss) based on system size, softened by an exponent < 1. + resolnFac := 1.0 / float32(math.Pow(float64(spatialSizeToRef), 0.3)) + + bitRatePerFrame := p.bitsPerFrame() + + // Average number of packets per frame (source and FEC). + avgTotPackets := saturateUint8(1.5 + float64(bitRatePerFrame)*1000.0/(8.0*adaptiveMaxPayloadSize)) + + // The table index is based on an effective rate; its range corresponds to + // ~200k to ~8000k bps at 30 fps. + effRateFecTable := int(saturateUint16(float64(resolnFac * float32(bitRatePerFrame)))) + rateIndexTable := max(min((effRateFecTable-ratePar1)/ratePar1, ratePar2), 0) + + // The table is defined for loss up to 50%. + if packetLoss >= packetLossMax { + packetLoss = packetLossMax - 1 + } + + // Protection factor for P frames. + delta := int(fecRateTable[rateIndexTable*packetLossMax+packetLoss]) + if packetLoss > lossThr && int(avgTotPackets) > packetNumThr { + // Set a minimum based on the first partition size. + delta = max(delta, firstPartitionProt) + } + // 50% is the max protection for P frames. + if delta >= packetLossMax { + delta = packetLossMax - 1 + } + + // Key frames are effectively at a higher rate, so scale/boost the rate. + packetFrameDelta := saturateUint8(0.5 + p.packetsPerFrame) + packetFrameKey := saturateUint8(0.5 + p.packetsPerFrameKey) + boostKey := boostCodeRateKey(packetFrameDelta, packetFrameKey) + + rateIndexTable = max(min(1+(boostKey*effRateFecTable-ratePar1)/ratePar1, ratePar2), 0) + indexTableKey := min(rateIndexTable*packetLossMax+packetLoss, fecRateTableSize-1) + + // Protection factor for I frames. + key := int(fecRateTable[indexTableKey]) + + // Boosting for key frames (_scaleProtKey = 2.0). + boostKeyProt := 2 * delta + if boostKeyProt >= packetLossMax { + boostKeyProt = packetLossMax - 1 + } + + // Key frame protection is at least the delta frame protection and at + // least the filtered packet loss. + key = max(packetLoss, boostKeyProt, key) + // 50% is the max protection for I frames. + if key >= packetLossMax { + key = packetLossMax - 1 + } + return uint8(delta), uint8(key) +} + +// boostCodeRateKey ports VCMFecMethod::BoostCodeRateKey. +func boostCodeRateKey(packetFrameDelta uint8, packetFrameKey uint8) int { + const boostRateKey = 2 + // Default: ratio scales the FEC protection up for I frames. + ratio := 1 + if packetFrameDelta > 0 { + ratio = int(packetFrameKey / packetFrameDelta) + } + return max(boostRateKey, ratio) +} + +// bitRateTooLowForFec ports VCMNackFecMethod::BitRateTooLowForFec, below which +// FEC is turned off regardless of reported packet loss. +func bitRateTooLowForFec(p *adaptiveParams) bool { + estimateBytesPerFrame := 1000 * p.bitsPerFrame() / 8 + maxBytesPerFrame := maxBytesPerFrameForFec + width, height := p.width, p.height + if width <= 0 || height <= 0 { + width, height = adaptiveDefaultWidth, adaptiveDefaultHeight + } + numPixels := width * height + if numPixels <= 352*288 { + maxBytesPerFrame = maxBytesPerFrameForFecLow + } else if numPixels > 640*480 { + maxBytesPerFrame = maxBytesPerFrameForFecHigh + } + return estimateBytesPerFrame < maxBytesPerFrame && adaptiveNumLayers < 3 && p.rttMs < maxRttTurnOffFecMs +} + +// convertFECRate ports VCMFecMethod::ConvertFECRate: the table defines rates +// relative to source plus repair packets, the encoder relative to source packets. +func convertFECRate(codeRate uint8) uint8 { + return saturateUint8(min(255, 0.5+255.0*float64(codeRate)/float64(255-int(codeRate)))) +} + +type lossSample struct { + lossPr255 uint8 + timeMs int64 +} + +// lossFilter ports the max-window filter (kMaxFilter) of +// VCMLossProtectionLogic: the max loss over 1 second windows, for the last +// lossPrHistorySize seconds. +type lossFilter struct { + history [lossPrHistorySize]lossSample + shortMax uint8 +} + +func newLossFilter() lossFilter { + f := lossFilter{} + for i := range f.history { + f.history[i].timeMs = -1 + } + return f +} + +// filteredLoss records a received loss sample and returns the filtered loss. +func (f *lossFilter) filteredLoss(nowMs int64, lossPr255 uint8) uint8 { + f.update(lossPr255, nowMs) + return f.max(nowMs) +} + +func (f *lossFilter) update(lossPr255 uint8, nowMs int64) { + if f.history[0].timeMs >= 0 && nowMs-f.history[0].timeMs < lossPrShortFilterWinMs { + f.shortMax = max(f.shortMax, lossPr255) + return + } + // Only add a new value to the history once a second. + if f.history[0].timeMs == -1 { + // First, no shift. + f.shortMax = lossPr255 + } else { + copy(f.history[1:], f.history[:lossPrHistorySize-1]) + } + if f.shortMax == 0 { + f.shortMax = lossPr255 + } + f.history[0] = lossSample{lossPr255: f.shortMax, timeMs: nowMs} + f.shortMax = 0 +} + +func (f *lossFilter) max(nowMs int64) uint8 { + maxFound := f.shortMax + for _, s := range f.history { + if s.timeMs == -1 || nowMs-s.timeMs > lossPrHistorySize*lossPrShortFilterWinMs { + // This sample (and all samples after this) is too old. + break + } + maxFound = max(maxFound, s.lossPr255) + } + return maxFound +} + +// expFilter ports rtc_base ExpFilter without a max limit. +type expFilter struct { + alpha float64 + filtered float64 +} + +func newExpFilter(alpha float64) expFilter { + return expFilter{alpha: alpha, filtered: expFilterValueUndefined} +} + +func (f *expFilter) apply(exp float64, sample float64) { + if f.filtered == expFilterValueUndefined { + f.filtered = sample + return + } + alpha := math.Pow(f.alpha, exp) + f.filtered = alpha*f.filtered + (1-alpha)*sample +} + +func saturateUint8(v float64) uint8 { + switch { + case math.IsNaN(v) || v <= 0: + return 0 + case v >= math.MaxUint8: + return math.MaxUint8 + default: + return uint8(v) + } +} + +func saturateUint16(v float64) uint16 { + switch { + case math.IsNaN(v) || v <= 0: + return 0 + case v >= math.MaxUint16: + return math.MaxUint16 + default: + return uint16(v) + } +} + +func saturateInt(v float64) int { + switch { + case math.IsNaN(v) || v <= 0: + return 0 + case v >= math.MaxInt32: + return math.MaxInt32 + default: + return int(v) + } +} diff --git a/pkg/sfu/flexfec/protection_test.go b/pkg/sfu/flexfec/protection_test.go new file mode 100644 index 000000000..2d9eeeaca --- /dev/null +++ b/pkg/sfu/flexfec/protection_test.go @@ -0,0 +1,265 @@ +// 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 ( + "fmt" + "testing" + "time" + + "github.com/pion/rtp" + "github.com/stretchr/testify/require" +) + +func TestProtectionFactorPercentConversion(t *testing.T) { + for _, tc := range []struct { + percent uint32 + factor uint8 + }{ + {0, 0}, {15, 38}, {25, 63}, {35, 89}, {40, 102}, {100, 255}, {101, 255}, + } { + require.Equal(t, tc.factor, ProtectionFactorFromPercent(tc.percent)) + require.Equal(t, min(tc.percent, MaxProtectionPercent), protectionFactorToPercent(tc.factor)) + } +} + +func TestAdaptiveProtectionFactorsMatchLibwebrtc(t *testing.T) { + // Expected values were computed from libwebrtc's fec_rate_table.h with an + // independent implementation of VCMNackFecMethod::UpdateParameters. + for _, tc := range []struct { + name string + loss uint8 + rttMs int64 + bitrateKbps float64 + frameRate float64 + width, height int + packetsPerFrame float64 + packetsPerFrameKey float64 + delta, key uint8 + }{ + {"10% loss", 26, 100, 1000, 30, 704, 576, 3, 15, 95, 255}, + {"low rtt is nack only for delta frames", 26, 10, 1000, 30, 704, 576, 3, 15, 0, 255}, + {"bit rate too low", 26, 100, 100, 30, 704, 576, 3, 15, 0, 0}, + {"no loss", 0, 100, 1000, 30, 704, 576, 3, 15, 0, 0}, + {"720p", 13, 50, 2500, 30, 1280, 720, 4, 20, 64, 170}, + {"high rtt keeps fec at low rate", 64, 300, 300, 15, 320, 180, 1, 4, 253, 255}, + {"loss above table range", 200, 100, 1500, 30, 640, 360, 2, 8, 253, 255}, + {"unknown resolution uses the default", 13, 50, 2500, 30, 0, 0, 4, 20, 0, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + delta, key := adaptiveProtectionFactors(adaptiveParams{ + loss: tc.loss, + rttMs: tc.rttMs, + bitrateKbps: tc.bitrateKbps, + frameRate: tc.frameRate, + packetsPerFrame: tc.packetsPerFrame, + packetsPerFrameKey: tc.packetsPerFrameKey, + width: tc.width, + height: tc.height, + }) + if tc.name == "unknown resolution uses the default" { + expectedDelta, expectedKey := adaptiveProtectionFactors(adaptiveParams{ + loss: tc.loss, rttMs: tc.rttMs, bitrateKbps: tc.bitrateKbps, frameRate: tc.frameRate, + packetsPerFrame: tc.packetsPerFrame, packetsPerFrameKey: tc.packetsPerFrameKey, + width: adaptiveDefaultWidth, height: adaptiveDefaultHeight, + }) + require.Equal(t, expectedDelta, delta) + require.Equal(t, expectedKey, key) + return + } + require.Equal(t, tc.delta, delta, "delta") + require.Equal(t, tc.key, key, "key") + }) + } +} + +func TestLossFilterKeepsMaxOverTenSeconds(t *testing.T) { + f := newLossFilter() + require.EqualValues(t, 10, f.filteredLoss(0, 10)) + require.EqualValues(t, 50, f.filteredLoss(500, 50), "max within the short window") + require.EqualValues(t, 50, f.filteredLoss(1000, 0)) + require.EqualValues(t, 50, f.filteredLoss(5000, 0)) + require.EqualValues(t, 50, f.filteredLoss(10_000, 0)) + // The window holding 50 was recorded at 1000ms and expires 10s later. + require.EqualValues(t, 50, f.filteredLoss(11_000, 0)) + require.EqualValues(t, 0, f.filteredLoss(12_000, 0)) + require.EqualValues(t, 20, f.filteredLoss(13_000, 20)) +} + +// adaptiveTestSender sends 30 fps frames of 5 packets at the given offset. +type adaptiveTestSender struct { + e *Encoder + now int64 + sn uint16 + ts uint32 +} + +func (s *adaptiveTestSender) sendFrames(t *testing.T, frames int, keyEvery int) (repairs int) { + t.Helper() + base := s.now + defer func() { s.now = base + int64(frames)*int64(time.Second)/30 }() + for i := range frames { + s.now = base + int64(i)*int64(time.Second)/30 + key := keyEvery != 0 && i%keyEvery == 0 + packets := 5 + if key { + packets = 25 + } + for j := range packets { + h := rtp.Header{Version: 2, SSRC: 1, PayloadType: 96, SequenceNumber: s.sn, Timestamp: s.ts, Marker: j == packets-1} + s.sn++ + repairs += len(s.e.encode(s.now, &h, make([]byte, 1000), key && j == 0)) + } + s.ts += 3000 + } + return repairs +} + +func TestEncoderAdaptiveProtection(t *testing.T) { + e := NewEncoder(testFECPT, testFECSSRC, nil) + start := int64(time.Hour) + e.mu.Lock() + e.protection = Protection{Mode: ProtectionAdaptive} + e.adaptive = newAdaptiveState(start) + e.mu.Unlock() + s := &adaptiveTestSender{e: e, now: start} + + require.Zero(t, s.sendFrames(t, 30, 0), "no repairs before a receiver report") + stats := NetworkStats{FractionLost: 26, RTT: 100 * time.Millisecond, Width: 1280, Height: 720} + e.onReceiverReport(s.now, stats) + delta, key := e.ProtectionFactors() + require.NotZero(t, delta) + require.GreaterOrEqual(t, key, delta) + require.Equal(t, protectionFactorToPercent(delta), e.OverheadPercent(), "reserve adaptive overhead") + require.NotZero(t, s.sendFrames(t, 30, 0)) + + // Loss subsides: protection is held by the 10 second max filter. + for range 9 { + s.sendFrames(t, 30, 0) + e.onReceiverReport(s.now, NetworkStats{RTT: stats.RTT, Width: stats.Width, Height: stats.Height}) + held, _ := e.ProtectionFactors() + require.Equal(t, delta, held) + } + for range 3 { + s.sendFrames(t, 30, 0) + e.onReceiverReport(s.now, NetworkStats{RTT: stats.RTT, Width: stats.Width, Height: stats.Height}) + } + delta, key = e.ProtectionFactors() + require.Zero(t, delta) + require.Zero(t, key) + require.Zero(t, e.OverheadPercent()) + require.Zero(t, s.sendFrames(t, 30, 0)) + + // At low RTT, NACK protects delta frames and FEC only key frames. + e.onReceiverReport(s.now, NetworkStats{FractionLost: 26, RTT: 5 * time.Millisecond, Width: 1280, Height: 720}) + delta, key = e.ProtectionFactors() + require.Zero(t, delta) + require.NotZero(t, key) + require.NotZero(t, s.sendFrames(t, 30, 10), "key frames are protected") + require.Zero(t, s.sendFrames(t, 9, 0), "delta frames are not protected") +} + +func TestEncoderMinimumProtection(t *testing.T) { + e := NewEncoder(testFECPT, testFECSSRC, nil) + floor := ProtectionFactorFromPercent(15) + e.SetProtection(Protection{Mode: ProtectionMinimum, Factor: floor}) + start := int64(time.Hour) + e.mu.Lock() + e.adaptive = newAdaptiveState(start) + e.mu.Unlock() + s := &adaptiveTestSender{e: e, now: start} + + delta, key := e.ProtectionFactors() + require.Equal(t, floor, delta) + require.Equal(t, floor, key) + require.EqualValues(t, 15, e.OverheadPercent()) + require.Equal(t, 30, s.sendFrames(t, 30, 0), "one repair for each 5 packet frame at the floor") + + e.onReceiverReport(s.now, NetworkStats{FractionLost: 26, RTT: 100 * time.Millisecond, Width: 1280, Height: 720}) + delta, _ = e.ProtectionFactors() + require.Greater(t, delta, floor, "rises adaptively with loss") + require.Greater(t, s.sendFrames(t, 30, 0), 30) + + for range 12 { + s.sendFrames(t, 30, 0) + e.onReceiverReport(s.now, NetworkStats{RTT: 100 * time.Millisecond, Width: 1280, Height: 720}) + } + delta, key = e.ProtectionFactors() + require.Equal(t, floor, delta, "returns to the floor once loss subsides") + require.Equal(t, floor, key) + require.EqualValues(t, 15, e.OverheadPercent()) +} + +func TestEncoderProtectionModes(t *testing.T) { + e := NewEncoder(testFECPT, testFECSSRC, nil) + report := NetworkStats{FractionLost: 26, RTT: 100 * time.Millisecond, Width: 1280, Height: 720} + for _, tc := range []struct { + protection Protection + want Protection + }{ + {Protection{Mode: ProtectionFixed, Factor: 63}, Protection{Mode: ProtectionFixed, Factor: 63}}, + {Protection{Mode: ProtectionDisabled, Factor: 63}, Protection{}}, + {Protection{Mode: ProtectionAdaptive, Factor: 63}, Protection{Mode: ProtectionAdaptive}}, + {Protection{Mode: ProtectionMinimum, Factor: 63}, Protection{Mode: ProtectionMinimum, Factor: 63}}, + {Protection{Mode: 99, Factor: 63}, Protection{}}, + } { + t.Run(fmt.Sprint(tc.protection.Mode), func(t *testing.T) { + e.SetProtection(tc.protection) + e.mu.Lock() + protection, hasAdaptive := e.protection, e.adaptive != nil + e.mu.Unlock() + require.Equal(t, tc.want, protection) + require.True(t, hasAdaptive, "the adaptive state is kept in every mode") + // Receiver reports only affect adaptive and minimum protection. + before, _ := e.ProtectionFactors() + e.OnReceiverReport(report) + after, _ := e.ProtectionFactors() + if !tc.want.usesAdaptive() { + require.Equal(t, before, after) + } + }) + } + e.Close() + e.OnReceiverReport(report) +} + +func TestEncoderAdaptiveStateTrackedInEveryMode(t *testing.T) { + for _, from := range []Protection{{}, {Mode: ProtectionFixed, Factor: 38}} { + t.Run(from.Mode.String(), func(t *testing.T) { + e := NewEncoder(testFECPT, testFECSSRC, nil) + start := int64(time.Hour) + e.mu.Lock() + e.adaptive = newAdaptiveState(start) + e.mu.Unlock() + e.SetProtection(from) + s := &adaptiveTestSender{e: e, now: start} + report := NetworkStats{FractionLost: 26, RTT: 100 * time.Millisecond, Width: 1280, Height: 720} + s.sendFrames(t, 30, 0) + e.onReceiverReport(s.now, report) + s.sendFrames(t, 30, 0) + e.onReceiverReport(s.now, NetworkStats{RTT: report.RTT, Width: report.Width, Height: report.Height}) + before, _ := e.ProtectionFactors() + require.Equal(t, from.Factor, before, "the override applies on top of the tracked adaptive rate") + + // Switching to adaptive starts from the loss history recorded so far, + // without waiting for another receiver report. + e.SetProtection(Protection{Mode: ProtectionAdaptive}) + delta, key := e.ProtectionFactors() + require.NotZero(t, delta) + require.GreaterOrEqual(t, key, delta) + require.NotZero(t, s.sendFrames(t, 30, 0)) + }) + } +} diff --git a/pkg/sfu/pacer/base.go b/pkg/sfu/pacer/base.go index 916e51d4f..d612cbead 100644 --- a/pkg/sfu/pacer/base.go +++ b/pkg/sfu/pacer/base.go @@ -90,7 +90,7 @@ func (b *Base) SendPacket(p *Packet) (int, error) { } if p.FEC != nil && written > 0 && !p.IsRTX && !p.IsProbe { - repair := p.FEC.Encode(p.Header, p.Payload) + repair := p.FEC.Encode(p.Header, p.Payload, p.IsKeyFrame) sent, payloadBytes, rtpBytes := 0, 0, 0 for i := range repair { packet := &repair[i] diff --git a/pkg/sfu/pacer/pacer.go b/pkg/sfu/pacer/pacer.go index b0c88d893..0cc3cb1a9 100644 --- a/pkg/sfu/pacer/pacer.go +++ b/pkg/sfu/pacer/pacer.go @@ -62,6 +62,8 @@ type Packet struct { PoolEntity *[]byte // FEC is set only on original video media, never padding, RTX or probes. FEC *flexfec.Encoder + // IsKeyFrame selects the key frame protection factor of FEC. + IsKeyFrame bool // per-packet scratch for header extensions held before Enqueue or patched at send time, // the Packet is owned by one send until SendPacket returns diff --git a/test/client/client.go b/test/client/client.go index 27b9a18c6..a323d6c4e 100644 --- a/test/client/client.go +++ b/test/client/client.go @@ -1435,6 +1435,12 @@ func (c *RTCClient) IsLocalCandidateRelaySelected() bool { return false } +// WriteSubscriberRTCP sends RTCP on the subscriber connection, for tests that +// report reception statistics themselves. +func (c *RTCClient) WriteSubscriberRTCP(packets []rtcp.Packet) error { + return c.subscriber.WriteRTCP(packets) +} + func (c *RTCClient) SendNacks(count int) { var packets []rtcp.Packet c.lock.Lock() diff --git a/test/flexfec_downstream_test.go b/test/flexfec_downstream_test.go index 268a6179b..2ed5ae2e3 100644 --- a/test/flexfec_downstream_test.go +++ b/test/flexfec_downstream_test.go @@ -28,6 +28,7 @@ import ( "testing" "time" + "github.com/pion/rtcp" "github.com/pion/rtp" "github.com/pion/sdp/v3" "github.com/pion/webrtc/v4" @@ -125,6 +126,8 @@ type fecLossRecorder struct { recovered map[uint16]bool // value reports a bit-exact match mediaPackets int fecPackets int + // highest media sequence number seen, including dropped packets + highestSeq uint16 } func newFECLossRecorder() *fecLossRecorder { @@ -189,6 +192,9 @@ func (r *fecLossRecorder) filter(pkt *rtp.Packet) bool { if err != nil { return true } + if r.mediaPackets == 0 || int16(pkt.SequenceNumber-r.highestSeq) > 0 { + r.highestSeq = pkt.SequenceNumber + } r.mediaPackets++ if r.dropEvery > 0 && r.mediaPackets%r.dropEvery == 0 { r.dropped[pkt.SequenceNumber] = raw @@ -235,6 +241,28 @@ 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. +func (r *fecLossRecorder) receiverReport() *rtcp.ReceiverReport { + r.mu.Lock() + defer r.mu.Unlock() + if r.mediaSSRC == 0 { + return nil + } + var fractionLost uint8 + if r.dropEvery > 0 { + fractionLost = uint8(256 / r.dropEvery) + } + return &rtcp.ReceiverReport{ + Reports: []rtcp.ReceptionReport{{ + SSRC: r.mediaSSRC, + FractionLost: fractionLost, + LastSequenceNumber: uint32(r.highestSeq), + }}, + } +} + // subscriberVideoSSRCs returns the media, FlexFEC and RTX SSRCs of the first // video m-section the SFU offered to the subscriber. func subscriberVideoSSRCs(sd *webrtc.SessionDescription) (media, fec, rtx uint32, err error) { @@ -276,17 +304,114 @@ func subscriberVideoSSRCs(sd *webrtc.SessionDescription) (media, fec, rtx uint32 return 0, 0, 0, fmt.Errorf("no FEC-FR ssrc-group in subscriber description") } -func sendFECSetting(t *testing.T, c *testclient.RTCClient, trackSID livekit.TrackID, level livekit.FECProtection) { +func fecDisabled() *livekit.FECProtection { + return &livekit.FECProtection{} +} + +func fecFixed(level livekit.FECProtectionLevel) *livekit.FECProtection { + return &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_FIXED, Level: level} +} + +func sendFECSetting(t *testing.T, c *testclient.RTCClient, trackSID livekit.TrackID, fec *livekit.FECProtection) { require.NoError(t, c.SendRequest(&livekit.SignalRequest{ Message: &livekit.SignalRequest_TrackSetting{ TrackSetting: &livekit.UpdateTrackSettings{ TrackSids: []string{string(trackSID)}, - Fec: level.Enum(), + Fec: fec, }, }, })) } +// fecDownstreamSession is a publisher sending the test VP8 track through the +// SFU to a FlexFEC-capable subscriber whose received packets are recorded. +type fecDownstreamSession struct { + sub *testclient.RTCClient + trackSID livekit.TrackID + // subscriber's remote description once FlexFEC was negotiated + offerSDP string + recorder *fecLossRecorder +} + +func startFlexFECDownstreamSession(t *testing.T) *fecDownstreamSession { + _, finish := setupFlexFECDownstreamTest(t.Name()) + t.Cleanup(finish) + + recorder := newFECLossRecorder() + pub := createRTCClient("fec_down_pub", fecDownstreamServerPort, testRTCServicePathv0, nil) + sub := createRTCClient("fec_down_sub", fecDownstreamServerPort, testRTCServicePathv0, &testclient.Options{ + AutoSubscribe: true, + EnableFlexFEC: true, + SubscriberRTPFilter: recorder.filter, + }) + t.Cleanup(func() { stopClients(pub, sub) }) + waitUntilConnected(t, pub, sub) + + writer, err := pub.AddFileTrack(writeFlexFECTestIVF(t, 900), "video", "fecdownvideo") + require.NoError(t, err) + t.Cleanup(writer.Stop) + + session := &fecDownstreamSession{sub: sub, recorder: recorder} + testutils.WithTimeout(t, func() string { + tracks := sub.SubscribedTracks()[pub.ID()] + if len(tracks) == 0 { + return "subscriber has not subscribed to the publisher's track" + } + _, session.trackSID = rtc.UnpackStreamID(tracks[0].StreamID()) + if session.trackSID == "" { + return "subscribed track has no track SID yet" + } + return "" + }) + + testutils.WithTimeout(t, func() string { + answer := sub.SubscriberLocalDescription() + if answer == nil || !strings.Contains(answer.SDP, "flexfec-03") { + return "subscriber did not negotiate flexfec-03" + } + sd := sub.SubscriberRemoteDescription() + media, fec, rtx, err := subscriberVideoSSRCs(sd) + if err != nil { + return err.Error() + } + recorder.setSSRCs(media, fec, rtx) + session.offerSDP = sd.SDP + return "" + }) + + done := make(chan struct{}) + t.Cleanup(func() { close(done) }) + go func() { + ticker := time.NewTicker(200 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-done: + return + case <-ticker.C: + if rr := recorder.receiverReport(); rr != nil { + _ = sub.WriteSubscriberRTCP([]rtcp.Packet{rr}) + } + } + } + }() + return session +} + +// measure drops every dropEvery-th media packet (none for 0) for duration and +// returns what the subscriber received and recovered in that window. +func (s *fecDownstreamSession) measure(dropEvery int, duration time.Duration) fecWindowResult { + s.recorder.startWindow(dropEvery) + time.Sleep(duration) + res := s.recorder.result() + logger.Infow("flexfec downstream window", "dropEvery", dropEvery, "result", fmt.Sprintf("%+v", res)) + return res +} + +func (s *fecDownstreamSession) setFEC(t *testing.T, fec *livekit.FECProtection) { + sendFECSetting(t, s.sub, s.trackSID, fec) +} + // TestFlexFECDownstreamRecovery publishes a VP8 track through the SFU to a // FlexFEC-capable subscriber and checks, with simulated downstream loss, that // the subscriber recovers dropped packets bit-exactly from the SFU's repairs @@ -297,71 +422,20 @@ func TestFlexFECDownstreamRecovery(t *testing.T) { return } - _, finish := setupFlexFECDownstreamTest("TestFlexFECDownstreamRecovery") - defer finish() + session := startFlexFECDownstreamSession(t) + sub, trackSID, offerSDP, measure := session.sub, session.trackSID, session.offerSDP, session.measure - recorder := newFECLossRecorder() - pub := createRTCClient("fec_down_pub", fecDownstreamServerPort, testRTCServicePathv0, nil) - sub := createRTCClient("fec_down_sub", fecDownstreamServerPort, testRTCServicePathv0, &testclient.Options{ - AutoSubscribe: true, - EnableFlexFEC: true, - SubscriberRTPFilter: recorder.filter, - }) - defer stopClients(pub, sub) - waitUntilConnected(t, pub, sub) - - writer, err := pub.AddFileTrack(writeFlexFECTestIVF(t, 900), "video", "fecdownvideo") - require.NoError(t, err) - defer writer.Stop() - - var trackSID livekit.TrackID - testutils.WithTimeout(t, func() string { - tracks := sub.SubscribedTracks()[pub.ID()] - if len(tracks) == 0 { - return "subscriber has not subscribed to the publisher's track" - } - _, trackSID = rtc.UnpackStreamID(tracks[0].StreamID()) - if trackSID == "" { - return "subscribed track has no track SID yet" - } - return "" - }) - - var offerSDP string - testutils.WithTimeout(t, func() string { - answer := sub.SubscriberLocalDescription() - if answer == nil || !strings.Contains(answer.SDP, "flexfec-03") { - return "subscriber did not negotiate flexfec-03" - } - sd := sub.SubscriberRemoteDescription() - media, fec, rtx, err := subscriberVideoSSRCs(sd) - if err != nil { - return err.Error() - } - recorder.setSSRCs(media, fec, rtx) - offerSDP = sd.SDP - return "" - }) - - measure := func(dropEvery int, duration time.Duration) fecWindowResult { - recorder.startWindow(dropEvery) - time.Sleep(duration) - res := recorder.result() - logger.Infow("flexfec downstream window", "dropEvery", dropEvery, "result", fmt.Sprintf("%+v", res)) - return res - } - - // FEC_NONE is the default: no repairs, and simulated loss is not recovered. + // FEC_MODE_DISABLED is the default: no repairs, and simulated loss is not recovered. res := measure(7, 3*time.Second) require.Greater(t, res.mediaPackets, 100, "media is not flowing") require.Zero(t, res.fecPackets, "repairs were sent before a preset was selected") require.NotZero(t, res.dropped) require.Zero(t, res.recovered, "dropped packets were recovered without FEC") - for _, level := range []livekit.FECProtection{ - livekit.FECProtection_FEC_LOW, - livekit.FECProtection_FEC_MEDIUM, - livekit.FECProtection_FEC_HIGH, + for _, level := range []*livekit.FECProtection{ + fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_LOW), + fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_MEDIUM), + fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH), } { sendFECSetting(t, sub, trackSID, level) testutils.WithTimeout(t, func() string { @@ -381,17 +455,98 @@ func TestFlexFECDownstreamRecovery(t *testing.T) { "%s: recovered %d of %d dropped packets", level, res.recovered, res.dropped) } - // Switching back to FEC_NONE stops repairs, still without renegotiation. - sendFECSetting(t, sub, trackSID, livekit.FECProtection_FEC_NONE) + // Switching back to FEC_MODE_DISABLED stops repairs, still without renegotiation. + sendFECSetting(t, sub, trackSID, fecDisabled()) testutils.WithTimeout(t, func() string { if measure(0, 500*time.Millisecond).fecPackets != 0 { - return "repairs continue after selecting FEC_NONE" + return "repairs continue after selecting FEC_MODE_DISABLED" } return "" }) require.Equal(t, offerSDP, sub.SubscriberRemoteDescription().SDP, "FEC preset changes renegotiated") } +// TestFlexFECDownstreamAdaptive checks, like libwebrtc's +// AdaptiveSendsNoFecWithoutLoss, that adaptive protection sends no repairs +// without loss. With loss it protects the test track, whose frames are all key +// frames: libwebrtc's low RTT rule leaves delta frames to NACK, not key frames. +func TestFlexFECDownstreamAdaptive(t *testing.T) { + if testing.Short() { + t.SkipNow() + return + } + + session := startFlexFECDownstreamSession(t) + session.setFEC(t, &livekit.FECProtection{Mode: livekit.FECProtectionMode_FEC_MODE_ADAPTIVE}) + res := session.measure(0, 3*time.Second) + require.Greater(t, res.mediaPackets, 100, "media is not flowing") + require.Zero(t, res.fecPackets, "adaptive protection sent repairs without loss") + + testutils.WithTimeout(t, func() string { + if session.measure(7, 500*time.Millisecond).fecPackets == 0 { + return "adaptive protection did not respond to reported loss" + } + return "" + }) + res = session.measure(7, 3*time.Second) + require.NotZero(t, res.dropped) + require.Zero(t, res.mismatched, "recovered packets differ from the originals") + require.GreaterOrEqual(t, res.recovered*100, res.dropped*90, + "recovered %d of %d dropped packets", res.recovered, res.dropped) + require.Equal(t, session.offerSDP, session.sub.SubscriberRemoteDescription().SDP, "FEC mode changes renegotiated") +} + +// TestFlexFECDownstreamMinimum checks, like libwebrtc's +// MinimumSendsFecWithoutLoss, that minimum protection keeps its level as a +// floor without loss, sending as many repairs as fixed protection at that +// level, and that it rises above the floor with loss. +func TestFlexFECDownstreamMinimum(t *testing.T) { + if testing.Short() { + t.SkipNow() + return + } + + session := startFlexFECDownstreamSession(t) + ratio := func(res fecWindowResult) float64 { + return float64(res.fecPackets) / float64(res.mediaPackets) + } + + session.setFEC(t, fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH)) + testutils.WithTimeout(t, func() string { + if session.measure(0, 300*time.Millisecond).fecPackets == 0 { + return "no repairs with fixed protection" + } + return "" + }) + fixed := session.measure(0, 3*time.Second) + require.Greater(t, fixed.mediaPackets, 100, "media is not flowing") + require.NotZero(t, fixed.fecPackets) + + session.setFEC(t, &livekit.FECProtection{ + Mode: livekit.FECProtectionMode_FEC_MODE_MINIMUM, + Level: livekit.FECProtectionLevel_FEC_LEVEL_HIGH, + }) + // let the change and in-flight packets settle + session.measure(0, 500*time.Millisecond) + minimum := session.measure(0, 3*time.Second) + require.Greater(t, minimum.mediaPackets, 100, "media is not flowing") + require.NotZero(t, minimum.fecPackets, "minimum protection sent no repairs without loss") + require.InDelta(t, ratio(fixed), ratio(minimum), 0.05, + "minimum protection without loss must match its level: fixed %+v, minimum %+v", fixed, minimum) + + // With loss, protection rises above the floor: every frame of the test + // track is a key frame, which the low RTT rule leaves to FEC. + session.measure(7, 500*time.Millisecond) + res := session.measure(7, 3*time.Second) + require.Greater(t, ratio(res), ratio(minimum)+0.1, + "minimum protection did not rise with loss: without loss %+v, with loss %+v", minimum, res) + require.NotZero(t, res.dropped) + require.Zero(t, res.mismatched, "recovered packets differ from the originals") + require.GreaterOrEqual(t, res.recovered*100, res.dropped*90, + "recovered %d of %d dropped packets", res.recovered, res.dropped) + require.Equal(t, session.offerSDP, session.sub.SubscriberRemoteDescription().SDP, "FEC mode changes renegotiated") +} + // TestFlexFECDownstreamNotNegotiated checks that a subscriber without FlexFEC // support receives media but no repairs, even when it selects a preset. func TestFlexFECDownstreamNotNegotiated(t *testing.T) { @@ -454,7 +609,7 @@ func TestFlexFECDownstreamNotNegotiated(t *testing.T) { mu.Unlock() _, trackSID := rtc.UnpackStreamID(track.StreamID()) - sendFECSetting(t, sub, trackSID, livekit.FECProtection_FEC_HIGH) + sendFECSetting(t, sub, trackSID, fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH)) time.Sleep(2 * time.Second) mu.Lock()