Repository navigation
fix(livekit): use LK APIs for WebRTC stats gathering, fix edge cases - #24873
Conversation
remote-inbound-rtp stats may lack packetsReceived and bytesReceived When stats.js falls back to remote-inbound-rtp, buildData reads undefined for these fields, producing NaN in downstream calculations. Default relevant stats to 0.
The liveKitConnectionStatus reactive var initializes to 'unknown'. getWorstStatus lacks 'unknown' in its statusOrder map, so it falls through to the default comparison (undefined > 0 = false), which works by accident. Add 'unknown' explicitly with value -1 so it is always treated as lower than 'normal'.
Connection status integration with LiveKit has a couple of edge cases: - Alert triggers use inbound-rtp from subscribed remote tracks (wrong direction — a remote user's loss triggers a local alert), and bandwidth calculations pick a single arbitrary stat entry via [0] index (underreporting download, fragmented video rates, negative bitrate on track churn). - Uses internal, undocumented SDK APIs (engine.pcManager.*) which will most certainly break someday and also bork track direction context when merging stats data. - Imprecise packetsLost and jitter reporting Replace getLKStats() with a new livekit/stats.ts module that uses the public per-track APIs from livekit-client via its own methods: - monitorLiveKitAudioStats: probes LocalAudioTrack.getSenderStats() on sliding window, dispatches audiostats events with packet loss from the server's perspective (RTCP receiver reports). Fixes wrong-direction alert triggers. - getLiveKitAudio/VideoNetworkData: iterates over all relevant tracks via getSenderStats/getReceiverStats, aggregates bitrate by track SID. Fixes bandwidth underreporting. Uses raw RTCStats reports (pulled from LK APIs as well) to fix packetsLost and jitter reporting. Additionally, network stats gathering is split into their own A/V variants so that we had heteregeneous bridges (e.g.: audio=livekit, video=webrtc-sfu). Changes here do have two caveats: - Breaking the pattern of gathering stats via AudioManager through each bridge getStats methods. I do not see a cleaner way of using LK's APIs without doing that - less of two evils and the mediasoup/FS path is unaffected by any of this. - Jitter semantics differ in the LK variant. mediasoup one is incorrect, this one's good :)
WalkthroughThe changes restructure how LiveKit audio and video statistics are collected and reported. Previously, centralized Sequence DiagramsequenceDiagram
participant AudioManager
participant LiveKitRoom as LiveKit Room
participant StatsMonitor as stats.ts Module
participant ConnectionStatus as connection-status service
participant AudioUI as Audio UI Layer
AudioManager->>AudioManager: monitor() called
AudioManager->>AudioManager: isUsingLiveKit()?
alt LiveKit Active
AudioManager->>StatsMonitor: monitorLiveKitAudioStats(room, interval)
activate StatsMonitor
loop Every interval
StatsMonitor->>LiveKitRoom: getLocalParticipant().audioTracks
LiveKitRoom-->>StatsMonitor: track sender stats
StatsMonitor->>StatsMonitor: Probe & aggregate stats (packets, bytes, jitter)
StatsMonitor->>AudioUI: dispatch CustomEvent('audiostats')
end
else SFU Active
AudioManager->>AudioManager: monitorAudioConnection(peer)
end
ConnectionStatus->>ConnectionStatus: startMonitoringNetwork()
loop Monitor tick
ConnectionStatus->>AudioManager: isUsingLiveKit()?
alt LiveKit Path
ConnectionStatus->>StatsMonitor: getLiveKitAudioNetworkData(room, previousStats)
StatsMonitor->>LiveKitRoom: Query sender/receiver stats
StatsMonitor-->>ConnectionStatus: { audio rates, jitter, loss, previousStats }
ConnectionStatus->>StatsMonitor: getLiveKitVideoNetworkData(room, previousStats)
StatsMonitor-->>ConnectionStatus: { video rates, previousStats }
else SFU Path
ConnectionStatus->>ConnectionStatus: Compute SFU audio/video rates
end
ConnectionStatus->>ConnectionStatus: setNetworkData({ audio, video, user })
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes 🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsTimed out fetching pipeline failures after 30000ms Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
bigbluebutton-html5/imports/ui/components/connection-status/service.js (1)
488-500:⚠️ Potential issue | 🟡 Minor
unknownstill can't win here.Because
worstStatusstarts as'normal', a list like['unknown']still returnsnormal, so the new rank never surfaces. Keepnormalfor the empty case only, and initialize comparisons fromunknownor the first status.✅ Minimal fix
- let worstStatus = 'normal'; + let worstStatus = statuses.length ? 'unknown' : 'normal'; // eslint-disable-next-line for (let status of statuses) { - if (statusOrder[status] > statusOrder[worstStatus]) { + if ((statusOrder[status] ?? statusOrder.unknown) > statusOrder[worstStatus]) { worstStatus = status; } }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@bigbluebutton-html5/imports/ui/components/connection-status/service.js` around lines 488 - 500, The getWorstStatus function incorrectly initializes worstStatus to 'normal' so a single 'unknown' in statuses doesn't win; change initialization to start comparisons from the first element (or 'unknown' by default) instead of always 'normal' — e.g., set worstStatus = statuses.length ? statuses[0] : 'normal' (or worstStatus = 'unknown' when you prefer) and then iterate comparing via statusOrder; update references to worstStatus and statusOrder in getWorstStatus accordingly so an actual 'unknown' can be returned when it's the only/lowest-ranked item.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@bigbluebutton-html5/imports/ui/components/connection-status/service.js`:
- Around line 410-430: The code collapses cameraBridge and screenShareBridge
into one boolean videoIsLK causing the SFU side to be ignored; change the
video-path logic in the service so you treat camera and screenShare bridges
independently (e.g., query getLiveKitVideoNetworkData for each LiveKit bridge
and getSFUVideoNetworkData for each SFU bridge) then merge/sum their returned
video stats into the single video object used downstream; ensure you update
previousLkStats only with LiveKit results (merge result.previousStats into
previousLkStats after each LiveKit call) and keep the existing handling for SFU
results so mixed SFU+LiveKit setups report total video bitrate correctly.
In `@bigbluebutton-html5/imports/ui/services/livekit/stats.ts`:
- Around line 304-374: The code only sets audioJitter and audioPacketsLost from
the local mic via getRemoteInboundAudioStats (micPub/micTrack), so listen-only
sessions leave those fields zero; add a receive-side fallback after the
remoteParticipants loop that, when audioJitter or audioPacketsLost are unset,
iterates room.remoteParticipants -> participant.audioTrackPublications ->
pub.track (RemoteAudioTrack) and calls track.getReceiverStats() to read jitterMs
and packetsLost, then pick a sensible value (e.g. the max jitterMs and total or
max packetsLost, or the first non-null values) and assign them to audioJitter
and audioPacketsLost before returning; use the same pub.trackSid keys and
newPreviousStats logic as in the download loop to avoid duplication and handle
missing tracks.
- Around line 132-151: The monitor can reschedule probes after stop because
probe()'s finally always sets probingTimeout; introduce a generation token
(e.g., probeGeneration) that you increment in stopLiveKitAudioStats(), capture
as localGen at the start of runProbe/when calling probe(), and in the
probe().finally only schedule the next setTimeout if localGen ===
probeGeneration and probingTimeout is still null; update
monitorLiveKitAudioStats to use this token when starting probes and ensure
stopLiveKitAudioStats increments the token, clears probingTimeout, sets it to
null, and clears statsWindow to prevent any in-flight probe from resurrecting
the poller.
---
Outside diff comments:
In `@bigbluebutton-html5/imports/ui/components/connection-status/service.js`:
- Around line 488-500: The getWorstStatus function incorrectly initializes
worstStatus to 'normal' so a single 'unknown' in statuses doesn't win; change
initialization to start comparisons from the first element (or 'unknown' by
default) instead of always 'normal' — e.g., set worstStatus = statuses.length ?
statuses[0] : 'normal' (or worstStatus = 'unknown' when you prefer) and then
iterate comparing via statusOrder; update references to worstStatus and
statusOrder in getWorstStatus accordingly so an actual 'unknown' can be returned
when it's the only/lowest-ranked item.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: a97bf0f1-0ecf-412b-b831-e07edf1e2531
📒 Files selected for processing (8)
bigbluebutton-html5/imports/api/audio/client/bridge/livekit.tsbigbluebutton-html5/imports/api/screenshare/client/bridge/livekit.tsbigbluebutton-html5/imports/ui/components/connection-status/service.jsbigbluebutton-html5/imports/ui/components/video-provider/service.tsbigbluebutton-html5/imports/ui/services/audio-manager/index.jsbigbluebutton-html5/imports/ui/services/livekit/index.tsbigbluebutton-html5/imports/ui/services/livekit/stats.tsbigbluebutton-html5/imports/utils/stats.js
💤 Files with no reviewable changes (2)
- bigbluebutton-html5/imports/ui/components/video-provider/service.ts
- bigbluebutton-html5/imports/api/screenshare/client/bridge/livekit.ts
| export const monitorLiveKitAudioStats = (room: Room, interval: number): void => { | ||
| const probeInterval = interval / PROBES; | ||
| const runProbe = () => { | ||
| probe(room).finally(() => { | ||
| probingTimeout = setTimeout(runProbe, probeInterval); | ||
| }); | ||
| }; | ||
|
|
||
| stopLiveKitAudioStats(); | ||
| runProbe(); | ||
| }; | ||
|
|
||
| export const stopLiveKitAudioStats = (): void => { | ||
| if (probingTimeout) { | ||
| clearTimeout(probingTimeout); | ||
| probingTimeout = null; | ||
| } | ||
|
|
||
| statsWindow = []; | ||
| }; |
There was a problem hiding this comment.
Stopping the monitor doesn't stop an in-flight probe.
If stopLiveKitAudioStats() runs while probe() is still awaiting stats, the finally block still schedules the next timeout. That leaves a background poller running after audio exit or after a restart, and can duplicate audiostats events.
🛑 Guard rescheduling with a generation token
let probingTimeout: ReturnType<typeof setTimeout> | null = null;
+let probingGeneration = 0;
export const monitorLiveKitAudioStats = (room: Room, interval: number): void => {
+ stopLiveKitAudioStats();
const probeInterval = interval / PROBES;
+ const generation = ++probingGeneration;
const runProbe = () => {
+ if (generation !== probingGeneration) return;
probe(room).finally(() => {
- probingTimeout = setTimeout(runProbe, probeInterval);
+ if (generation === probingGeneration) {
+ probingTimeout = setTimeout(runProbe, probeInterval);
+ }
});
};
- stopLiveKitAudioStats();
runProbe();
};
export const stopLiveKitAudioStats = (): void => {
+ probingGeneration += 1;
if (probingTimeout) {
clearTimeout(probingTimeout);
probingTimeout = null;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@bigbluebutton-html5/imports/ui/services/livekit/stats.ts` around lines 132 -
151, The monitor can reschedule probes after stop because probe()'s finally
always sets probingTimeout; introduce a generation token (e.g., probeGeneration)
that you increment in stopLiveKitAudioStats(), capture as localGen at the start
of runProbe/when calling probe(), and in the probe().finally only schedule the
next setTimeout if localGen === probeGeneration and probingTimeout is still
null; update monitorLiveKitAudioStats to use this token when starting probes and
ensure stopLiveKitAudioStats increments the token, clears probingTimeout, sets
it to null, and clears statsWindow to prevent any in-flight probe from
resurrecting the poller.
✅ Automated tests have passed! |
b4a3246
into
bigbluebutton:v3.0.x-develop

What does this PR do?
direction — a remote user's loss triggers a local alert), and bandwidth
calculations pick a single arbitrary stat entry via [0] index
(underreporting download, fragmented video rates, negative bitrate on
track churn).
most certainly break someday and also bork track direction context when
merging stats data.
uses the public per-track APIs from livekit-client via its own methods:
sliding window, dispatches audiostats events with packet loss from the
server's perspective (RTCP receiver reports). Fixes wrong-direction
alert triggers.
via getSenderStats/getReceiverStats, aggregates bitrate by track SID.
Fixes bandwidth underreporting. Uses raw RTCStats reports (pulled from
LK APIs as well) to fix packetsLost and jitter reporting.
variants so that we had heteregeneous bridges (e.g.: audio=livekit,
video=webrtc-sfu).
When stats.js falls back to remote-inbound-rtp, buildData reads undefined
for these fields, producing NaN in downstream calculations.
getWorstStatus lacks 'unknown' in its statusOrder map, so it falls
through to the default comparison (undefined > 0 = false), which
works by accident.
Closes Issue(s)
None