Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 36 ยท Quality and Debugging

Reading getStats for Call Quality

Use RTCPeerConnection.getStats() to measure bitrate, packet loss, jitter and round-trip time. Compute rates from two snapshots and build a small quality monitor you can run.

A WebRTC call can feel perfect for one user and terrible for another with the same code. To understand why, you need numbers: how many bits per second are flowing, how many packets are lost, how long a round trip takes. The browser measures all of this continuously and exposes it through one method: pc.getStats().

This lesson explains the report types that matter, shows why most values are counters (so you must subtract two snapshots), and builds a monitor that turns raw stats into bitrate and a plain quality verdict. The examples run on a loopback connection using a canvas as the video source.

What getStats returns

await pc.getStats() resolves to an RTCStatsReport, a map of stat objects. Every object has an id, a type and a timestamp. The types you will meet most:

Type Describes Useful fields
outbound-rtp One stream you send bytesSent, packetsSent, framesPerSecond, frameWidth, qualityLimitationReason
inbound-rtp One stream you receive bytesReceived, packetsLost, jitter, framesDecoded, framesDropped
remote-inbound-rtp How the peer sees your stream roundTripTime, fractionLost, jitter
candidate-pair An ICE path being used or tested state, nominated, currentRoundTripTime, availableOutgoingBitrate
local-candidate / remote-candidate Addresses candidateType, protocol
transport The DTLS/ICE transport dtlsState, bytesSent, selectedCandidatePairId
data-channel A data channel messagesSent, bytesReceived, state

Not every browser implements every field. Always check that a field exists before using it, and treat missing values as "unknown", not as zero.

Counters need two snapshots

Fields like bytesSent and packetsLost only ever grow: they are totals since the stream began. A single snapshot tells you very little. To get a rate, take two snapshots a known time apart and divide the difference:

Text
bitrate (bit/s) = (bytes2 - bytes1) * 8 / (time2 - time1 in seconds)

timestamp is in milliseconds, so convert.

flowchart LR
  A["getStats at t1"] --> D["subtract"]
  B["getStats at t2"] --> D
  D --> R["bytes per second, loss per second, frames per second"]

Quality is the change between snapshots, not the totals.

Try it: list the report types

JS What does a connected call report?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The exact numbers change every run, so this example prints only checks that are always true.

Try it: a bitrate and loss monitor

The helper below measures the outgoing video bitrate between two snapshots, and the incoming loss ratio. On a loopback link the loss is zero; on a real network these are the first numbers you inspect when users complain.

JS Compute bitrate from two snapshots

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Which numbers matter

Think of quality in four layers:

  1. Is it connected? candidate-pair with state: 'succeeded' and nominated: true; transport.dtlsState: 'connected'.
  2. Is the network healthy? Round-trip time (candidate-pair.currentRoundTripTime or remote-inbound-rtp.roundTripTime), jitter, packet loss.
  3. Is the encoder keeping up? outbound-rtp.qualityLimitationReason is none, bandwidth, cpu or other. bandwidth means the network limits you; cpu means the device is too slow.
  4. Is the viewer seeing smooth video? framesPerSecond, framesDropped, freezeCount, totalFreezesDuration.

Rough guidelines for voice and video calls: RTT under 150 ms is comfortable; jitter under 30 ms is fine; loss under 2 percent is barely noticeable, while above 8 percent calls degrade quickly.

A reusable monitoring loop

In a real app you poll every second or two, compute deltas, and send a compact summary to your analytics, plus a warning to the user when things are poor:

JavaScript
// sketch of a monitoring loop (read-only)
let prev = null;
setInterval(async () => {
  const report = await pc.getStats();
  const now = {};
  report.forEach((s) => {
    if (s.type === 'inbound-rtp' && s.kind === 'video') now.inbound = s;
    if (s.type === 'candidate-pair' && s.nominated) now.pair = s;
  });
  if (prev && now.inbound) {
    const dt = (now.inbound.timestamp - prev.inbound.timestamp) / 1000;
    const kbps = ((now.inbound.bytesReceived - prev.inbound.bytesReceived) * 8) / dt / 1000;
    report({ kbps, rtt: now.pair?.currentRoundTripTime, jitter: now.inbound.jitter });
  }
  prev = now;
}, 2000);

Keep the interval at one to five seconds: polling too often wastes CPU and makes noisy graphs.

Common mistakes

  • Reading totals as rates. Always subtract two snapshots.
  • Treating undefined as 0. A missing field means the browser does not provide it.
  • Mixing timestamps. Use the timestamp from the stat objects, not Date.now(), between two snapshots.
  • Ignoring qualityLimitationReason. It tells you why quality dropped.
  • Polling every 100 ms. One to five seconds is enough.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do you need two getStats snapshots to measure bitrate?

    Counters like bytesSent only grow. Subtract the earlier value and divide by the elapsed seconds.
  2. 2. Which report type describes the stream you RECEIVE?

    inbound-rtp covers received streams; outbound-rtp covers streams you send.
  3. 3. qualityLimitationReason: 'cpu' means

    The browser reduces resolution or frame rate when the device cannot encode fast enough.
  4. 4. Which loss ratio generally starts to hurt call quality noticeably?

    Small loss is hidden by error concealment and retransmissions; high loss causes visible and audible problems.

Summary

  • getStats() returns typed reports: outbound-rtp, inbound-rtp, candidate-pair, transport and more.
  • Most values are cumulative; compute rates from two snapshots.
  • Watch RTT, jitter, packet loss, frame rate and qualityLimitationReason.
  • Poll every one to five seconds and check that each field exists.

Next: Controlling Bitrate and Adapting to Bandwidth