mirror of
https://github.com/livekit/livekit.git
synced 2026-12-04 04:58:22 +00:00
* Do not recover FlexFEC from RTX repaired packets A packet repaired from RTX takes its header from the RTX packet: libwebrtc adds a MID to retransmissions until the RTX SSRC is acknowledged, and sets abs-send-time and transport-cc at send time. The stored packet therefore differs from the media the publisher protected, so using it as a protected packet recovered the wrong length, failing with "invalid recovered packet size", or silently corrupted the recovered packet's header extensions when the length happened to match. Like libwebrtc's FlexfecReceiver, which skips packets recovered by RTX, mark RTX repaired sequence numbers and treat them as missing for FEC recovery. They are still forwarded and update NACK state as before. With a libwebrtc publisher at 10% upstream loss, every recovery attempt in a block containing a retransmitted packet failed; with retransmissions excluded recoveries succeed. * Move RTX repair tracking into BufferBase Keep the RTX repaired history, its lookup and the publisher sequence number extension in BufferBase, so every buffer built on it, such as the relay, can exclude RTX repaired packets from FlexFEC recovery the same way. The history is now cleared with the rest of the sequence number state when the stream restarts. Buffer only marks repaired packets from writeRTX. Packets recovered by FEC also enter with isRTX set, but they are exact reconstructions and stay usable, so marking is explicit rather than tied to that flag. * Keep RTX-repaired history safe with large packet caches The RTX repair history had 512 fixed slots. With a larger video packet cache, e.g. packet_buffer_size_video: 1500, two cached repairs could share a slot, the earlier mark was lost, and FlexFEC could recover from the altered retransmission. - Size the history from the video packet cache, at least 512 slots, and allocate it on the first repair. - When a later repair reuses a slot, the earlier packet counts as repaired: losing a recovery is better than corrupting one. - Do not mark a retransmission of a packet that is already cached. The bucket rejects it as a duplicate and keeps the exact packet, which stays usable for recovery. - Mark a repair before ingesting it and do not feed RTX repaired packets to the FEC decoder, as BufferBase now feeds ingested media to the decoder. * Generate downstream FlexFEC with per-track protection presets Generate FlexFEC-03 repairs for subscribed video tracks. Subscribers select none (default), low, medium or high through UpdateTrackSettings.fec; repairs require rtc.flexfec.downstream_enabled and negotiated flexfec-03 support. Generate repairs at each frame marker, splitting large frames into blocks of at most 48 packets, with upstream Q8 repair-count rounding and at least one repair per block. Reserve measured repair overhead during layer allocation and charge repair traffic to pacing, bandwidth estimation and metrics. Carry repair sequence state through the DownTrack GetState/SeedState handoff, apply subscriber settings from immutable snapshots, and preserve upstream FEC on shared sendrecv codec lists when downstream generation is disabled. This squashes the three commits of dc/feature/fec_down (38a67502,d269ac59,7b02897c) and rebases them onto master. Conflict resolution: - pacer.Packet keeps master's held-extension scratch next to the FEC field, and the DownTrack sets FEC on the pacer packet master now creates before adding extensions - DownTrackParams and subscriber config keep master's RTXBudget - configureSenderParams uses master's enableFlexFEC name - tests follow master: pion/transport v5 packetio, mid-less receivers skipped when restricting codecs, and settings compared by value since they are stored as merged snapshots Requires the UpdateTrackSettings.fec field from livekit/protocol#1794, which is not in the pinned protocol version yet. * Add end-to-end tests for downstream FlexFEC Publish a VP8 track through the SFU to a FlexFEC-capable subscriber, simulate downstream loss before the subscriber's receive buffer, and recover the dropped packets from the repairs actually sent, using the same FlexFEC-03 decoder as upstream recovery. RTX is dropped meanwhile so retransmissions cannot fill the gaps. The test checks that no repairs are sent before a preset is selected, that every preset recovers isolated losses bit-exactly, that presets change without renegotiation, and that a subscriber which declines flexfec-03 receives media but no repairs. Frames alternate between one and five packets, so repair counts match the Q8 rounding for both block sizes. The test client gains a subscriber RTP filter to simulate loss and accessors for the subscriber descriptions. The tests use their own ports so they can run next to a local server on the default ports. * Support downstream FEC protection modes Adopt the FECProtection message from livekit/protocol#1987: subscribers select a mode (disabled, adaptive, fixed, minimum) and a level (low, medium, high; unspecified is low) per track. As before, an update that omits fec keeps the previous setting. Unknown modes disable FEC and unknown levels are treated as unspecified. The modes follow libwebrtc's RtpParameters::fec_protection (webrtc-sdk/webrtc#329): - adaptive ports VCMNackFecMethod: the kFecRateTable lookup with a 10 second max-window loss filter, key frame boost, ConvertFECRate, NACK only delta frames below 20ms RTT, and BitRateTooLowForFec. Inputs are the subscriber's receiver reports, the sent bit and frame rates, and the forwarded layer's dimensions. - fixed uses the level for delta and key frames. - minimum uses the larger of the adaptive rate and the level. - the adaptive state is updated in every mode, so switching to adaptive or minimum starts from the current loss history, and a protection change keeps the group that is accumulating and protects it at the new rate. Key frames get their own protection factor, so pacer packets carry a key frame flag. Repairs are still generated per frame; multi-frame blocks (max_fec_frames) are not supported. The end-to-end tests report the simulated loss in receiver reports, since the test client sends none, and check that adaptive protection sends no repairs without loss and protects with loss, and that minimum protection matches its level without loss and rises with loss. Requires livekit/protocol#1987, which is not in the pinned protocol version yet. * Point protocol at livekit/protocol#1987 * Report loss before repair in receiver reports to publishers Receiver reports counted packets restored by RTX or recovered by FlexFEC as received, so as long as repairs kept up the reported fraction lost stayed at zero, even with 20% upstream loss. libwebrtc receivers exclude recovered packets from their receive statistics, and a publisher's loss-based protection depends on that: with no reported loss, FlexFEC backs off to almost no repairs. Packets that fill a loss through a repair are now counted separately, and receiver reports include them in the fraction and cumulative loss. Reordered packets that arrive on their own still cancel the loss. The fraction is also capped at 255, so a full loss no longer wraps to zero. With 20% simulated upstream loss from an Android publisher, the reported fraction lost goes from 0 to about 0.15, the FEC packets received over 30 seconds go from 64 to 204, and the packets recovered by FEC from 11 to 61. * Protect zeroed abs-send-time and TWCC in downstream FlexFEC The pacer encoded FEC after it had filled in abs-send-time and the transport-wide sequence number. libwebrtc generates FEC before its sender fills them in, and its FlexFEC receiver zeroes both in media packets before recovery. Packets recovered from SFU repairs therefore got wrong bytes in those extensions, and in the payload when the header lengths within a group differed, for example when only the first packet carried abs-capture-time. Zero both extensions after the media packet is written and before it is fed to the encoder. * Aggregate receiver report loss for adaptive FEC protection Adaptive and minimum protection fed the fraction lost of every reception report into the max-window loss filter. libwebrtc receivers can send a report with each NACK, so a report often covers only a few packets and its fraction lost is very noisy. With 10% random loss, single reports read up to 70%, and the filter kept the maximum. Derive loss from the cumulative counters instead and produce a sample only once it covers at least 20 expected packets, like libwebrtc's SendSideBandwidthEstimation::UpdatePacketsLost. The end-to-end tests now report cumulative loss and the extended highest sequence number in their receiver reports. * Report loss before repair only to FlexFEC publishers Counting repaired packets as lost in receiver reports applied to every publisher, so any publisher whose loss RTX repaired started to see that loss and its bandwidth estimate could back off sooner. Only FlexFEC protection needs loss before repair to choose its rate. Count repairs only for streams that negotiated flexfec-03, which requires FlexFEC to be enabled on the server. Other publishers keep receiving loss after repair, as before. * Keep the newest RTX repair mark of a history slot A late retransmission of an older packet that has aged out of the cache overwrote the slot of a newer repair sharing it. The newer repair, which carries the RTX packet's header, could then be used for FlexFEC recovery and corrupt the recovered packet. Keep the highest extended sequence number written to a slot until the stream restarts. isRTXRepairedLocked already treats an older packet in a slot with a newer mark as repaired. * Measure FEC overhead against all media The allocator scales the whole media bitrate by the measured repair overhead, but the overhead was measured against protected media only. With adaptive protection below 20 ms RTT only key frames are protected, so the ratio of key frame repairs to key frame media was applied to every frame, and the reservation could make the allocator lower the layer or pause the track although the bandwidth was sufficient. Count all non-padding media while any protection is active. * Keep the loss sample that closes a filter window The max-window loss filter, ported from libwebrtc, dropped the report that closes a one-second window when the window already had a maximum, so a loss spike arriving on the boundary never reached adaptive protection. Store the larger of the window's maximum and that sample. * Skip the encoder allocation check under the race detector CI runs the tests with -race and swaps sync.Mutex for go-deadlock, whose Lock allocates, so Encode allocated about once per call there. Check allocations only without the race detector, like the other allocation tests. * Bump protocol to v1.55.0 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * sfu: reserve measured FEC overhead only on the forwarded layer The measured repair overhead comes from the spatial layer being forwarded. On a low layer with one or two packets per frame it can be 60-100%, and applying it to every layer reserved the high layer at nearly twice its cost, so the allocator could stay on the low layer. Attribute measurements to the forwarded spatial layer, restarting them when forwarding starts, resumes or switches layers, and reserve the configured rate for the other layers. Also reallocate only when a reserved overhead moves by 5 points or more, or turns on or off, so that per-second measurements and adaptive protection do not re-run allocation on every receiver report. * buffer: gate upstream FlexFEC on an explicit flag A publisher PC registers flexfec-03 when only downstream FEC is enabled, because it can also carry subscriptions. Its buffers then got a FEC payload type, which reported loss before repair to the publisher and let the decoder start from the observed repair SSRC, although upstream FEC was disabled. Buffers now ignore the negotiated FlexFEC payload type unless the buffer factory enables upstream FlexFEC. * pacer: protect interceptor-written transport-cc as zeros in FEC With UseSendSideBWEInterceptor, Pion's TWCC header extension interceptor writes transport-cc during WriteRTP while the DownTrack leaves TransportWideExtID at zero. The extension was then protected with its non-zero value, which the receiver zeroes before recovery, so recovered packets got wrong bytes there. Pass the negotiated transport-cc ID to the pacer for FEC and zero it before encoding as well. * sfu: skip the FEC encoder while protection is disabled The encoder was attached whenever flexfec-03 was negotiated, including in the default disabled mode, so every forwarded packet took the encoder lock and updated the adaptive state without generating repairs. Pass the encoder to the pacer only while protection is enabled. Receiver reports still keep the loss history; adaptive protection measures media rates again once enabled. * sfu: account sent FEC repairs in the down track RTP stats Repairs were counted only in the aggregate Prometheus counter, so the down track's stats under-counted what the subscriber receives. Record them in the sender's FEC packet and byte counters, separate from media, and export the FEC counters in RTPStats for both directions. * rtc: merge subscriber FEC settings in one place The subscription merged and normalized settings, and the subscribed track merged and normalized them again, while the DownTrack mapped unknown modes and levels a third time. Merge only in the subscription, store the merged settings in the subscribed track as is, and leave unknown values to the DownTrack. * prometheus: resolve fixed-label FEC counters once RecordFECDownstream runs on the pacer path for every repair batch and looked up both counter vectors by label each time. * rtpstats: seed a sender without holding both locks Seed took the receiving sender's lock and then the source's, so two senders seeding from each other at the same time could deadlock. Copy the source's state under its own lock first, then apply the copy under the receiving sender's lock. * telemetry: count FlexFEC repairs in traffic totals Retransmissions and padding count towards node and participant traffic, but FEC repairs, which are also on the wire, did not. Add repairs sent and received to the node packet and byte totals, and to the packets and bytes of TrafficStats. Analytics streams are unchanged: AnalyticsStream has no FEC field. * sfu: read the FEC transport-cc ID atomically setRTPHeaderExtensions runs again when the stream allocator listener is set, which can happen while media is already forwarded, and WriteRTP read the ID without synchronization. Store it atomically once the extensions are processed. * telemetry: count only FEC repairs sent in node traffic Media recovered from FEC repairs is counted as received media, so adding the repairs received to node ingress counted recovered packets twice. Node traffic feeds room admission against limit.bytes_per_sec, so ingress must not be inflated. Keep repairs sent in node egress, where nothing is synthesized, and leave ingress as before. TrafficStats is derived from RTPStats without a direction, so it cannot tell repairs sent from repairs received; leave it without FEC. * rtc: add WebRTCConfig.SetFlexFEC for per-session FlexFEC settings * rtc: apply a session's upstream FlexFEC to its buffers SetFlexFEC changed what a session negotiates with its publisher, but the publisher's buffers still followed the node config: the room's buffer factory read it once. A session with upstream on and a node with it off negotiated flexfec-03, so the publisher sent repairs that its buffers ignored; the reverse turned on upstream recovery and loss reported before repair for a session that asked for neither. The session's buffer factory now follows the session's upstream setting, whichever of SetFlexFEC and SetBufferFactory comes first. Without a SetFlexFEC call it follows the node config, as before. The setting applies to buffers the factory creates afterwards, so SetFlexFEC is meant to be called while the session is set up, before any track is published. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Jules Testard <jules.testard@livekit.io> Co-authored-by: David Chen <chenosaurus@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
644 lines
20 KiB
Go
644 lines
20 KiB
Go
// 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 test
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/binary"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/pion/rtcp"
|
|
"github.com/pion/rtp"
|
|
"github.com/pion/sdp/v3"
|
|
"github.com/pion/webrtc/v4"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/livekit/mediatransportutil/pkg/rtcconfig"
|
|
"github.com/livekit/protocol/livekit"
|
|
"github.com/livekit/protocol/logger"
|
|
|
|
"github.com/livekit/livekit-server/pkg/config"
|
|
"github.com/livekit/livekit-server/pkg/rtc"
|
|
"github.com/livekit/livekit-server/pkg/service"
|
|
"github.com/livekit/livekit-server/pkg/sfu/flexfec"
|
|
"github.com/livekit/livekit-server/pkg/testutils"
|
|
testclient "github.com/livekit/livekit-server/test/client"
|
|
)
|
|
|
|
// fecDownstreamServerPort keeps these tests clear of a server running on the
|
|
// default ports.
|
|
const fecDownstreamServerPort = 17880
|
|
|
|
func setupFlexFECDownstreamTest(name string) (*service.LivekitServer, func()) {
|
|
logger.Infow("----------------STARTING TEST----------------", "test", name)
|
|
s := createSingleNodeServer(func(conf *config.Config) {
|
|
conf.Port = fecDownstreamServerPort
|
|
conf.RTC.UDPPort = rtcconfig.PortRange{Start: fecDownstreamServerPort + 1}
|
|
conf.RTC.TCPPort = fecDownstreamServerPort + 2
|
|
conf.RTC.FlexFEC = config.FlexFECConfig{
|
|
DownstreamEnabled: true,
|
|
}
|
|
})
|
|
go func() {
|
|
if err := s.Start(); err != nil {
|
|
logger.Errorw("server returned error", err)
|
|
}
|
|
}()
|
|
|
|
waitForServerToStart(s)
|
|
|
|
return s, func() {
|
|
s.Stop(true)
|
|
logger.Infow("----------------FINISHING TEST----------------", "test", name)
|
|
}
|
|
}
|
|
|
|
// writeFlexFECTestIVF writes a VP8 IVF file whose frames alternate between a
|
|
// single RTP packet and several, so repairs cover both one-packet and
|
|
// multi-packet blocks.
|
|
func writeFlexFECTestIVF(t *testing.T, numFrames int) string {
|
|
var buf bytes.Buffer
|
|
header := make([]byte, 32)
|
|
copy(header[0:4], "DKIF")
|
|
binary.LittleEndian.PutUint16(header[6:8], 32)
|
|
copy(header[8:12], "VP80")
|
|
binary.LittleEndian.PutUint16(header[12:14], 640)
|
|
binary.LittleEndian.PutUint16(header[14:16], 480)
|
|
binary.LittleEndian.PutUint32(header[16:20], 30) // timebase denominator
|
|
binary.LittleEndian.PutUint32(header[20:24], 1) // timebase numerator
|
|
binary.LittleEndian.PutUint32(header[24:28], uint32(numFrames))
|
|
buf.Write(header)
|
|
|
|
for i := 0; i < numFrames; i++ {
|
|
size := 5
|
|
if i%2 == 1 {
|
|
size = 5000
|
|
}
|
|
// a leading zero byte marks a VP8 key frame, the rest is filler
|
|
frame := bytes.Repeat([]byte{0xff}, size)
|
|
frame[0] = 0
|
|
frameHeader := make([]byte, 12)
|
|
binary.LittleEndian.PutUint32(frameHeader[0:4], uint32(size))
|
|
binary.LittleEndian.PutUint64(frameHeader[4:12], uint64(i))
|
|
buf.Write(frameHeader)
|
|
buf.Write(frame)
|
|
}
|
|
|
|
path := filepath.Join(t.TempDir(), "flexfec.ivf")
|
|
require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600))
|
|
return path
|
|
}
|
|
|
|
// fecLossRecorder drops every n-th media packet before the subscriber's
|
|
// receive buffer and recovers the dropped packets from the repairs the SFU
|
|
// actually sent, using the same FlexFEC-03 decoder as upstream recovery. RTX
|
|
// is dropped while loss is simulated, so retransmissions cannot fill the gaps.
|
|
type fecLossRecorder struct {
|
|
mu sync.Mutex
|
|
|
|
mediaSSRC, fecSSRC, rtxSSRC uint32
|
|
dropEvery int
|
|
|
|
decoder *flexfec.Decoder
|
|
received map[uint16][]byte
|
|
dropped map[uint16][]byte
|
|
recovered map[uint16]bool // value reports a bit-exact match
|
|
mediaPackets int
|
|
fecPackets int
|
|
// highest media sequence number seen, including dropped packets
|
|
highestSeq uint16
|
|
// sequence number cycles and media packets dropped since the start,
|
|
// for the cumulative counters of receiver reports
|
|
seqCycles uint32
|
|
totalLost uint32
|
|
}
|
|
|
|
func newFECLossRecorder() *fecLossRecorder {
|
|
r := &fecLossRecorder{}
|
|
r.startWindow(0)
|
|
return r
|
|
}
|
|
|
|
func (r *fecLossRecorder) setSSRCs(media, fec, rtx uint32) {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.mediaSSRC, r.fecSSRC, r.rtxSSRC = media, fec, rtx
|
|
r.resetLocked()
|
|
}
|
|
|
|
// startWindow resets the counters and sets the simulated loss pattern.
|
|
func (r *fecLossRecorder) startWindow(dropEvery int) {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.dropEvery = dropEvery
|
|
r.resetLocked()
|
|
}
|
|
|
|
func (r *fecLossRecorder) resetLocked() {
|
|
r.received = make(map[uint16][]byte)
|
|
r.dropped = make(map[uint16][]byte)
|
|
r.recovered = make(map[uint16]bool)
|
|
r.mediaPackets = 0
|
|
r.fecPackets = 0
|
|
r.decoder = flexfec.NewDecoder(r.fecSSRC, r.mediaSSRC, func(sn uint16, dst []byte) (int, error) {
|
|
raw, ok := r.received[sn]
|
|
if !ok {
|
|
return 0, errors.New("media packet not received")
|
|
}
|
|
if len(dst) < len(raw) {
|
|
return 0, io.ErrShortBuffer
|
|
}
|
|
return copy(dst, raw), nil
|
|
}, logger.GetLogger())
|
|
}
|
|
|
|
func (r *fecLossRecorder) filter(pkt *rtp.Packet) bool {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
switch {
|
|
case r.mediaSSRC == 0:
|
|
return true
|
|
case pkt.SSRC == r.fecSSRC:
|
|
r.fecPackets++
|
|
r.decodeLocked(pkt)
|
|
return true
|
|
case pkt.SSRC == r.rtxSSRC:
|
|
return r.dropEvery == 0
|
|
case pkt.SSRC != r.mediaSSRC:
|
|
return true
|
|
}
|
|
if _, ok := r.dropped[pkt.SequenceNumber]; ok {
|
|
// a retransmission on the media SSRC must not undo the loss
|
|
return false
|
|
}
|
|
raw, err := pkt.Marshal()
|
|
if err != nil {
|
|
return true
|
|
}
|
|
if r.mediaPackets == 0 || int16(pkt.SequenceNumber-r.highestSeq) > 0 {
|
|
if pkt.SequenceNumber < r.highestSeq {
|
|
r.seqCycles++
|
|
}
|
|
r.highestSeq = pkt.SequenceNumber
|
|
}
|
|
r.mediaPackets++
|
|
if r.dropEvery > 0 && r.mediaPackets%r.dropEvery == 0 {
|
|
r.dropped[pkt.SequenceNumber] = raw
|
|
r.totalLost++
|
|
return false
|
|
}
|
|
r.received[pkt.SequenceNumber] = raw
|
|
r.decodeLocked(pkt)
|
|
return true
|
|
}
|
|
|
|
func (r *fecLossRecorder) decodeLocked(pkt *rtp.Packet) {
|
|
for _, rp := range r.decoder.DecodeFEC(pkt.Clone()) {
|
|
original, ok := r.dropped[rp.SequenceNumber]
|
|
if !ok {
|
|
continue
|
|
}
|
|
raw, err := rp.Marshal()
|
|
r.recovered[rp.SequenceNumber] = err == nil && bytes.Equal(raw, original)
|
|
if err == nil {
|
|
// a recovered packet can complete the next repair
|
|
r.received[rp.SequenceNumber] = raw
|
|
}
|
|
}
|
|
}
|
|
|
|
type fecWindowResult struct {
|
|
mediaPackets, fecPackets, dropped, recovered, mismatched int
|
|
}
|
|
|
|
func (r *fecLossRecorder) result() fecWindowResult {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
res := fecWindowResult{
|
|
mediaPackets: r.mediaPackets,
|
|
fecPackets: r.fecPackets,
|
|
dropped: len(r.dropped),
|
|
}
|
|
for _, exact := range r.recovered {
|
|
res.recovered++
|
|
if !exact {
|
|
res.mismatched++
|
|
}
|
|
}
|
|
return res
|
|
}
|
|
|
|
// receiverReport reports the simulated loss for the media SSRC. The test
|
|
// client does not send receiver reports itself, so the test reports what a
|
|
// receiver would see, as input for adaptive protection. The SFU derives loss
|
|
// from the cumulative counters, so they must reflect the dropped packets.
|
|
func (r *fecLossRecorder) receiverReport() *rtcp.ReceiverReport {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
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,
|
|
TotalLost: r.totalLost,
|
|
LastSequenceNumber: r.seqCycles<<16 | 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) {
|
|
if sd == nil {
|
|
return 0, 0, 0, fmt.Errorf("no subscriber description")
|
|
}
|
|
parsed := &sdp.SessionDescription{}
|
|
if err = parsed.Unmarshal([]byte(sd.SDP)); err != nil {
|
|
return 0, 0, 0, err
|
|
}
|
|
for _, md := range parsed.MediaDescriptions {
|
|
if md.MediaName.Media != "video" {
|
|
continue
|
|
}
|
|
for _, attr := range md.Attributes {
|
|
if attr.Key != "ssrc-group" {
|
|
continue
|
|
}
|
|
fields := strings.Fields(attr.Value)
|
|
if len(fields) != 3 {
|
|
continue
|
|
}
|
|
base, err1 := strconv.ParseUint(fields[1], 10, 32)
|
|
other, err2 := strconv.ParseUint(fields[2], 10, 32)
|
|
if err1 != nil || err2 != nil {
|
|
continue
|
|
}
|
|
switch fields[0] {
|
|
case "FEC-FR":
|
|
media, fec = uint32(base), uint32(other)
|
|
case "FID":
|
|
rtx = uint32(other)
|
|
}
|
|
}
|
|
if media != 0 {
|
|
return media, fec, rtx, nil
|
|
}
|
|
}
|
|
return 0, 0, 0, fmt.Errorf("no FEC-FR ssrc-group in subscriber description")
|
|
}
|
|
|
|
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: 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
|
|
// once it selects a FEC preset, and that presets change without renegotiation.
|
|
func TestFlexFECDownstreamRecovery(t *testing.T) {
|
|
if testing.Short() {
|
|
t.SkipNow()
|
|
return
|
|
}
|
|
|
|
session := startFlexFECDownstreamSession(t)
|
|
sub, trackSID, offerSDP, measure := session.sub, session.trackSID, session.offerSDP, session.measure
|
|
|
|
// 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{
|
|
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 {
|
|
if measure(0, 300*time.Millisecond).fecPackets == 0 {
|
|
return fmt.Sprintf("no repairs after selecting %s", level)
|
|
}
|
|
return ""
|
|
})
|
|
|
|
res = measure(7, 3*time.Second)
|
|
require.Greater(t, res.fecPackets, 0, level.String())
|
|
require.NotZero(t, res.dropped, level.String())
|
|
require.Zero(t, res.mismatched, "%s: recovered packets differ from the originals", level)
|
|
// isolated single losses are recoverable at every preset, since each
|
|
// frame or block carries at least one repair
|
|
require.GreaterOrEqual(t, res.recovered*100, res.dropped*90,
|
|
"%s: recovered %d of %d dropped packets", level, res.recovered, res.dropped)
|
|
}
|
|
|
|
// 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_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) {
|
|
if testing.Short() {
|
|
t.SkipNow()
|
|
return
|
|
}
|
|
|
|
_, finish := setupFlexFECDownstreamTest("TestFlexFECDownstreamNotNegotiated")
|
|
defer finish()
|
|
|
|
// counts packets that are neither media nor RTX once the SSRCs are known
|
|
var mu sync.Mutex
|
|
var mediaSSRC, rtxSSRC uint32
|
|
var mediaPackets, unexpected int
|
|
filter := func(pkt *rtp.Packet) bool {
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
switch {
|
|
case mediaSSRC == 0:
|
|
case pkt.SSRC == mediaSSRC:
|
|
mediaPackets++
|
|
case pkt.SSRC != rtxSSRC:
|
|
unexpected++
|
|
}
|
|
return true
|
|
}
|
|
|
|
pub := createRTCClient("nofec_down_pub", fecDownstreamServerPort, testRTCServicePathv0, nil)
|
|
sub := createRTCClient("nofec_down_sub", fecDownstreamServerPort, testRTCServicePathv0, &testclient.Options{
|
|
AutoSubscribe: true,
|
|
SubscriberRTPFilter: filter,
|
|
})
|
|
defer stopClients(pub, sub)
|
|
waitUntilConnected(t, pub, sub)
|
|
|
|
writer, err := pub.AddStaticTrack("video/vp8", "video", "nofecdownvideo")
|
|
require.NoError(t, err)
|
|
defer writer.Stop()
|
|
|
|
var track *webrtc.TrackRemote
|
|
testutils.WithTimeout(t, func() string {
|
|
tracks := sub.SubscribedTracks()[pub.ID()]
|
|
if len(tracks) == 0 || sub.BytesReceived() == 0 {
|
|
return "subscriber has not received media"
|
|
}
|
|
track = tracks[0]
|
|
return ""
|
|
})
|
|
// the SFU offers flexfec-03, the subscriber declines it
|
|
answer := sub.SubscriberLocalDescription()
|
|
require.NotNil(t, answer)
|
|
require.NotContains(t, answer.SDP, "flexfec-03")
|
|
sd := sub.SubscriberRemoteDescription()
|
|
require.NotNil(t, sd)
|
|
|
|
mu.Lock()
|
|
mediaSSRC = uint32(track.SSRC())
|
|
rtxSSRC = subscriberRTXSSRC(sd, mediaSSRC)
|
|
mu.Unlock()
|
|
|
|
_, trackSID := rtc.UnpackStreamID(track.StreamID())
|
|
sendFECSetting(t, sub, trackSID, fecFixed(livekit.FECProtectionLevel_FEC_LEVEL_HIGH))
|
|
time.Sleep(2 * time.Second)
|
|
|
|
mu.Lock()
|
|
defer mu.Unlock()
|
|
require.Greater(t, mediaPackets, 50, "media stopped after selecting a preset")
|
|
require.Zero(t, unexpected, "packets on an unexpected SSRC, likely repairs")
|
|
}
|
|
|
|
// subscriberRTXSSRC returns the RTX SSRC paired with media, or 0.
|
|
func subscriberRTXSSRC(sd *webrtc.SessionDescription, media uint32) uint32 {
|
|
prefix := fmt.Sprintf("a=ssrc-group:FID %d ", media)
|
|
for _, line := range strings.Split(sd.SDP, "\r\n") {
|
|
if rest, ok := strings.CutPrefix(line, prefix); ok {
|
|
rtx, err := strconv.ParseUint(strings.TrimSpace(rest), 10, 32)
|
|
if err == nil {
|
|
return uint32(rtx)
|
|
}
|
|
}
|
|
}
|
|
return 0
|
|
}
|