@bazariodev/caliper
v1.0.1
Published
WebRTC statistics, call quality, diagnostic dumps, and audio and video measurements.
Maintainers
Readme
@bazariodev/caliper
Measure WebRTC statistics and call quality. Optional entries record diagnostic dumps, measure audio levels, and detect video that stops progressing.
Install
pnpm add @bazariodev/caliperThere are no peer dependencies. The monitor, audio meter, and video monitor use
coordination for subscriptions and timers.
Quality and dump entries have no external runtime imports.
Node.js support is ^22.12.0 || ^24.0.0 || >=26.0.0. Output targets ES2022.
Usage
The application supplies an existing peer connection.
import { createMediaStatsMonitor } from '@bazariodev/caliper';
export function observeCall(peerConnection, onSample) {
const monitor = createMediaStatsMonitor({ peerConnection });
monitor.subscribe(onSample);
monitor.start();
return monitor;
}Quality and shutdown
import { createMediaStatsMonitor } from '@bazariodev/caliper';
import { createCallQualityTracker } from '@bazariodev/caliper/quality';
export function trackCall(peerConnection, readCallState, onWarning) {
const monitor = createMediaStatsMonitor({ peerConnection });
const quality = createCallQualityTracker();
monitor.subscribe((sample) => {
for (const change of quality.push(sample, readCallState())) onWarning(change);
});
monitor.start();
return {
finish(end) {
monitor.dispose();
return quality.report(end);
},
};
}readCallState() returns { microphoneMuted, expectedInboundAudio }.
Set microphoneMuted: true for local mute or hold that intentionally stops microphone audio.
Supply expectedInboundAudio: false during hold or a known remote pause. If omitted, this value
derives from a connected peer and a live audio receiver with an active receive direction.
The tracker reads the negotiated audio send direction from each accepted sample.
Upgrade from 0.1.0
Version 1.0.0 marks the existing public API as stable.
It also checks the negotiated send direction for silent-microphone.
You can remove a duplicate send-direction check from microphoneMuted.
Keep application mute and hold policy in that input. Synthetic samples need a live audio sender
with negotiated sendrecv or sendonly for silence detection. See the changelog.
Diagnostic recording
import { createRtcDumpRecorder, buildWebrtcInternalsDump } from '@bazariodev/caliper/dump';
export function recordCall(peerConnection, monitor, connectionId, onEntry) {
return createRtcDumpRecorder({ peerConnection, monitor, connectionId, onEntry });
}
export function exportCall(entries, userAgent, userAgentData) {
return buildWebrtcInternalsDump(entries, { userAgent, userAgentData });
}The recorder starts at construction. Give each peer connection a new connectionId.
The attachment configuration omits ICE server username and credential fields. It retains
server urls, optional credentialType, and the other configuration fields. The peer is unchanged.
Store entries through the application's redaction policy. Caliper does not redact addresses,
SDP credentials, credentials in application notes, or certificate fingerprints.
note(label, value) adds application JSON data. Caliper does not replace browser constructors
or methods and cannot observe a failed method call unless the application records it.
Each entry has schemaVersion: 1, a sequence seq, wall-clock at, connectionId, type,
label, and optional value. Types are attach, event, sdp, stats, and note.
Entries are owned and frozen. Every statistics entry is a complete snapshot.
The default statsIntervalMs is 1,000 ms. Recording uses the supplied monitor and adds no poll.
When records come from multiple logging runs, map (runId, connectionId) to a unique connection
ID before calling the builder. Keep the recorder's seq. The builder orders entries by at
and then seq. It skips invalid entries, duplicate sequences, and truncated snapshots with warnings.
It warns when attachment metadata is absent, incomplete, or truncated. Put these warnings in the export manifest.
Application notes use the viewer event type application-note. Their JSON values contain
the original label and value. JSON escapes prevent the viewer from treating note text as SDP.
It does not create missing events. Missing statistic values use null gaps, not zeroes.
The builder returns { dump, warnings }. It supplies UserAgentData for the maintained viewer;
pass browser brand/version data when available. The default is an empty array. No browser version
is invented. The tested rtcstats importer
revision is 8676135e6bad0473556bbeb3f6ceb92398f89e8c.
Native Chrome 154.0.8037.98, Firefox 150.0.2, and Safari 26.6.2 recordings passed that check.
This file describes observed page activity. It is not a native browser diagnostic dump.
Call identity
Caliper does not add call, user, or tenant identifiers. Log warning changes and the final report
through an application logger context that contains the call ID. Supply end values, such as the
SIP status, to report(end). After recorder construction, write recorder.note('call', { callId })
once for each recorder. To retain the call ID in an exported dump, keep this note in the entries
supplied to buildWebrtcInternalsDump. Apply the application's redaction policy to identifiers
in logger context and recorded entries before storage or export.
Bounded storage can remove the first entries of a long call. Also include the call ID in the
application's export metadata. Apply the same redaction policy to that metadata.
Recording budgets and export cost
At one snapshot per second, the recorded Chrome audio/video fixture used approximately 10,900 JSON characters per second per connection, including logging fields. Ten minutes used 6.5 million characters. One hour needs approximately 39 million characters. Actual size depends on the browser, stream count, and application fields. Complete snapshots retain all candidate pairs and static fields.
Choose storage size, age, and record-count limits together. Hopper's default 1,000,000-character bucket budget holds approximately 90 seconds of this fixture. Its 16,000,000-character total budget is shared by all buckets. The ten-minute replay used explicit 32,000,000-character bucket and total budgets, a 610,000 ms age limit, and 1,000 records per bucket. These are measured test settings. Measure the final application's complete redaction and storage path before selecting its limits.
Dump building is synchronous and keeps the input, copied observations, and output series in memory. A 3,600-snapshot replay took approximately 279 ms to build on Node 24.7.0 on macOS. Heap use rose by approximately 54 MB during the build, to 78 MB. This is not a peak-memory limit. Use a worker for large exports in a browser. The builder's input and output are JSON data.
Audio and video
import { createAudioLevelMeter, toLinearLevel } from '@bazariodev/caliper/audio';
import { createVideoProgressMonitor } from '@bazariodev/caliper/video';
export function showLevels(stream, audioContext, onLevel) {
const meter = createAudioLevelMeter({ stream, audioContext });
meter.subscribe((rms) => onLevel(toLinearLevel(rms)));
return meter;
}
export function observeVideo(monitor, receiver, onState) {
const video = createVideoProgressMonitor({ monitor, receiver });
video.subscribe(onState);
return video;
}Audio construction starts one 250 ms timer. Only a running AudioContext produces measurements.
Set fftSize to select the analyser window in samples, for example 256 for a call meter or
512 for a microphone test. Use a power of two from 32 through 32768. Invalid values throw
RangeError before node creation. If omitted, the analyser keeps its native default of 2048.
getLevel() returns the last measured level, initially zero. It retains that level while the
context is suspended or closed and after stop(). No new levels are published while suspended.
RMS uses byte time-domain samples: sqrt(mean(((sample - 128) / 128) ** 2)); empty input gives zero.
The meter does not resume or close the context, stop tracks, or connect to the destination.
stop() cancels its timer and disconnects its nodes. Stop is terminal and safe to repeat.
toLinearLevel(rms, gain = 3) clamps rms * gain to [0, 1].
toDecibelLevel(rms, options) clamps
(20 * log10(max(rms, silenceFloor)) - minimumDecibels) / -minimumDecibels * maximumLevel
to [0, maximumLevel]. The reference settings are minimumDecibels: -60,
silenceFloor: 0.00001, and maximumLevel: 100.
Video consumes monitor samples and never calls receiver.getStats(). Use a shared monitor
interval of 250 ms for fast video detection. The receiver maps to one transceiver mid and
one inbound video stream. Missing or ambiguous associations return unknown.
The first decoded-frame count establishes a baseline. Progress gives flowing; no progress
for stallAfterMs (default 1,500 ms) gives stalled. Progress clears a stall.
An ended track, inactive receive direction, counter reset, new stream ID, invalid timestamp,
or a gap above max(2,000 ms, stallAfterMs) resets the baseline to unknown.
Timing uses the selected stream's statistics timestamp. Only state changes notify subscribers.
stop() removes the subscription and is terminal. Caliper does not attempt media recovery.
Behavior
- Imports start no work. Monitor construction adds a peer-state listener but starts no read or timer.
start()starts polling at 1,000 ms by default. Repeated starts do not add timers.- One monitor owns at most one physical
getStats()call. A slow read causes missed ticks to be skipped. sample()joins a current read. A manual-only read does not notify subscribers.stop()pauses polling, cancels the timer, and invalidates pending results. Subscriptions remain.- Restart creates fresh rate baselines. An old physical read must settle before another can start.
- A manual caller behind an old read waits for settlement, then starts or joins a fresh read.
- Shutdown during that wait rejects the pending request with
AbortError. dispose()is terminal. It removes listeners and subscriptions. Peer closure also stops polling and rejects future samples. A local close without an event stops polling at the next tick. Call methods on the returned monitor object.- Normalized samples and their nested values are owned and frozen. Raw reports remain browser values.
- The monitor's public object is frozen. Its methods still control its private state.
- Stream IDs and statistics timestamps determine rates. New IDs, decreased packet or byte counters, and invalid time intervals establish fresh baselines. Missing counters remain absent.
- Late or duplicate packets can reduce
packetsLost. A decrease in that value alone does not reset rates or the quality window. Loss calculations clamp the lost-packet delta to zero. - Bitrate is
8 * deltaBytes / deltaMillisecondsin kbps. Inbound loss ismax(0, deltaLost) / (deltaReceived + max(0, deltaLost))for a positive denominator. - RTT and jitter are milliseconds. Referenced IDs select codecs and candidate pairs. An unknown
selected pair remains absent. Without a transport selection reference, one candidate pair with
selected === truecan supply the selected pair and RTT. Multiple selected pairs remain unknown. A nominated or successful pair alone does not prove selection. Local audio level is the maximum reported audio-source level. - Listener errors go to
logger.warn. Logger errors are contained. A failed read does not stop polling. - Custom schedulers provide asynchronous, nonthrowing
setTimeoutandclearTimeoutmethods. Delayed callbacks do not cause a burst of missed work. Browser throttling can still delay work.
Quality observations
The tracker accepts at most one sample per wall-clock second. Non-increasing buckets do not alter baselines or totals. Missing values do not count as good observations. A gap above two seconds resets pending warning windows. It does not establish an audio interruption.
| Warning | Raise | Clear |
| --- | --- | --- |
| high-rtt | RTT above 400 ms in 3 of 5 valid observations | At or below 400 ms in 3 of 5 |
| high-jitter | Maximum inbound audio jitter above 30 ms in 3 of 5 valid observations | At or below 30 ms in 3 of 5 |
| high-packet-loss | Packet-weighted inbound audio loss above 3% over 7 seconds | At or below 1% over 7 seconds |
| no-inbound-audio | No packet progress for 5 consecutive eligible seconds | Packets arrive or inbound audio is not expected |
| silent-microphone | Source level below 0.001 for 10 consecutive eligible seconds | Level rises, microphone is muted, or no eligible audio sender remains |
RTT/jitter need a complete valid observation window. Packet loss needs a complete time window
with valid packet and loss counters for every inbound audio stream. Incomplete intervals do not
enter loss summaries. Missing counters, decreased received-packet counters, and stream changes
reset the loss window.
Packet progress does not require loss counters. Each inbound audio stream needs readable packet
counters before a no-packet warning can be raised. Missing counters and stream changes reset
that baseline. Known packet progress can clear the warning when another stream is unknown.
Missing audio levels cannot raise a microphone warning. Warning changes omit unavailable values.
Microphone silence requires a connected peer and a live audio sender with currentDirection
set to sendrecv or sendonly. The tracker checks the sender and direction on the same
transceiver. A transceiver with direction: 'stopped' is excluded immediately after stop(),
even if currentDirection still permits sending and the sender track remains live.
Other preferred direction values do not establish negotiated sending.
When no eligible sender remains, the next accepted sample clears an active microphone warning
and resets its pending duration. Sending must resume for a full new silence interval before
the warning can be raised again. Application mute and hold policy remain in microphoneMuted.
An ended sender track also stops silence detection. A track can end when its device disconnects.
To find this microphone loss, monitor the track ended event in the application.
expectedInboundAudio affects only inbound audio warnings.
Thresholds are validated at construction. Time windows are positive; sample counts are positive
integers. Numeric cutoffs can be zero; fractions are in [0, 1], with clear loss at most raise loss.
The tracker calculates packet and byte deltas from its accepted observations. Faster samples
cannot remove traffic from quality totals. Reports accumulate byte deltas across stream replacement,
omit unavailable metrics, and exclude candidate addresses. Loss averages use packet weighting.
Warning history holds at most maxWarningChanges entries (default 1,000).
droppedWarningChanges counts later changes; active state and aggregates continue.
The first report(end) finalizes and caches an owned report. Later pushes do nothing.
Duration starts at tracker construction. An empty report has sampleCount: 0, zero byte totals,
and no metric summaries.
API
| Import | Exports |
| --- | --- |
| @bazariodev/caliper | createMediaStatsMonitor and monitor/sample types |
| @bazariodev/caliper/quality | createCallQualityTracker, DEFAULT_QUALITY_THRESHOLDS, quality types |
| @bazariodev/caliper/dump | createRtcDumpRecorder, buildWebrtcInternalsDump, dump types |
| @bazariodev/caliper/audio | createAudioLevelMeter, toLinearLevel, toDecibelLevel, meter types |
| @bazariodev/caliper/video | createVideoProgressMonitor and video types |
The root does not re-export optional entries. The application owns peer connections, tracks, the AudioContext, recording policy, redaction, storage, and the user interface.
Errors
Unsupported required capabilities and invalid function options throw TypeError at construction.
Invalid numeric configuration throws RangeError. A sample after disposal or peer closure rejects
with a DOMException named InvalidStateError. An invalidated pending sample rejects with a
DOMException named AbortError after its physical
read settles. Other read errors reject the manual sample and go to logger.warn.
Audio setup errors disconnect resources already created. Recorder callback and logger failures
are contained. Invalid dump records produce builder warnings.
TypeScript
Declarations support strict ESM and CommonJS consumers. Browser entries need DOM.
The optional disposal symbol needs ESNext.Disposable; its declarations reference that library.
Explicit dispose() works when Symbol.dispose is absent. The symbol alias exists only when
the runtime supplies the symbol. The quality entry has no DOM requirement.
{ "compilerOptions": { "lib": ["ES2022", "DOM", "ESNext.Disposable"] } }License
MIT.
