Skip to content

Add RtpParameters::fec_protection to control FEC per sender at runtime - #329

Merged
cloudwebrtc merged 22 commits into
m150_releasefrom
duan/rtp-fec-protection
Nov 9, 2026
Merged

cloudwebrtc merged 22 commits into
m150_releasefrom
duan/rtp-fec-protection

Conversation

@cloudwebrtc

@cloudwebrtc cloudwebrtc commented Nov 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

FlexFEC works in libwebrtc today, but the only way to set how much protection a sender generates is to replace the whole FecControllerFactory. That factory is process-wide, so it cannot be set per track or changed at runtime. livekit/rust-sdks#1424 does exactly that, using a custom controller, a global singleton and a private x-livekit-fec-rate fmtp parameter.

This PR adds a sender-level policy, RtpParameters::fec_protection, so every SDK can control FEC through the existing RtpSender::SetParameters():

  • Set per sender (per track).
  • Change at runtime. This does not reconfigure the encoder, recreate the send stream or renegotiate SDP.
  • No custom FEC controller factory needed.
  • Unset (std::nullopt) keeps the current behavior exactly.

API

struct RtpFecProtection {
  enum class Mode { kAdaptive, kFixed, kMinimum, kDisabled };
  Mode mode = Mode::kAdaptive;
  double protection_factor = 0.0;                     // [0.0, 1.0]
  std::optional<double> key_frame_protection_factor;  // defaults to protection_factor
  std::optional<int> max_fec_frames;                  // [1, 6]
};

struct RtpParameters {
  ...
  std::optional<RtpFecProtection> fec_protection;     // video senders only
};

The field lives on RtpParameters, not on the encodings, because a send stream has a single FecController. Which streams it affects depends on the FEC scheme:

  • ULPFEC is generated per stream, so with simulcast the policy applies to every layer.
  • FlexFEC protects a single media stream. libwebrtc does not allocate a FlexFEC SSRC for simulcast senders, so FlexFEC, and with it the policy, normally only takes effect without simulcast.

Modes

All modes run the adaptive computation first, so loss filters and other internal state keep updating and switching back to kAdaptive is seamless. The override is then applied on top of the result. A mode takes effect only when FEC was negotiated. Bitrate yielding is unchanged: the encoder target still subtracts the FEC and NACK overhead actually sent, capped at 50%.

kFixed kMinimum
FEC rate always protection_factor (replaces adaptive) max(adaptive, protection_factor)
When loss increases unchanged, so protection can fall short rises with loss, following the loss table
With no loss keeps the configured rate drops to the floor, no lower
Low-RTT rule (NackFec, RTT < 20 ms turns off delta FEC) bypassed limited to the floor, never reaches 0
BitRateTooLowForFec bypassed limited to the floor
max_fec_frames unset 1 (each frame its own block, lowest recovery delay) adaptive value
Overhead fixed requested rate; the actual ratio is rounded per block (see below) varies with loss
Suited for a fixed requested rate, A/B testing, or when the application or SFU computes the rate a baseline protection that strengthens automatically on bad networks

Example with protection_factor = 0.1 (Q8 value 26):

Scenario Adaptive kFixed kMinimum
0% loss 0 26 26
25% loss, RTT 100 ms e.g. 80 26 80
NACK+FEC, RTT 10 ms 0 26 26

Notes:

  • The adaptive loss is max-filtered over a window, so after loss stops kMinimum decays to the floor with a delay. kFixed has no such delay.
  • kDisabled sets both delta and key rates to 0, so FEC can be paused without renegotiation. The FEC SSRC and the FlexfecReceiveStream stay alive. FEC sequence numbers only advance when packets are sent, so receivers see no gap when protection resumes.
  • New parameters take effect on the next media packet (UlpfecGenerator::pending_params_). A block that is already accumulating is encoded with the new rate, so one block can span both settings. This is harmless: it only changes how many FEC packets that block gets.
  • The rate is a request, not a cap on the resulting overhead. ForwardErrorCorrection::NumFecPackets rounds the FEC count to whole packets per block, with at least one FEC packet for any nonzero rate. With protection_factor = 0.1, blocks of 1 / 2 / 10 media packets get 100% / 50% / 10% packet overhead. A larger max_fec_frames lets blocks grow, at the cost of up to max_fec_frames frames of recovery delay.

Call chain

RtpSender::SetParameters → WebRtcVideoSendStream::SetRtpParameters (applies only when the value changed, without reconfiguring the encoder) → VideoSendStream::SetFecProtection → VideoSendStreamImpl → RtpVideoSender → FecController::SetProtectionOverride → FecControllerDefault.

  • FecController::SetProtectionOverride and VideoSendStream::SetFecProtection have default no-op implementations, so existing custom controllers and fake streams keep compiling.
  • The FEC controller only applies the policy in UpdateFecRates, which normally runs when the bandwidth estimate changes, and on a stable network that may not happen for a long time. So VideoSendStreamImpl::SetFecProtection re-registers with the bitrate allocator, which recomputes the allocation with the last estimate, loss and RTT. A change therefore takes effect right away, including the resulting encoder target rate.
    • Not while the encoder is timed out (e.g. the camera stopped producing frames): the stream was removed from the allocator, and re-adding it would reserve bandwidth for an idle sender. The stored policy applies when encoding resumes.
  • When the send stream is recreated (codec switch, encoder selector or frame encryptor change), the policy is re-applied.
  • FecController implementations that do not override SetProtectionOverride ignore the policy: it is accepted and returned by GetParameters() but has no effect. Custom controllers need to implement it.
  • A value set before negotiation (ssrc == 0) is stored in init_parameters_ and applied in SetSsrc, the same way degradation_preference is handled.
  • Validation:
    • Factors outside [0, 1] or max_fec_frames outside [1, 6] return INVALID_RANGE.
    • Setting the field on an audio sender returns INVALID_PARAMETER.

Testing

Run in out/test (mac arm64, release):

  • modules_unittests: 5 new ProtectionBitrateCalculatorTest cases (fixed ignores low RTT, disabled overrides loss, minimum keeps the higher rate, reset restores adaptive, override requires FEC). All 193 FEC-related tests pass.

  • rtc_media_unittests: SetRtpSendParametersFecProtection (forwarded to the send stream with no encoder reconfiguration or stream recreation, deduplicated) and SetRtpSendParametersInvalidFecProtection pass.

  • pc_rtp_sender_receiver_unittest_bin: all 110 pass, including AudioSenderCantSetFecProtection and VideoSenderFecProtectionMovedAfterNegotiation.

  • video_video_send_stream_impl_unittest_bin: all 34 pass, including ForwardsFecProtectionToRtpVideoSender, FecProtectionChangeRecomputesAllocationWhenRunning and FecProtectionChangeDoesNotReRegisterTimedOutSender. The timeout test was verified to fail without the fix.

  • modules_unittests: UlpfecGeneratorTest.FixedRateIsQuantizedWithOneFecPacketFloor pins the FEC count for a 0.1 rate (1 / 2 / 10 / 20 media packets → 1 / 1 / 1 / 2 FEC packets).

  • pc_rtp_fec_protection_integrationtest_bin (new, end to end): two PeerConnections negotiate FlexFEC and the FEC actually sent is checked through outbound-rtp and inbound-rtp stats. 8 tests pass, with no flakes over repeated runs:

    • adaptive sends no FEC without loss;
    • kFixed sends FEC that the receiver gets, and kDisabled stops it;
    • kMinimum keeps a floor without loss;
    • a factor of 0.9 sends more than twice the FEC ratio of 0.1 (0.48 vs 0.19);
    • a policy set before negotiation is applied;
    • clearing the policy round-trips;
    • invalid values and audio senders are rejected.

    These tests found that a policy change did not apply on a stable network until the next bandwidth estimate change; that is fixed as described in the call chain above.

8 WebRtcVoiceEngineTestFake tests fail in rtc_media_unittests: an AGC mode expectation (0 vs 2) and unexpected ADM mock calls. This PR does not touch the voice engine; I believe these failures already exist on m150_release, but I have not confirmed it on a clean build.

outbound-rtp FEC stats

The second commit adds the non-standard fecPacketsSent, fecBytesSent and fecSsrc fields to RTCOutboundRtpStreamStats, mirroring the inbound-rtp FEC stats that already exist.

  • The values come from the FlexFEC substream of VideoSendStream::Stats.
  • They are reported only on the media stream that the FlexFEC stream protects.
  • They appear once the first FEC packet has been sent, since the FlexFEC substream stats are created lazily. With the default adaptive policy and no loss, they are absent.
  • As before, FEC packets and bytes are also counted in packetsSent and bytesSent.

ObjC and Android bindings

The third commit adds the bindings:

  • ObjC: a new RTCRtpFecProtection class (mode, protectionFactor, keyFrameProtectionFactor, maxFecFrames) and RTCRtpParameters.fecProtection.
  • Android: RtpParameters.FecProtection, the RtpParameters.FecProtectionMode enum, RtpParameters.fecProtection, and JNI conversion in both directions. The enum is a direct member of RtpParameters because jni_zero supports only one level of nesting. A doubly nested FecProtection.Mode resolved to the wrong class path (RtpParameters$Mode), which broke native-to-Java conversion in getParameters().

Both SDKs rebuild the native RtpParameters from their own fields on setParameters. Without these bindings, any setParameters call from ObjC or Android would also clear a policy that was set natively.

Testing (stats and bindings)

  • rtc_media_unittests: all 279 WebRtcVideoChannel* tests pass. GetStatsReportsTransmittedAndRetransmittedBytesAndPacketsCorrectly now also checks that FEC stats appear only on the protected stream.
  • pc_rtc_stats_collector_unittest_bin: all 120 pass. CollectRTCOutboundRtpStreamStats_Video now covers the FEC fields.
  • pc_rtc_stats_integrationtest_bin: all 17 pass. The FEC fields are verified as undefined when FlexFEC is not negotiated.
  • ObjC: the binding compiles for mac. The new RTCRtpParametersTest.mm (round trip in both directions) passes a syntax-only compile with the build flags, but it has not been run, because the XCTest target is iOS-only.
  • Android: this has not been built or run here, because there is no Android toolchain locally.
    • RtpParameters.java compiles with javac.
    • The JNI function names, class paths and the FecProtection constructor descriptor were verified against a header generated by jni_zero; they match the descriptors javac emits (RtpParameters$FecProtectionMode).
    • rtp_parameters.cc has no errors of its own in a host syntax-only compile.
    • A null FecProtection.mode is treated as ADAPTIVE instead of throwing a NullPointerException from the native call.
    • The new instrumentation tests RtpSenderTest.testSetFecProtection and testSetFecProtectionWithNullMode still need to run in CI or on a device.

Follow-ups (not in this PR)

  • Migrate rust-sdks to this API and remove LkFecControllerFactory, FecGlobalState and x-livekit-fec-rate.

cloudwebrtc and others added 5 commits November 3, 2026 20:54
Adds a non-standard, sender-wide RtpFecProtection policy (kAdaptive,
kFixed, kMinimum, kDisabled) applied through RtpSender::SetParameters.
It is forwarded to FecController::SetProtectionOverride without
reconfiguring the encoder or renegotiating, and FecControllerDefault
applies it on top of its adaptive result. Unset keeps today's behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds non-standard fecPacketsSent, fecBytesSent and fecSsrc to
RTCOutboundRtpStreamStats, mirroring the existing inbound-rtp FEC stats.
They are taken from the FlexFEC substream of VideoSendStream::Stats and
reported on the media stream it protects, so FEC overhead can be
observed per sender when using RtpParameters::fec_protection.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds RTCRtpFecProtection and RTCRtpParameters.fecProtection on ObjC, and
RtpParameters.FecProtection and RtpParameters.fecProtection on Android,
converting to and from webrtc::RtpFecProtection. Without these, setting
parameters from either SDK would also clear a policy set natively, since
both rebuild RtpParameters from their own fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jni_zero only supports one level of class nesting, so the doubly nested
RtpParameters.FecProtection.Mode was resolved as RtpParameters$Mode
instead of RtpParameters$FecProtection$Mode. Converting a non-null
fec_protection to Java in getParameters() would then fail to find the
class and constructor. Make it a direct member named FecProtectionMode,
which jni_zero resolves to the class path javac generates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FecProtection.mode is a public field, so an application can set it to
null. getModeNativeIndex() then threw a NullPointerException from the
native setParameters() call. Fall back to ADAPTIVE instead, matching the
ObjC binding's handling of unknown modes, and mark the field and the
public constructor parameter @nullable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cloudwebrtc

Copy link
Copy Markdown
Collaborator Author

Security review

Result: no high-confidence vulnerabilities found.

Scope: git diff m150_release...HEAD at 0c7b8abb81, 5 commits, 37 files, +999/−7. Test-only files were excluded.

Where input enters

Entry point What was checked Result
RtpParameters.fec_protection (C++, ObjC, Android setParameters) Every write path runs CheckRtpParametersInvalidModificationAndValues, in pc/rtp_sender.cc (init parameters and normal path) and WebRtcVideoSendStream::SetRtpParameters. Safe
protection_factor / key_frame_protection_factor CheckRtpParametersValues requires values in [0, 1], which also rejects NaN. ToFecRate clamps again before converting to the Q8 rate (0–255). Safe
max_fec_frames Validated to [1, kMaxFecFrames=6] before it reaches the FEC generator. Safe
ObjC mode (arbitrary NSInteger) NativeModeFromMode falls back to kAdaptive for unknown values. Safe
Android mode across JNI Java → native uses ordinal(). A null mode now maps to ADAPTIVE (0c7b8abb81) instead of throwing an NPE in the native call. Native → Java only indexes values() with a valid C++ enum. Safe
Thread safety of SetFecProtection FecControllerDefault::SetProtectionOverride and UpdateFecRates both hold mutex_. The new state is RTC_GUARDED_BY(mutex_). Safe
New outbound-rtp stats fecSsrc / fecPacketsSent / fecBytesSent Local send counters plus the FlexFEC SSRC, which is already in the SDP. Exposed only through the app's own getStats(). No data exposure

Threat model

The new surface is an API the local application calls. It adds no SDP or RTP/RTCP parsing, and a remote peer cannot set fec_protection. The only effect is how many FEC packets the sender generates, which is a bandwidth concern and outside the scope of this review.

Change since the previous review

The previous review found one robustness issue, not a vulnerability: setting FecProtection.mode = null on Android caused an NPE in getModeNativeIndex(). 0c7b8abb81 fixes it and adds testSetFecProtectionWithNullMode. That commit has not yet been built or tested.

🤖 Generated with Claude Code

@cloudwebrtc
cloudwebrtc marked this pull request as ready for review November 5, 2026 06:51
@cloudwebrtc

Copy link
Copy Markdown
Collaborator Author

cloudwebrtc and others added 2 commits November 5, 2026 14:58
The FEC controller only applies RtpParameters::fec_protection in
UpdateFecRates, which RtpVideoSender::OnBitrateUpdated calls when the
bandwidth estimate changes. On a stable network that may not happen for a
long time, so switching to kDisabled kept sending FEC and changing the
protection factor had no effect.

When the policy changes while the stream is running, re-register with the
bitrate allocator, as SignalEncoderActive() does. This recomputes the
allocation with the last estimate, loss and RTT, so the new policy and the
resulting encoder target rate apply right away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Two PeerConnections negotiate FlexFEC and the FEC actually sent is checked
through the outbound-rtp and inbound-rtp stats: adaptive sends no FEC
without loss, kFixed sends FEC that the receiver gets and kDisabled stops
it, kMinimum keeps a floor, a higher factor sends more FEC, a policy set
before negotiation is applied, and invalid values and audio senders are
rejected.

Also clarify that the outbound FEC stats only appear once the first FEC
packet has been sent, since the FlexFEC substream stats are created
lazily.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Changing FEC can re-register a timed-out sender and reserve bandwidth from other senders, while the public API contract incorrectly applies FlexFEC’s first-stream restriction to ULPFEC.

2 open issues
What changed in this PR

This PR adds per-video-sender forward error correction (FEC) control through RtpParameters, allowing runtime policy changes without renegotiation or encoder reconfiguration.

Changes:

  • Adds adaptive, fixed, minimum, and disabled policies, with validation and forwarding through the video send pipeline.
  • Exposes outbound FlexFEC statistics and adds Objective-C and Android bindings.
  • Adds unit and integration coverage for policy changes, validation, statistics, and binding conversions.
File Description
video/​video_send_stream_impl.h Declares the FEC policy setter.
video/​video_send_stream_impl.cc Forwards policies and refreshes bitrate allocation.
video/​video_send_stream_impl_unittest.cc Tests forwarding and allocation refresh.
stats/​rtcstats_objects.cc Registers outbound FEC statistics.
sdk/​objc/​unittests/​RTCRtpParametersTest.mm Tests Objective-C policy conversions.
sdk/​objc/​api/​peerconnection/​RTCRtpParameters.mm Preserves policies during native conversion.
sdk/​objc/​api/​peerconnection/​RTCRtpParameters.h Exposes the sender FEC property.
sdk/​objc/​api/​peerconnection/​RTCRtpFecProtection+Private.h Declares native conversion helpers.
sdk/​objc/​api/​peerconnection/​RTCRtpFecProtection.mm Implements Objective-C policy conversion.
sdk/​objc/​api/​peerconnection/​RTCRtpFecProtection.h Defines the Objective-C policy API.
sdk/​BUILD.gn Includes Objective-C sources, headers, and tests.
sdk/​android/​src/​jni/​pc/​rtp_parameters.cc Converts FEC policies through JNI.
sdk/​android/​instrumentationtests/​src/​org/​webrtc/​RtpSenderTest.java Tests policy round trips and null modes.
sdk/​android/​api/​org/​webrtc/​RtpParameters.java Defines Android policy fields and modes.
pc/​rtp_sender.cc Rejects audio policies and transfers pre-negotiation settings.
pc/​rtp_sender_receiver_unittest.cc Tests audio rejection and negotiation transfer.
pc/​rtp_fec_protection_integrationtest.cc Adds end-to-end policy and packet-count tests.
pc/​rtc_stats_integrationtest.cc Checks when FEC statistics are absent.
pc/​rtc_stats_collector.cc Populates outbound FEC statistics.
pc/​rtc_stats_collector_unittest.cc Tests FEC statistics collection.
pc/​BUILD.gn Adds the FEC integration-test target.
modules/​video_coding/​fec_controller_unittest.cc Tests override modes and adaptive restoration.
modules/​video_coding/​fec_controller_default.h Declares override state and setter.
modules/​video_coding/​fec_controller_default.cc Applies policies over adaptive FEC calculations.
modules/​video_coding/​BUILD.gn Adds the RTP parameters dependency.
media/​engine/​webrtc_video_engine.cc Applies policies, restores them on recreation, and maps statistics.
media/​engine/​webrtc_video_engine_unittest.cc Tests policy updates, validation, and statistics attribution.
media/​engine/​fake_webrtc_call.h Records policy updates in fake streams.
media/​base/​media_engine.cc Validates protection factors and frame limits.
media/​base/​media_channel.h Adds optional sender FEC statistics.
call/​video_send_stream.h Adds a default no-op policy setter.
call/​rtp_video_sender.h Declares RTP sender policy forwarding.
call/​rtp_video_sender.cc Forwards policies to the FEC controller.
call/​rtp_video_sender_interface.h Adds the RTP sender policy interface.
api/​stats/​rtcstats_objects.h Declares outbound FEC statistics.
api/​rtp_parameters.h Defines policies, equality, and string formatting.
api/​rtp_parameters.cc Adds policy mode names.
api/​fec_controller.h Adds a default no-op controller override hook.
api/​BUILD.gn Adds the controller’s RTP parameters dependency.

Review effort: Balanced

Comment thread video/video_send_stream_impl.cc Resolved
Comment thread api/rtp_parameters.h Resolved

@xianshijing-lk xianshijing-lk left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the full diff against head (5a9d95c) plus the surrounding code in media_opt_util, ulpfec_generator, forward_error_correction, rtp_video_sender and the GN targets.

The design is right: applying the policy after the adaptive computation, so the loss filters keep running and kAdaptive stays seamless, is the correct seam, and the default no-op SetProtectionOverride / SetFecProtection keep custom controllers and fakes compiling. Test coverage is good for this fork. My comments are mostly documentation and test execution. The one thing I'd fix before merge is the timed-out-sender re-registration already raised at video_send_stream_impl.cc:659 — replied on that thread.

One correction to the PR description, not to the code. "New parameters apply when the next FEC block starts (UlpfecGenerator::pending_params_), so a block is never split across settings" isn't accurate. pending_params_ is consumed at the top of the next AddPacketAndGenerateFec (ulpfec_generator.cc:119-128) — the next packet, not the next block — so a block already accumulating in media_packets_ gets encoded with the new fec_rate and a recomputed min_num_media_packets_. The effect is benign, but it's phrased as a guarantee. Worth correcting unless block-boundary application is an actual requirement.

Checked and fine, listing so you know these weren't skipped: kFixed does bypass both the low-RTT NackFec rule and BitRateTooLowForFec (media_opt_util.cc:107-120, 213-216 — both zero the factors and leave SelectedType() at kNackFec, so the override at fec_controller_default.cc:186 still runs, and the early return at :162 can't fire with FEC negotiated). kDisabled truly stops FEC (fec_rate 0 → NumFecPackets 0 → ResetState). The stats source is correct: MergeInfoAboutOutboundRtpSubstreams drops kFlexfec from the merged map but folds its rtp_stats into the media substream, so reading raw stats.substreams is right and the "also counted in packetsSent/bytesSent" note holds; GetAggregatedVideoSenderInfo starting from infos[0] correctly covers the first-stream case. GN deps and includes all check out.

Comment thread api/rtp_parameters.h Resolved
Comment thread api/fec_controller.h Resolved
Comment thread sdk/BUILD.gn Resolved
Comment thread api/rtp_parameters.h Resolved
Comment thread media/engine/webrtc_video_engine.cc Resolved
Comment thread video/video_send_stream_impl.cc Resolved

@xianshijing-lk xianshijing-lk left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think mostly nits, good work in general, I give the stamp now, please address those comments

cloudwebrtc and others added 3 commits November 6, 2026 09:13
SetFecProtection() re-adds the stream to the bitrate allocator so a new
policy applies without waiting for a new estimate. It only checked
IsRunning(), which stays true after an encoder timeout. If the camera
stopped producing frames, SignalEncoderTimedOut() had already removed the
stream, so changing the policy re-registered an idle sender and reserved
bandwidth that other senders could use. Since timed_out_ was already set,
the activity check would not remove it again until encoding resumed.

Also require !timed_out_. The policy is still stored and applies when
SignalEncoderActive() re-registers the stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Covers the previous fix: after the encoder times out and the stream is
removed from the bitrate allocator, SetFecProtection() must not add it
back, and it must recompute the allocation again once encoding resumes.

The test delivers a nonzero bitrate update before the timeout, since
SignalEncoderTimedOut() only removes the observer when the encoder target
rate is nonzero; without it the observer would never be removed and the
test would pass regardless of the fix. Verified to fail without the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The RtpFecProtection comment said that with simulcast only the first
stream is affected. That only describes FlexFEC. ULPFEC gets a generator
per simulcast stream in RtpVideoSender::MaybeCreateFecGenerator(), and
ProtectionRequest() forwards the parameters to all of them, so with
ULPFEC the policy applies to every layer.

For FlexFEC, also note that libwebrtc does not allocate a FlexFEC SSRC
for simulcast senders (media_session.cc), so FlexFEC normally only takes
effect without simulcast.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
cloudwebrtc and others added 10 commits November 6, 2026 09:55
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replaces std::pair<uint32_t, const StreamDataCounters*> with a small
FlexfecSubstream struct so the fields are named at the use site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The stats helpers kept the last video outbound-rtp or the first video
inbound-rtp they found, so a fixture with a second video track would
silently pick one of them. Expect exactly one video stream instead.

Also use NewGetStats(run_loop()), which integration_test_helpers.h
prefers over the WaitUntilSettings overload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EXPECT_GT(high_ratio, low_ratio) passes on any difference, including
noise. With factors of 0.1 and 0.9 the measured FEC ratios are about
0.19 and 0.48, so require high_ratio > 2 * low_ratio: if the factor has
no real effect, the test fails instead of depending on chance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The audio sender is rejected in
RtpSenderBase::ValidateAndMaybeUpdateInitParameters before FEC
negotiation matters, so the field trials have no effect on this test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
gtest's ASSERT_TRUE inside an XCTest method returns from the method on
failure, silently skipping the remaining checks. Use XCTAssertTrue and
return explicitly before dereferencing the optional, which makes the
early exit visible.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The kFixed docs said the FEC overhead stays constant and is predictable.
What is fixed is the requested rate: ForwardErrorCorrection::NumFecPackets
rounds the FEC count to whole packets per block, with at least one FEC
packet for any nonzero rate. A factor of 0.1 therefore gives 100%, 50%
and 10% packet overhead for blocks of 1, 2 and 10 media packets, and with
one frame per block (the kFixed default) small frames stay in the high
overhead regime.

Describe the rounding and the one-packet floor on kFixed and on
protection_factor. Add a UlpfecGenerator test that pins the FEC count for
those block sizes at the Q8 rate a factor of 0.1 maps to; the
ProtectionBitrateCalculator tests cannot cover this because their
protection callback is a mock that never reaches the generator.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t it

kMaxFecFrames = 6 is not an independent choice: it is the same cap on
frames per FEC block that the adaptive path uses,
VCMNackFecMethod::kUpperLimitFramesFec. Cite that source, and
static_assert in media_opt_util.cc that the two match so they cannot
drift silently. The assert lives there because kUpperLimitFramesFec is
a protected member.

Also document what max_fec_frames trades off: a larger value spreads
FEC over more frames, which lowers overhead for the same factor, at the
cost of recovery delay of up to max_fec_frames frames. Note that it is
an upper bound, since UlpfecGenerator may close a block earlier once it
holds enough media packets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An application-supplied FecController inherits the no-op
SetProtectionOverride(). For those, RtpParameters::fec_protection is
accepted and returned by GetParameters() but has no effect, which is
exactly the case for applications moving off custom controllers. State
that contract on the method.

This is documentation only. Detecting the controller type at runtime
would be wrong, since a custom controller may implement the method, and
getStats() cannot tell either: fecSsrc only appears once FEC is sent and
only covers FlexFEC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Running sdk_unittests on an iOS simulator showed that a failing gtest
EXPECT_* inside an XCTest method only prints the failure: the test case
still passes. Changing an expected value to a wrong one printed
"RTCRtpParametersTest.mm:49: Failure" and the run still reported
TEST EXECUTE SUCCEEDED. Six of the thirteen assertions in this file were
gtest ones, including every check of the ObjC-to-native conversion in
testFecProtectionToNative, so that conversion was not actually tested.

Replace them with XCTest assertions, using XCTAssertTrue(a == b) for
enum class and std::optional values, and drop the gtest include.
Verified on an iPhone 17 / iOS 27.2 simulator: the three tests pass, and
the same wrong value now fails testFecProtectionToNative with
TEST EXECUTE FAILED.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
testSetFecProtection only sets keyFrameProtectionFactor and maxFecFrames
to non-null values, and testSetFecProtectionWithNullMode, where they are
null, only checked the mode after the round trip. So the Java null ->
std::nullopt -> Java null path through JNI was never asserted: a
conversion that turned null into 0 would still pass.

Also assert that both stay null and that protectionFactor is preserved.

Not built or run locally (no Android toolchain in this checkout); needs
CI or a device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@cloudwebrtc
cloudwebrtc merged commit 83af826 into m150_release Nov 9, 2026
4 checks passed
@cloudwebrtc
cloudwebrtc deleted the duan/rtp-fec-protection branch November 9, 2026 12:16
cloudwebrtc added a commit to webrtc-sdk/webrtc-build that referenced this pull request Nov 10, 2026
Picks up the following changes from webrtc-sdk/webrtc `m150_release`
since 150.7871.05 (a802fa9849..83af826464):

- Drop encrypted frames that are too short to decrypt
(livekit/libwebrtc#324)
- Keep the H.264 PPS id readable in E2EE keyframes without a wire change
(livekit/libwebrtc#327)
- Copy `discard_frame_when_cryptor_not_ready` in `KeyProviderOptions`
(livekit/libwebrtc#328)
- fix(pc): fire `OnTrack` when a receiving transceiver gains a remote
stream (livekit/libwebrtc#321)
- Add `RtpParameters::fec_protection` to control FEC per sender at
runtime (livekit/libwebrtc#329)
cloudwebrtc added a commit to livekit/livekit that referenced this pull request Nov 16, 2026
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
(livekit/libwebrtc#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.
cloudwebrtc added a commit to livekit/client-sdk-swift that referenced this pull request Nov 17, 2026
Picks up livekit/libwebrtc#329, which adds RtpParameters::fec_protection
to set a sender's FEC policy (adaptive, fixed, minimum, disabled) at
runtime without renegotiation, and reports FEC packets and bytes sent in
outbound-rtp stats. It also carries livekit/libwebrtc#321, #324, #327
and #328.
cloudwebrtc added a commit to livekit/livekit that referenced this pull request Nov 17, 2026
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
(livekit/libwebrtc#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.
davidliu pushed a commit to webrtc-sdk/android that referenced this pull request Nov 18, 2026
Bumps `VERSION_NAME` to 150.7871.06 and updates README and CHANGES.md.

Picks up these webrtc-sdk/webrtc `m150_release` changes since
150.7871.04 (corresponds to `83af826464`):

- Drop encrypted frames that are too short to decrypt
(livekit/libwebrtc#324)
- Keep the H.264 PPS id readable in E2EE keyframes without a wire change
(livekit/libwebrtc#327)
- Copy `discard_frame_when_cryptor_not_ready` in `KeyProviderOptions`
(livekit/libwebrtc#328)
- Fire `OnTrack` when a receiving transceiver gains a remote stream
(livekit/libwebrtc#321)
- Add `RtpParameters::fec_protection` to control FEC per sender at
runtime (livekit/libwebrtc#329)

150.7871.05 is skipped on Android: its only change
(livekit/libwebrtc#325) affects the iOS/macOS `RTCMTLVideoView`.
cloudwebrtc added a commit to livekit/livekit that referenced this pull request Nov 26, 2026
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
(livekit/libwebrtc#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants