Skip to content

fix(livekit): use LK APIs for WebRTC stats gathering, fix edge cases - #24873

Merged
prlanzarin merged 3 commits into
bigbluebutton:v3.0.x-developfrom
prlanzarin:u30/fix/lk-connstats
Apr 14, 2026
Merged

prlanzarin merged 3 commits into
bigbluebutton:v3.0.x-developfrom
prlanzarin:u30/fix/lk-connstats

Conversation

@prlanzarin

Copy link
Copy Markdown
Member

What does this PR do?

  • fix(livekit): use LK APIs for stats gathering, fix edge cases
    • 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).
  • fix(stats): guard WebRTC stats data against undefined vals
    • 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.
  • fix(stats): handle MetricStatus.Unknown in getWorstStatus
    • 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.

Closes Issue(s)

None

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 :)
@prlanzarin prlanzarin added this to the Release 3.0 milestone Apr 8, 2026
@prlanzarin
prlanzarin requested a review from Arthurk12 April 8, 2026 14:15
@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes restructure how LiveKit audio and video statistics are collected and reported. Previously, centralized getStats() methods in audio and screenshare bridge classes aggregated stats. This refactoring removes those bridge-level methods and introduces dedicated stats monitoring and collection functions. A new livekit/stats.ts module implements continuous audio stats probing via monitorLiveKitAudioStats() and network data collection via getLiveKitAudioNetworkData() and getLiveKitVideoNetworkData(). The AudioManager now branches its monitoring logic based on whether LiveKit is in use, and connection-status/service.js was updated to consume stats from either LiveKit or SFU sources. The isLiveKitBridge() utility replaces the removed getLKStats() function, and inbound RTP stats now include defensive null-coalescing for missing fields.

Sequence Diagram

sequenceDiagram
    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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: fixing LiveKit stats gathering by using LiveKit APIs instead of internal SDK methods, and addressing related edge cases.
Description check ✅ Passed The description is detailed and directly relates to the changeset, explaining what the PR does, the problems it solves, and the technical approach taken across multiple commits.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

Review ran into problems

🔥 Problems

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

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud

sonarqubecloud Bot commented Apr 8, 2026 •

Copy link
Copy Markdown

Quality Gate Passed Quality Gate passed

Issues
11 New issues
0 Accepted issues

Measures
0 Security Hotspots
No data about Coverage
0.0% Duplication on New Code

See analysis details on SonarQube Cloud

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

unknown still can't win here.

Because worstStatus starts as 'normal', a list like ['unknown'] still returns normal, so the new rank never surfaces. Keep normal for the empty case only, and initialize comparisons from unknown or 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

📥 Commits

Reviewing files that changed from the base of the PR and between 802c084 and b461b82.

📒 Files selected for processing (8)
  • bigbluebutton-html5/imports/api/audio/client/bridge/livekit.ts
  • bigbluebutton-html5/imports/api/screenshare/client/bridge/livekit.ts
  • bigbluebutton-html5/imports/ui/components/connection-status/service.js
  • bigbluebutton-html5/imports/ui/components/video-provider/service.ts
  • bigbluebutton-html5/imports/ui/services/audio-manager/index.js
  • bigbluebutton-html5/imports/ui/services/livekit/index.ts
  • bigbluebutton-html5/imports/ui/services/livekit/stats.ts
  • bigbluebutton-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

Comment on lines +132 to +151
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 = [];
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

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.

@antobinary antobinary mentioned this pull request Apr 8, 2026
22 of 26 tasks
@github-actions

github-actions Bot commented Apr 8, 2026

Copy link
Copy Markdown

✅ Automated tests have passed!

@prlanzarin
prlanzarin merged commit b4a3246 into bigbluebutton:v3.0.x-develop Apr 14, 2026
84 of 87 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants