* 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: 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>
* 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>
* 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>
A second Close returns at once while the first still runs the close
callbacks. CloseDone is closed after they have run, so a caller can act
only once the participant's final update went out.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: match publisher m-sections by mid, not by position
A client that stops a transceiver lets the next one recycle its m-line
(JSEP 5.2.2), so a new m-section can come before negotiated ones.
GetUnmatchMediaForOffer stopped at the last answered mid and missed it,
so its codec preferences were never applied.
Bump the protocol so clients know they can stop transceivers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Update protocol_version.go
* Remove comments from GetUnmatchMediaForOffer function
Removed comments explaining the GetUnmatchMediaForOffer function.
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Refresh tokens were signed with the first configured key pair, which is
an arbitrary map entry when several keys are configured. Keep the join
token's API key on the participant and sign with it when its secret is
still configured, falling back to the first key pair otherwise.
* Use negotiated data channels in single PC mode
Bump the protocol version to 18. For protocol >= 18 single peer connection
clients, the server creates its publisher data channels as negotiated with
fixed IDs (100/101/102), so it can send on them without waiting for the
client's DCEP OPEN. Dual PC keeps the in-band channels.
* solve comment
* rtc: split EndSession out of MoveToRoom
A participant's session in a room can end without the participant
closing: today on a move, and next on a room re-key, where a room ended
by the sweeper while participants were joining restarts under a new room
id with the same participants in it.
EndSession is the room-independent half of MoveToRoom: report the
published tracks unpublished, report the session end, run the caller's
leave under the ending session's telemetry guard, then take a fresh
guard and reset the deferred resolvers for the next session. The guard
matters: ParticipantLeft releases it and the telemetry service refuses
to open a stats worker for a released guard, so without a fresh one the
next session's join would silently get no worker.
MoveToRoom keeps the subscriber teardown and the onClose fan-out, passed
in as the leave.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* rtc: rename EndSession to LeaveSession, add JoinSession
EndSession read as terminal, but the participant survives it and joins
another session, so name the pair for what happens to the participant:
LeaveSession and JoinSession.
JoinSession is the other half that review pointed out was missing from
the API: the caller reports the join, then the published tracks are
reported published again under the new session, pairing the unpublish
LeaveSession reported. Without it the re-publish lived only in the
caller, with nothing in OSS proving the two halves balance.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
participants.
While migrating, the old node will have the recently disconnected
participants in the migrating out participant's cache and needs to sent
out to the participant from the migrating in node via the new WebSocket.
This method can be used to exchange that data between the two nodes.
Keeping it as `recently` disconnected and leaving the semantics upto how
recent for implementation.
SubscriptionManager tracks data-track subscriptions but exposed no accessor
for the active ones, so callers could see subscribed and published media tracks
and published data tracks, but not subscribed data tracks. Add
GetSubscribedDataTracks(), returning the bound data down-tracks, mirroring
GetSubscribedTracks() for media, so a participant's full track set can be
accounted for. Regenerated the LocalParticipant fake.
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* report a reason on room-ended telemetry
Room.Close already took a ParticipantCloseReason, but OnClose was func()
with no arguments, so the reason was structurally dropped before it could
reach RoomEnded.
Add types.RoomCloseReason and carry it through Close -> OnClose -> RoomEnded,
where it lands on both the analytics event and the room_finished webhook.
Room.Close now takes the room reason and derives the participant reason from
it, so the two can never disagree. ToParticipantCloseReason maps each reason
to exactly what its call site passed before, so no participant-facing
behaviour changes; a table test pins that mapping.
* fix(test): update webhook test for RoomCloseReason
test/ was outside the packages checked before pushing, so this Close call
site was missed. Also assert the reason reaches the room_finished webhook,
which the unit test cannot cover since it runs with a nil notifier.
* Reduce locking in media track + telemetry listener on move participant.
Telemetry listener was not getting it from new room on room move.
* update comment
* fix signal bytes reporting
* room aware telemetry listener in media track
* data track telemetry listener
* Check for ICE connection before closing participant on signal close.
Only close the participant if ICE has not connected by the time signal
source is closed. If ICE had connected, candidates have been exchanged
and link was established. So, it should be resumable.
Waiting for DTLS closed the participant sometimes in the windowa after
ICE connection, but before DTLS finishes and that unnecessarily closed
the participant forcing a full reconnect.
* variable name
* Add configurable read-message size limit on signalling WebSockets
Set a read limit on both the client-facing (/rtc) and agent worker
WebSocket connections so an oversized frame is rejected by the transport
before being buffered. The limits are operator-tunable via
signal_message_size_limit and agent_signal_message_size_limit, both
defaulting to 2 MiB (0 disables).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Add tests for signalling WebSocket read-message size limit
Cover the configurable signal_message_size_limit added in the prior
commit:
- config: assert both limits default to 2 MiB and that a YAML override
(including 0 to disable) is parsed correctly.
- full-path integration: a real client connects to /rtc on a single-node
server and an oversized frame is rejected by the transport with a 1009
close; a 0 limit leaves the connection unbounded and signalling
proceeds.
Adds setupSingleNodeTestWithConfig so a single-node server can be started
with config overrides.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Bound decompressed size of signalling WebSocket messages
conn.SetReadLimit only accounts for the compressed bytes read off the
wire, and the client-facing /rtc upgrader negotiates permessage-deflate,
so a small compressed frame could still expand into a much larger buffer
once inflated. Enforce the same limit on the decompressed message by
reading through NextReader + io.LimitReader in WSSignalConnection instead
of the unbounded ReadMessage.
The transport-level SetReadLimit is kept as the cheap wire-level guard;
the new check is the decompressed-size backstop.
Adds NextReader to the WebsocketClient interface (regenerated fake) and a
unit test plus permessage-deflate integration tests covering the
amplification case.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Fix publish track count on migration in.
https://github.com/livekit/livekit/pull/4707 addressed the case of
publish tracks overcounting due to synthesised track publish on migrate
in. But, it introduced an issue where published tracks count could go
negative because unpublish subtracted the counter irrespective of the
track actually migrated in or not.
Fix it by keeping track of local publish.
Also, the older code was skipping publisher track count increase if the
synthesised publish was handled first. Address it by checking if the
track is actually new (i. e. fresh local publish) when the track was
already created in the migrate in path.
* fix pub time for tracks published after migration
* test
* prevent multiple track egresses
- Count a publish attempt on a migrating in tarck as there is no
AddTrack for that.
- Add cancel publish only if the participant connection is canceled
- Do not add publish counter for synthetic publish attempts which
happens for migrating in tracks. It will be counted on migrating in
node when the track is actually published, i. e. negotiated/packets
flowing.
* Record subscribe stream start time in prometheus.
Adjust for mutes, i. e. take the last unmute time as the start point and
calculate time till the first byte is sent.
* close the tiny window of race
* Prevent long tail sample when publisher glitches.
Thanks to @milos-lk for this.
Publisher restarting would have reset the layer and would have caused a
sample with very high stream start time. We only need to capture when we
do a dummy start or when the state is seeded to a different node upon
migration.
* reduce a diff
* test
* changed the wrong thing, thank you Devin
* Async attributes on participant.
How it is different from existing participant attributes?
1. Async attribute can be added one at a time.
2. These are not included in `ParticipantInfo`.
3. Get an attribute bt participant identity and async attribute ID as
and when needed.
* clean up
* get full definitions, not just ids
* listener OnDataTrackSchema
* name length config
* data blob
* deps
* static check
* Add missing request ID
* Update protocol commit
* Wire up StoreDataBlobResponse
* Pass request ID through in GetDataBlobResponse
* deps
* atomic
* sctp at 1.9.5
* remove proto clone
---------
Co-authored-by: Jacob Gelman <3182119+ladvoc@users.noreply.github.com>
* feat: acquire requested video layer directly at HIGH quality by default
Two changes that together remove the visible low->high quality ramp for a new
subscriber (both publisher-first and subscriber-first join orders):
1. Default a subscriber's initial video quality to HIGH on bind instead of LOW
for adaptive stream, so the subscribed max layer is the top layer. Adaptive
stream clients can still scale down afterwards based on viewport.
2. On initial layer acquisition the forwarder/selector latch directly onto the
allocator's target (the requested top layer) instead of opportunistically
latching onto the first lower key frame that arrives. A short
initial-acquisition grace aims the target at the requested layer; if it does
not show up in time, the target falls back to the highest layer seen so
acquisition never stalls.
Always on - no configuration flag.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat: gate start-at-desired-quality behind EnableStartAtDesiredQuality flag
Put the "acquire requested video layer directly at HIGH quality" behavior
behind a per-subscriber EnableStartAtDesiredQuality flag (default off, so
the original low->high ramp-up is restored unless enabled).
Plumbed from config.RTC.EnableStartAtDesiredQuality through ParticipantParams
-> SubscribedTrack/DownTrack -> Forwarder -> simulcast selector, gating all
three behavior changes: the HIGH default on bind, the forwarder's
initial-acquisition grace, and the selector's direct-latch-onto-target.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* remove config.
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Shared helper for callers that need to distinguish intentional/expected
participant closures (client leave, admin action, room teardown, migration)
from connection failures. Extracted from cloud's IsClosedIntentionally
switch so cloud-side code paths can share a single source of truth.
* rtc: report participant kind code and details
Plumb ParticipantKind and KindDetails through MediaTrack and
BytesTrackStats so track-level reporting can record the numeric kind
code plus details codes on every participant_session aggregation,
alongside the existing Kind string. Also picks up the new kind fields
on resolved BytesSignalStats participants.
Adds deployment/agentID/version to the agent worker logger.
Had made a change in remote participant case to not have telemetry
listener as telemetry does not apply to remote participant. But, that
listener ended up getting used for subscriber and became a null
listener. Use the listener of the subscriber participant for subscribed
tracks.
* Key telemetry stats work using combination of roomID, participantID
With forwarded participant, the same participantID can existing in two
rooms.
NOTE: This does not yet allow a participant session to report its
events/track stats into multiple rooms. That would require regitering
multiple listeners (from rooms a participant is forwarded to).
* missed file
* data channel stats
* PR comments + pass in room name so that telemetry events have proper room name also
* Make data message naming a bit more consistent.
OnDataPacket and OnDataMessage half-way in the chain made it confusing
(for me at least). Use same name throughout.
API still uses SendDataPacket, but that is not harder to read.
* test
* Use published track for model access in data down track.
No need to pass in the model.
* implementation type assertion
* remove redundant log key
* one more type
* Close interface method
* clean up redundant log key
* remove unused method
* some interface changes to support data tracks in replay
* correct mock signature
* switch participant callbacks to room to listener interface
* mage generate
* clean up
* clear listener
* clean up
* use interface in up data track manager
* tweaks
* Paul feedback - should reduce the diff as this keeps the room handlers as is except making methods for a couple of anonymous handlers
* clean up