* telemetry: count failed publishes and subscribes, not only successes
- JoinSession records a publish request before each re-reported track.
- livekit_track_publish_counter gets state="failure" for tracks pending at close.
- A subscribe failure is counted once per attempt; a new attempt restarts its timers.
- livekit_track_subscribe_counter gets a user_error label.
- New livekit_pubsub_outcome_ms: one sample per attempt, failures at the time they fail.
- A connection that never comes up records its session start time at close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: close the gaps in failure samples found in review
- A subscribe that succeeds after a user-error wait starts a new attempt.
- Close records one publish failure sample per pending request, migrated ones included.
- A publish released for an unknown codec counts as a failed publish.
- A session that never reached primary transport connected records its start time at close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: start the new attempt when a bind lands before subscribe returns
After a user error, a bind that fired inside addSubscriber found the
outcome gate still closed and recorded no success sample. The bind
callback now starts the new attempt too, and the test waits for the
request count instead of reading it once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: serialize the new attempt and record legacy publish time per request
The bind callback and reconcile could both reach the new-attempt helper.
The one that lost the flag swap returned before the timers restarted, so
a later reconcile could fire a false not-bound timeout. A per-subscription
mutex now holds the whole restart.
On a close that is not a cancel, livekit_pubsubtime_ms now records one
publish sample for each pending request, migrated requests included, the
same set the failure counter and livekit_pubsub_outcome_ms cover.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
AddOnBind runs the callback at once for a track that is already bound.
The callback ran before setSubscribedTrack, so it found no track and
recorded no success, and setSubscribedTrack then cleared the bound
state. The subscription later reported "track not bound".
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Chrome 149+ offers the post-quantum hybrid group X25519MLKEM768 (DTLS 1.3)
with a key share. As DTLS server, pion picks the first curve in its own
list that the client supports, so X25519MLKEM768 leads there. As DTLS
client, X25519 stays first to keep the ClientHello unfragmented, since
some DTLS servers (e.g. older mbedTLS on ESP32) reject a fragmented one.
Enabled by default in the OSS server; EnableDTLSPQC lets embedders such
as Cloud gate it.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(secure-input): add a data packet receive hook and sip method stubs
* refactor(secure-input): bump protocol for sensitivity class names
* fix(secure-input): normalize data packets before caching them for joiners
* refactor(sensitive-input): rename secure input to sensitive input and bump protocol
* rtc: pick screen share layers from the sizes measured in the video
The layer sent to a viewer was chosen from the sizes the sharer announced
when it started publishing. When the shared window shrank, the server kept
believing the small layer was bigger than it was and sent it upscaled.
A screen share track now takes its sizes from the video it receives, like a
track in one-shot signalling mode already does, and updates them when they
change. The sizes are only replaced once every announced layer has been
measured, so codecs that report fewer sizes (VP9 with spatial layers) keep
the announced ones.
* rtc: keep the legacy video layers in sync with the measured sizes
UpdateVideoSize only rewrote the codec layers, so the top-level layers
sent to clients kept the announced sizes after a resize.
* rtc: read the measured video sizes under the track lock
The size callbacks of each simulcast layer run in their own goroutine.
Each one took a snapshot of the receiver sizes and then waited for the
track lock, so a delayed callback could overwrite the sizes written by a
later one with an older snapshot. UpdateVideoSize now receives the
getter and reads the sizes once it holds the lock.
Assisted-by: Claude
* rtc: get the video sizes from the track receiver in UpdateVideoSize
UpdateVideoSize looks up the receiver of the codec itself and reads its
sizes while holding the track lock, so the size callback no longer has
to pass a getter.
Assisted-by: Claude
* rtc: check the track lock from another goroutine in TestUpdateVideoSize
The CI runs the tests with go-deadlock, which reports TryLock from the
goroutine that already holds the lock as a recursive lock.
Assisted-by: Claude
When a WHIP PATCH carries an If-Match that no longer matches the
publisher's ICE session, the RTC node returns psrpc.FailedPrecondition,
but iceTrickle had no case for that code and answered 500. RFC 9725
section 4.3.1 requires 412 Precondition Failed, which is also what
psrpc's own ErrorCode.ToHTTP maps FailedPrecondition to.
Also pass the error instead of nil to handleError in the non-psrpc
branches of iceTrickle and iceRestart. handleError calls err.Error(),
so a nil error would panic. The psrpc client wraps all of its own
failures today, so this is hardening.
Add a unit test for the PATCH status mapping and an integration test
that drives a real WHIP session through trickle and ICE restart.
UpdateEgress indexes an ended egress in the ended_egress hash as
"<room>|<endedAt>". parseEgressEnded split the value on every "|" and
required exactly two parts, so an egress from a room whose name
contains "|" could not be parsed. Room names have no character
restrictions, so such rooms can exist.
CleanEndedEgress returns on the first parse error. The entry is
therefore never removed: its egress record, ended_egress entry and
egress:room:<room> member stay in Redis, and every node logs
"could not clean egress info" every 30 minutes. Entries after it in
the hash's iteration order are also skipped for that sweep.
Split at the last "|" instead, since the timestamp cannot contain it.
The stored format is unchanged, so entries already stuck before this
change are cleaned on the next sweep.
* rtc: hold the full reconnect on a failed negotiation while migrating out
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: keep a running disconnect cleanup, reconnect when a failed negotiation's wait ends
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: detach the signal sink in the migration out reconnect test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: attach an open signal sink in the migration out reconnect test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: hold the disconnect cleanup while a participant migrates out
The disconnect cleanup closes a participant as a leave 5 s after a
transport failure. A participant that is migrating to another node at
that moment is reported as gone while its session continues there.
LocalParticipantHelper.IsMigratingOut reports whether another node is
taking over the participant. While it is true, the cleanup checks again
every 5 s, for at most 75 s. The room manager here returns false.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* rtc: a disconnect cleanup cleared during its migration check does not close
The cleanup checked that its timer was still set before a reset, but not
before a close. A check that was in flight when the timer was cleared
could still close the participant.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* rtc: clarify the disconnect cleanup comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
CreateIngress and UpdateIngress stored a room name, participant identity, name or metadata over the configured limits. The ingress then joins with a token holding those values and CheckConnectLimits rejects the join, so the ingress was created but could never connect. Run the same check in the API, as CreateRoom and UpdateParticipant do.
* 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>
* Replay missed disconnects on resume from the client's last pong time
A resuming client can send the timestamp of the last Pong it processed.
The server replays the participant disconnects newer than the earlier of
that time minus 1 s and the last signal receive time minus 3 s. Requests
buffered by an offline client move the last signal receive time to just
before the resume, the last Pong time does not move.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Take the test pong time from the cached disconnect time
The simulated pong time came from time.Now(), so a pause of more than
1 s after the disconnect was cached moved the disconnect out of the
look back.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Exercise the pong look back in the replay test
A pong time equal to the disconnect time is replayed without the 1 s
look back too. Use a pong time 500 ms after the disconnect.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
* Enable ice-lite for migration session
In the client's ICE restart, a full agent's checks
can reach libwebrtc before it applies our answer;
it then prunes the resulting peer reflexive pair
behind the still writable pair to the previous node,
keeps that pair and sends the DTLS handshake to the previous node.
* 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>
* service: answer StopEgress for an ended egress without waiting
A stop for an egress that already ended finds no server subscribed to its
topic. On NATS psrpc reports that at once, but its retry interceptor then
waits out the request timeout before each retry, so the API answered 412
only after about 8 s.
StopEgress now sends the stop without psrpc's no-subscriber retry and asks
the IO service for the egress instead. An ended egress gets 412 and an
unknown one 404 at once. A starting or active egress that nothing is
subscribed for yet is retried every second for up to 3 seconds.
DeleteIngress and UpdateIngress only log a failed RPC to the ingress, so
they send it without the no-subscriber retry too.
Bumps psrpc for middleware.WithoutNoSubscriberRetry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
* deps: bump psrpc to claim queue rpcs on non-NATS buses
psrpc after v0.8.2 stopped claiming queue rpcs, so on the local and Redis
buses a queue rpc with no subscriber timed out instead of failing with
ErrNoResponse after the selection timeout. That broke
TestJobTerminateReleasesJob. The new pseudo-version claims queue rpcs again
on buses that do not report unsubscribed requests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
* service: retry an active ingress the way StopEgress retries a live egress
UpdateIngress and DeleteIngress send their RPC only when the stored state
says the ingress is buffering or publishing. When no ingress is subscribed,
they now reload the ingress and retry every second for up to 3 seconds
while it is still active, as StopEgress does for a live egress. A stale
state that is no longer active returns at once. The RPC error is still only
logged.
The retry timing is shared by egress and ingress, so it is renamed from
stopEgressRetry* to noSubscriberRetry*.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
* deps: pin psrpc to the merged livekit/psrpc#177
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
---------
Co-authored-by: Claude <noreply@anthropic.com>
* rtc: avoid O(N*M) subscriber scan in RevokeDisallowedSubscribers
Replace repeated linear slices.Contains scans in MediaTrackReceiver and DataTrack RevokeDisallowedSubscribers with an O(N + M) map lookup above allowedSubscribersMapThreshold (8), short-circuit when there are no subscribers, and avoid holding DataTrack.lock while building the allowlist set.
* rtc: cover boundary, empty-allowlist, and concurrent cases for RevokeDisallowedSubscribers
* rtc: fold threshold check into buildAllowedSubscriberSet
* rtc: keep the preferred codec's RTX when trimming the answer
Trimming the answer to the preferred video codec kept the codec and
flexfec but dropped its RTX, so clients that get a trimmed answer could
not negotiate RTX. Keep each RTX whose apt is a kept codec.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: test that the trimmed answer keeps the offered RTX
Drive a real offer through HandleRemoteDescription with client payload
types that differ from the server's, trim to VP8 from the remote
description hook, and check the answer from createAndSendAnswer keeps
VP8's RTX at the offered payload type and drops H264 and its RTX.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: check the trimmed answer's video payload list
Assert the video m-line lists only VP8 and its RTX, so a dropped codec
cannot stay listed without its attributes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* 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>
* rtc: unpublish a track whose codec is not in its track info
AddReceiver could not set up a receiver for a codec missing from the
track info, but the track stayed published with no receivers, so its
subscribers waited for media that never came. AddReceiver now returns an
error, and a track left with no receivers because of a codec mismatch is
unpublished instead of announced. Per-layer failures keep the track.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: reject an unknown codec before the track is published
Decide once, for a new pending track that is not migrated, before the
MediaTrack exists. A codec missing from the track info releases the
pending track through releasePendingTrackLocked and also releases the
webrtc track ID, so later layers cannot claim another pending track. The
track is never published, so no room event, webhook or gauge change
happens. Drops the AddReceiver error refactor; the codec rule moves into
codecPriority.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: keep the webrtc id with the released cids, skip queued replacements
Record the webrtc track ID in the same released group as the track's
CIDs, so a corrected publish of the track clears it too. Leave a pending
track as is when a replacement is queued on its cid, as the replacement
shares the track ID and releasing would drop it. Make the test's first
lookup deterministic.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: keep the migrated reliable data channel ordered
The migrated data channel loop shared one ordered value, so a
_reliable channel listed after _lossy was created unordered.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: register the connect handler before checking the call count
untilTransportsConnected checked the OnInitialConnected count before
registering its handler, so a call in between was missed and the wait
never returned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: wait for the close callback in subscription test helpers
addSubscriber and the data track subscribe register OnClose when they
return, after the subscription shows as subscribed. The test helpers
read the callback before that and failed with an empty call list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Keep the ICE config set by the candidate protocol simulate
The switch candidate protocol simulate restarts ICE with a TCP or TLS
config, and the client then rejoins. The participant reports only a
learned fallback to OnICEConfigChanged, so the room manager did not
cache the simulated config and the rejoin went back to UDP.
SimulateICEFallback restarts ICE and reports the config like a learned
fallback.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Keep a simulated ICE config only when the node offers the transport
The simulate still applies the config to the current session. It is
reported for the rejoin only for ICE/TCP on a node with an ICE/TCP
listener, or for TURN/TLS on a node with TURN/TLS. A rejoin after a
simulate of a transport that the node does not offer then uses UDP.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
* Apply a fallback learned on resume to the same resume
A short failed connection reported on resume can learn a TCP or TLS
fallback. The room manager resolved the resume ICE config before that
check ran, so the reconnect response, its ICE servers and the ICE
restart used the old config, and the fallback applied only on the next
attempt.
ResumeParticipant now runs the short-connection check after the signal
is valid again, then asks the caller to resolve the ICE config and
servers. HandleReconnectAndSendResponse no longer runs the check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep a pending fallback and skip ICE/TCP without a listener
A short failure of a UDP pair cleared a TCP or TLS preference that was
set after the pair connected. A client report of the same failure on
resume then removed the fallback the server had just chosen.
A UDP failure also chose ICE/TCP on a node with no ICE/TCP listener.
TCP mode drops UDP candidates, so the restart had no usable candidates.
It now chooses TURN/TLS when that is on, else it keeps UDP.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Test the resume ICE resolver in the room manager
The resume test in pkg/rtc supplies its own resolver, so it did not
run the room manager code that picks the ICE config and the ICE
servers. Move that code to resumeICE and test that a learned TLS
fallback gives the TLS config and drops the non-TLS TURN servers.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Skip the client failure check when a fallback is pending
The selector change that kept a preference on a UDP failure could trap
a participant in TCP mode. When the subscriber restarted in TCP mode and
never connected while the publisher still had its UDP pair, the
selector kept TCP and the next resume tried TCP only again.
Restore the selector. The client report on resume no longer clears the
guard, so it does nothing when the server already chose a fallback for
that failure, and the fallback stays for the ICE restart.
Add resume cases for a UDP failure that the client reports on a node
with no ICE/TCP listener.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Pick the fallback from the transport that failed
The selector used one connection type for both transports, so it could
not tell an old UDP pair from a transport that restarted with a
preference and did not connect.
It now gets the connection type of the transport that failed.
- A UDP pair that fails with a preference set keeps the preference. The
pair is older than the preference, and the ICE restart applies it.
- A transport that did not connect in TCP mode moves to TURN/TLS. It
went back to no preference before, so a client could alternate
between UDP and TCP and never reach TURN/TLS.
- A transport that did not connect with a preference counts as a short
failure. A TURN/TLS preference that cannot connect then goes back to
no preference on the first failure.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Let clients set a preferred ICE candidate protocol on join
The v1 JoinRequest ConnectionSettings.candidate_protocol and the v0
candidate_protocol query parameter let a client ask for TCP or TLS
from the start. The SFU applies the stronger of the client preference
and the learned room fallback, and keeps the join preference on resume.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Require the candidate protocol on every connect, check ICE/TCP
Resume uses the preference from the resume request, the same as join,
so the participant no longer stores the join value. TCP mode drops UDP
candidates, so a TCP preference applies only when ICE/TCP is enabled,
and TLS without TURN/TLS falls back to TCP only under the same check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep the client preference apart from the learned fallback
The room cache now holds only fallbacks the transport learned after a
failure. The participant stores the client preference from join, and
resume applies the stronger of it and the resume request before the
resume response, so the response carries the matching ForceRelay.
TLS mode lists only TLS relays, also from external TURN servers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Let a resume preference replace the join preference
A resume that sends TCP or TLS uses that value, and only a resume
without a value inherits the preference from join.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Ignore an unsupported preference on resume
A resume preference for a transport the server does not offer no
longer replaces the join preference. Each preference is lowered to a
supported transport before the resume picks between them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* docs: document the Redis ACL rules the server needs
There was no reference for which Redis ACL rules LiveKit requires
(#2486), so operators with restricted users had to derive them from
behavior, and the failure modes are non-obvious: a missing
+@connection fails the first PING with a startup error, a missing
+cluster fails CLUSTER SLOTS in cluster mode, and a missing
+@scripting breaks the room lock release script silently.
Lists the keys and prefixes LiveKit stores, the command families it
uses, and working rule sets for single-node and cluster mode. All of
it verified end to end by running the server against a Redis 8
instance with restricted users: startup, room create, list, delete,
and the cluster slot-map path each exercised against the documented
grants with no denials.
Refs #2486
* docs: keep only the two working Redis ACL rule sets
The key and command enumerations can drift from the code; the rule sets
verified against Redis 8 are the durable part.
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* rtc: handle subscribed track close after subscription installation
A close of a new SubscribedTrack during addSubscriber was lost or handled
too early. OnClose was registered before the track was stored and did not
replay an earlier close, and the publisher was marked after addSubscriber
returned. A close before the store left a closed track stored with no
resubscribe. A close after the store but before the mark left a stale
publisher mark.
SubscribedTrack now records a close and OnClose replays it. addSubscriber
marks the publisher itself and defers OnClose to its end, the same order
as the data track path.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: cover a rejected install and wait for the deferred close callback
TestSubscribeRevokedInFlight now waits for the close callback that
addSubscriber installs on return before it fires a close.
TestSubscribedTrackCloseDuringInstall adds a case where the recheck
rejects the install and the removal closes the track.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Test data track closes during auto-subscription
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* Wait for the close before checking installation recovery
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* Keep the installation regression on the public regrant result
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* Deliver data track close after subscription installation
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* rtc: verify the subscriber exists before the injected close
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* rtc: observe data-track permission races independently of resolver counts
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* rtc: deliver data-track close after subscription installation
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* rtc: guard the data-track close test window and wait for cleanup
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* rtc: deliver data-track close after subscription installation
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
---------
Signed-off-by: Perfloop Agent <agent@perfloop.ai>
* Always use full ice for publisher offer
When warp is enabled, ice-lite could complete dtls handshake
before ice is connected when RTT is high. Because libwebrtc
may send nomination after 1s interval, and pion relies on
the nomination to transit ice state to connected while libwebrtc
only relies on a writable pair. Full ice has connectivity check
to mitigate this.
After this change, ice-lite configuration only works on
subscriber pc.
* test
* feat: add token revocation
* token revocation: match LiveKit Cloud API, make it optional
- add token_revocation config section (enabled: false by default, ttl)
- RemoveParticipant: cutoff defaults to now, revoke_token_ts must be within
60s and is stored with the validation leeway, revoke absent participants,
keep not found unless revoke_token_ts is given
- UpdateParticipant revokes older tokens on permission updates and the
participant gets a refreshed token
- share the RoomService logic with Cloud through RevokeTokenClient
- revocations merge to the later cutoff and expiry
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: clean up expired revocations lazily
Drop the cleanup goroutine of LocalStore. Revocations are kept in a queue
ordered by expiry, and expired ones are removed from its front when
revoking or checking, at most once per minute.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: request context for redis, own lock for LocalStore
- RedisStore revocation calls use the request context
- LocalStore revocations use their own lock instead of the store lock
- remove TestRTCValidateRoomlessTokenAfterRevocation, which passes without revocation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: length checks before auth, test all auth chains
Check lengths before the admin permission check, as LiveKit Cloud does, and
test that the API, agent endpoint and WebTransport chains reject revoked tokens.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: do not return store errors to clients
Log the error of a failed revocation lookup and respond with a fixed message,
as the store error may contain internal addresses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: cnderrauber <zengjie9004@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: answer an ICE restart offer while ICE is gathering
A remote offer that restarts ICE was held while the peer connection was
still gathering candidates and only applied when gathering completed.
Until then no answer was sent, so the remote waited in have-local-offer
for as long as gathering ran, for example until a STUN request timed
out. The remote candidates of the new ICE generation that were trickled
in the meantime were added against the previous remote description,
dropped by pion as not matching the current ufrag, and never added
again.
Holding the offer was added when the ICE agent could not restart while
gathering. The ICE agent now cancels a gather in progress on restart,
so apply the restart offer and answer it right away, and remove the
held offer and its replay on gathering complete.
Refs #5167
* rtc: remove comment
UpDataTrackManager.Close empties its map and closes each track, but
does not report them unpublished. When the participant closes itself
(a peer connection disconnect timeout, a full reconnect), the room
removes it afterwards and finds no data tracks, so they stay in
RoomTrackManager and subscribers never get the removal notification.
Report each track unpublished on close, as a closing media track does.
Tests cover both close paths against a real room, and Close itself:
each track reported once, nothing on a second Close or for a track
unpublished before it.