46 Commits
Author SHA1 Message Date
ee75008bea Generate downstream FlexFEC with per-track protection modes (#5195)
* 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>
2026-11-30 14:55:27 +01:00
8179b3a117 Do not recover FlexFEC from RTX repaired packets (#5194)
* 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.

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

* 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.

---------

Co-authored-by: Jules Testard <jules.testard@livekit.io>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 13:44:15 +08:00
35c4357d90 migrate FEC logic into buffer_base (#5039)
* Add upstream FlexFEC recovery support

* Guard short TWCC extensions in FEC packets

* Release completed FlexFEC states

* Validate FlexFEC payload type range

* Invoke FEC callbacks after unlocking

* Reduce FlexFEC protection state allocations

* Avoid allocations for complete FlexFEC packets

* Optimize ordered FlexFEC packet insertion

* Reuse RTP packet storage for FlexFEC recovery

* Limit pending FlexFEC repair packets

* Lower FlexFEC repair window to two seconds

* Harden upstream FlexFEC handling

* Test FlexFEC with E2EE media

* Fix FlexFEC negotiation with libwebrtc publishers

* Enhance payload length validation in decoder

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* remove the ability to configure payload type for FlexFEC

* moved some helpers into protocol

* Handle big gaps in media sequence numbers

Reset buffers when a big gap in media sequence numbers is detected.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* bump protocol & psrpc deps

* Handle FEC packet recovery failure

Increment FEC packets discarded counter and remove packet.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* do not NACK on fec recovered packet (#4896)

* do not NACK on fec recovered packet

* fix test race in CI

* Fix FEC write return after merging RTX feedback changes

* PR fixes for FlexFEC implementation (#4898)

* do not NACK on fec recovered packet

* refactor common code into unlockAndInvokeFECRecovery

* add FEC stats to RTPStats

* add log for when fecdecoder unavailable after creation

* rename markAsFECRepair to setFECRepairBufferLimit for clarity

* refactor packet generation for tests into util

* fix test race in CI

* move the unlocks back inline for readability

* update RTPstats

* Fix FEC write return after merging RTX feedback changes

* Use shared RTP packet helper in merged FEC NACK test

* Remove redundant return from FEC write handler

* packet post process (#5020)

* packet post process

* remove redundant writeRTX

* send out RTCP (NACK and RR) from packetPostProcess only

* handle FEC decoder on receiver restart (#5032)

* handle FEC decoder on receiver restart

* move onStreamRestartLocked into BufferBaseParams

* migrate fec into buffer_base

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Raja Subramanian <raja.gobi@tutanota.com>
Co-authored-by: Jules Testard <jules.testard@livekit.io>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 13:41:03 +01:00
Raja SubramanianandClaude Fable 5.2 de817c7d50 sfu: return the stream generation from HandleIncomingPacket (#5235)
A caller that writes a packet and forwards it in the same call gets the
generation it needs for a later ReadRTP of that packet.

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 00:24:03 +05:30
Perfloop Agent 1d0bae0f76 sfu: bind retransmissions to the source cache generation (#5213)
* sfu: reproduce retransmission across receiver restart

Signed-off-by: Perfloop Agent <agent@perfloop.ai>

* sfu: use an atomic counter for cache generations

Signed-off-by: Perfloop Agent <agent@perfloop.ai>

* sfu: give test packets a stream generation

Signed-off-by: Perfloop Agent <agent@perfloop.ai>

---------

Signed-off-by: Perfloop Agent <agent@perfloop.ai>
2026-11-17 15:43:00 +05:30
Raja SubramanianandClaude Opus 5.5 031e7bd61d sfu: restart the dependency descriptor parser after a stream gap (#5192)
* sfu: restart the dependency descriptor parser of a publisher stream after a gap

libwebrtc numbers dependency descriptor frames with one counter across all
simulcast layers. A layer that dynacast paused for a long time resumes with a
frame number more than half the 16 bit range away from its last one. The
publisher buffer's parser never restarted, so it unwrapped the resumed frames
against the stale number and later lost a full wrap. Every packet of the layer
then fell below the structure thresholds and was dropped until the numbers
caught up, about 16 minutes for three 22 fps layers.

Enable the parser restart after a 30 s gap that relayed tracks already use, and
start the key frame seeder on a restart, as the restart drops the structure the
following packets need.

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

* sfu: request a key frame only when a restarted stream has no structure

The parser now reports the restart on the packet that caused it, so the
buffer does not read the parser's state. A stream that resumes with a key
frame carries its structure and needs no key frame request.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 00:39:21 +05:30
Raja SubramanianandClaude Opus 5.5 4a2615f127 sfu: throttle PLIs with an atomic before taking the rtpstats lock (#5093)
* Throttle PLIs with an atomic before taking the rtpstats lock

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

* Reset the PLI throttle when the stream restarts

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 00:34:28 +05:30
Raja SubramanianandClaude Opus 5.5 d2cf39bce6 sfu: replace forward scheduling delay with processing per write (#5072)
* sfu: replace forward scheduling delay with processing per subscriber

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

* sfu: describe processing per subscriber as per write

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

* telemetry: name forward processing metrics per write

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

* Pin protocol with NodeStats forward_processing_per_write

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:52:17 +05:30
Raja SubramanianandClaude Opus 5.5 125ea44a61 sfu: report forward scheduling delay next to forwarding latency (#5065)
* sfu: report forward scheduling delay next to forwarding latency

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

* sfu: keep full forwarding transit when packing scheduling delay

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

* sfu: saturate reported forwarding p90s instead of wrapping

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:24:31 +05:30
Raja Subramanian 6294ab37c7 prometheus: count keyframes received and forwarded (#5060) 2026-10-25 13:08:05 +05:30
Raja Subramanian a8729ee65b sfu: read lock for BufferBase.GetPacket (#5055) 2026-10-24 23:35:23 +05:30
6342d8fd1b Enable upstream FlexFEC03 (#4845)
* Add upstream FlexFEC recovery support

* Guard short TWCC extensions in FEC packets

* Release completed FlexFEC states

* Validate FlexFEC payload type range

* Invoke FEC callbacks after unlocking

* Reduce FlexFEC protection state allocations

* Avoid allocations for complete FlexFEC packets

* Optimize ordered FlexFEC packet insertion

* Reuse RTP packet storage for FlexFEC recovery

* Limit pending FlexFEC repair packets

* Lower FlexFEC repair window to two seconds

* Harden upstream FlexFEC handling

* Test FlexFEC with E2EE media

* Fix FlexFEC negotiation with libwebrtc publishers

* Enhance payload length validation in decoder

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* remove the ability to configure payload type for FlexFEC

* moved some helpers into protocol

* Handle big gaps in media sequence numbers

Reset buffers when a big gap in media sequence numbers is detected.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* bump protocol & psrpc deps

* Handle FEC packet recovery failure

Increment FEC packets discarded counter and remove packet.

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* do not NACK on fec recovered packet (#4896)

* do not NACK on fec recovered packet

* fix test race in CI

* Fix FEC write return after merging RTX feedback changes

* PR fixes for FlexFEC implementation (#4898)

* do not NACK on fec recovered packet

* refactor common code into unlockAndInvokeFECRecovery

* add FEC stats to RTPStats

* add log for when fecdecoder unavailable after creation

* rename markAsFECRepair to setFECRepairBufferLimit for clarity

* refactor packet generation for tests into util

* fix test race in CI

* move the unlocks back inline for readability

* update RTPstats

* Fix FEC write return after merging RTX feedback changes

* Use shared RTP packet helper in merged FEC NACK test

* Remove redundant return from FEC write handler

* packet post process (#5020)

* packet post process

* remove redundant writeRTX

* send out RTCP (NACK and RR) from packetPostProcess only

* handle FEC decoder on receiver restart (#5032)

* handle FEC decoder on receiver restart

* move onStreamRestartLocked into BufferBaseParams

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Raja Subramanian <raja.gobi@tutanota.com>
2026-10-22 13:58:04 -07:00
Anunay Maheshwari 0b58164597 fix(sfu): stop allocating per packet for abs-capture-time and retransmits (#5003)
* sfu: stop allocating per packet for abs-capture-time and retransmits

* sfu: drop unused abs-capture-time marshal errors

* sfu: size held extensions locally, guard nil holds, keep sequencer clones
2026-10-15 05:20:04 +05:30
Raja SubramanianandClaude Opus 5.5 9ddcc50767 sfu: parse VP8 and VP9 payload descriptors without an allocation (#4981)
* sfu: parse VP8 and VP9 payload descriptors without an allocation

Replace ExtPacket.Payload with typed VP8 and VP9 pointer fields that point
at backing structs inside the ExtPacket, so parsing does not allocate and a
wrong codec type is a compile error.

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

* sfu: copy the VP8 descriptor in the test packet helper

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 20:43:17 +05:30
Raja SubramanianandClaude Fable 5.1 9b20c1da57 sfu/buffer: stop allocating per ingested packet (#4951)
* sfu/buffer: stop allocating per ingested packet

Buffer.Write allocated six objects for every RTP packet. They were
the parsed rtp.Packet, a copy of it in patchExtPacket, and the flow
state, whose address two rare log calls took. The rest were an
AbsCaptureTime, present on about one packet per second, and the
extension slice that pion grows with append.

Unmarshal into a pooled scratch packet. Give ExtPacket its own backing
rtp.Packet and an [8]rtp.Extension array, and copy the header into
them. Patch the payload in place. If the abs-capture-time extension is
present, parse it. Log a copy of the flow state.

Per packet, Write plus ReadExtended. Opus: 6 allocs, 448 B -> 0.
VP8: 6 allocs, 416 B -> 1 alloc, 32 B. Opus 240 -> 142 ns, VP8 269 -> 204 ns.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* sfu/buffer: point extension payloads at the bucket copy on read

Queued ExtPackets kept extension payload slices into the write input,
which the transport reuses for the next packet. ReadExtended now parses
the header again from the bucket copy, so extensions and CSRCs point
into RawPacket like the payload does.

The test writes every packet through one input buffer and checks the
audio level of each packet read back.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* sfu/buffer: test that a dropped padding packet keeps the shifted sequence number on read

The bucket stores the shifted number, so re-parsing the header on read
returns it. This test guards that.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-06 18:21:11 +05:30
cnderrauber 7d556cfefe sample codec payload mismatch error log (#4751) 2026-08-13 19:32:21 +08:00
Raja Subramanian c6303bb15a Fix skipped packets accounting. (#4604)
* Fix skipped packets accounting.

No need to copy unskipped packet RTP header to skipped packet.
That was causing padding bytes to be counted.

Also use Header.PaddingSize as base PaddingSize is deprecated.

* PaddingSize in header in utils
2026-06-18 11:58:39 +05:30
Raja Subramanian 062d12197f Use NACKQuueInterface type. (#4538)
And some extra logging for subscription permission when it fails.
2026-05-21 23:00:51 +05:30
Raja Subramanian 4a7b1e8587 Create NACK tracker only once. (#4527)
Not a major issue, but just avoiding duplicate creation of NACK module.
RTCP feedback of `nack` and `nack pli` end up getting treated as `nack`
and was double creating.
2026-05-15 12:45:51 +05:30
Raja Subramanian ccdf23c8a6 Use mediatransportutil/codec package, no functional change (#4497) 2026-05-01 20:06:29 +05:30
Raja Subramanian 701a37c2d1 Convert sort.Slice -> slices.SortFunc (#4472)
* Convert sort.Slice -> slices.SortFunc

* active speaker loudness in descending order
2026-04-23 15:12:24 +05:30
Raja Subramanian cdfaacfca3 Restart nacker on OOB sequence number restart. (#4368)
Clears NACKs based on old sequence number base and restarts it.
Also rename the function to be more reflective of what stats lite is
for.
2026-03-17 09:16:08 +05:30
Raja Subramanian 750d5904f0 Add API to restart lite stats. (#4366) 2026-03-16 15:20:13 +05:30
Raja Subramanian 7eaaaada5d Mark last run of grow bucket outside goroutine. (#4348)
* straem tracker debug logging

* tracker

* debug

* clean up
2026-03-06 19:36:13 +05:30
Raja Subramanian 939794cf47 mark + restart (#4329) 2026-02-21 15:12:13 +05:30
Raja Subramanian 75f9c462be Add debug for receiver restart. (#4328)
* Add debug for receiver restart.

Have a suspicion that something is deadlocking between restart receiver
and buffer bind during replay. Adding debug to get a better picture of
state of receiver restart.

* consistent logging
2026-02-20 01:44:59 +05:30
Raja Subramanian 370e0a4d52 Set up audio config in audio level module when config is updated. (#4290)
* Set up audio config in audio level module when config is updated.

It is possible to get audio config after bind (bind is where the audio
level module is created) for remote tracks. So, split out setting audio
level config in audio level module and invoke it when config is updated.

* coderabbit review

* prevent divide-by-0

* not active before config
2026-02-05 09:35:26 +05:30
Raja Subramanian a9849340c3 Avoid logger data race. (#4284)
Also defer promise channel close.
2026-02-04 01:35:44 +05:30
Raja Subramanian 1e689e1a24 Reducing some info level logs. (#4274)
* Reducing some info level logs.

Also, relaxing the check for runaway RTCP receiver report to allow for
rollover to catch up if it is not too far away.

* set logger
2026-02-02 10:54:03 +05:30
Anunay Maheshwari 0c33b8c671 chore: move codecs/mime stuff to protocol (#4255) 2026-01-20 20:54:32 +05:30
Raja Subramanian aea044c5cb Defer setting clock rate in RTPStats module till codec is bound. (#4250)
With audio simulcast codecs, it is possible that the clock rate of the
primary codec is different from the secondary codec. If a subscriber
binds to the secondary codec, the clock rate should be set correctly. Do
it at bind time.
2026-01-15 22:08:50 +05:30
Raja Subramanian 7fae5ac9e6 Do not restart receiver on codec change mid-session. (#4225)
* Do not restart receiver on codec change mid-session.

This is not supported and was an erroneous change during the
receiver_base/buffer_base + RTP stream restart consolidation. Also make
the codec munger creation more resilient.

* fix test
2026-01-08 02:35:32 +05:30
Raja Subramanian 80ba93fa18 Do NACK updates as soon as flow state is processed. (#4221) 2026-01-06 11:59:21 +05:30
Raja Subramanian 46651c1978 Release v1.9.10 (#4214)
* Release v1.9.10

* move room exists service store op to Added section
2026-01-01 12:36:34 +05:30
Raja Subramanian 08ac4ecdc5 Support preserving external supplied time. (#4212)
In some paths, it is better to preserve pre-recorded time. So, make the
base implementations preserve the RTCP Sender Report receive time.

Also, add a method to enable forwarding packet arrival time. Could be
used across relay.
2025-12-31 14:41:59 +05:30
Raja Subramanian 1a4758ed9c Skip restart callback if external. (#4208)
* Skip restart callback if external.

Without out the external restart was bumping forwarder generation twice.

* fix sense
2025-12-30 22:14:06 +05:30
Raja Subramanian dde4fb498e configurable dependency descriptor restart (#4207)
* configurable dependency descriptor restart

* KeyFrame -> IsKeyFrame

* use the params directly
2025-12-29 23:51:15 +05:30
Raja Subramanian b91cd2e4ea Rework receiver restart. (#4202)
* Rework receiver restart.

- Protect against concurrent restarts
- Clean up and consolidate code around restarts
- Use `RestartStream` of buffer rather than creating new buffers.

* fix test
2025-12-27 17:17:16 +05:30
Raja Subramanian 25ece1e911 Minor refactor in buffer base and audio level (#4198)
* Minor refactor in buffer base and audio level

- Make a function for `restartStream`. Will be useful
  when external signal needs to restart a stream. Also restart all the
  bits (audio level, dd parser and frame rate calculator)
- make an audio level mode with RTP timestamp so that some state can be
  moved out of buffer base

* clean up

* log restart
2025-12-26 20:13:38 +05:30
Raja Subramanian 599002f890 ignore PLI requests for non-video (#4196)
* ignore PLI requests for non-video

* under lock
2025-12-26 12:26:22 +05:30
Raja Subramanian ed8e6afcd7 Handle repair SSRC of simulcast tracks during migration. (#4193)
* Handle repair SSRC of simulcast tracks during migration.

* fix

* fix comment
2025-12-25 14:45:48 +05:30
Raja Subramanian c6bf7a2786 Fix logging key and other clean up around stream restart. (#4192) 2025-12-24 22:48:25 +05:30
Raja Subramanian 381bce03ae Return extended sequence number only and not packet. (#4189)
* Return extended sequence number only and not packet.

Callers need only the extended sequence number.
Extended packet could get release if the forwarder processes it before
caller accesses it causing a data race.

* grow bucket in a go routine
2025-12-24 10:44:56 +05:30
Raja Subramanian 6bcbf54ea1 Always instantiate nacker when using out-of-band sequence numbers. (#4187) 2025-12-24 04:10:11 +05:30
Raja Subramanian e71184dea0 Store buffer after creating it. (#4186)
* Refactor receiver and buffer into Base and higher layer.

To be able to share code/functionality with relay.

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* clean up

* deps

* fix test

* fix test

* Store buffer after creating it.

Also changing signature of creator function as it could call TrackInfo()
and get into a deadlock.

* fix double unlock

* add some more debug logging
2025-12-24 02:55:51 +05:30
Raja Subramanian 7c8ea11505 Refactor receiver and buffer into Base and higher layer. (#4185)
* Refactor receiver and buffer into Base and higher layer.

To be able to share code/functionality with relay.

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* WIP

* clean up

* deps

* fix test

* fix test
2025-12-23 21:35:48 +05:30