@furious.luke/argus-js 0.5.5 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -66,6 +66,7 @@ const publisher = new Publisher({
66
66
  });
67
67
  },
68
68
  onConnectionStateChange: (state) => console.log("state:", state),
69
+ onConnectionQualityChange: ({ level }) => console.log("connection quality:", level),
69
70
  onRecoveryStateChange: (event) => console.log("media recovery:", event),
70
71
  // Show a button or prompt. From its click handler, call captureScreen()
71
72
  // and then publisher.publish(newStream, "screen").
@@ -201,6 +202,9 @@ not the `utterance_finished` lifecycle event, which can overtake the last chunk.
201
202
  | `peerConnectionTimeoutMs` | `number` | Deadline after the initial offer for WebRTC to reach `connected`. Defaults to 30 seconds. |
202
203
  | `signalingReconnectTimeoutMs` | `number` | How long to retry a dropped signaling socket against the selected regional gateway. Defaults to 20 seconds. |
203
204
  | `preferredVideoCodecs` | `string[]` | Preferred video codecs, most-preferred first, as RTP MIME types (e.g. `"video/VP9"`, `"video/H264"`). Each published video track offers these ahead of the rest, so the browser sends the first one the media server also accepts. Defaults to `["video/VP9"]`. Pass `[]` to leave the browser's native order untouched. Codecs the browser lacks (or `setCodecPreferences` support, e.g. older Safari) are ignored — negotiation always falls back cleanly. |
205
+ | `connectionStatsIntervalMs` | `number` | How often to poll `RTCPeerConnection.getStats()` for connection-quality assessment while connected. Defaults to 2000. Set to `0` to disable stats polling entirely (`onConnectionStats`/`onConnectionQualityChange` will not fire). |
206
+ | `connectionQualityThresholds` | `Partial<ConnectionQualityThresholds>` | Overrides for the quality classification thresholds. Packet loss is the primary axis; RTT and jitter can only push the level worse, never better. Any omitted field keeps its default (see below). |
207
+ | `connectionQualityDebounceSamples` | `number` | Consecutive worse-than-current samples required before a downgrade is committed, damping transient blips. Improvements are reported on the first better sample. Defaults to 2. |
204
208
  | `callbacks` | `PublisherCallbacks` | Optional lifecycle callbacks (see below). |
205
209
 
206
210
  ### Methods & properties
@@ -235,6 +239,9 @@ not the `utterance_finished` lifecycle event, which can overtake the last chunk.
235
239
  | `onAssistantText({ utteranceId, text })` | One caption chunk arrived; paced with synthesized speech when speech is enabled, immediate in text-only mode. An utterance emits many chunks sharing one `utteranceId` — append them to the bubble keyed by that id rather than rendering each separately. |
236
240
  | `onAssistantTextFinished({ utteranceId })` | The utterance's caption stream is complete. Emitted on the same ordered channel after its last `onAssistantText` chunk; finalize the visible caption here rather than on `utterance_finished`. |
237
241
  | `onUserTextResult({ messageId, accepted, reason })` | The server accepted or rejected a `sendUserText` message. |
242
+ | `onConnectionStats(sample)` | A periodic `ConnectionStatsSample` (loss ratio, RTT, jitter, send/available bitrate, encoder limitation) — the raw feed behind `onConnectionQualityChange`. Fires every `connectionStatsIntervalMs` while connected. |
243
+ | `onConnectionQualityChange({ level, sample })` | The derived connection-quality level (`"good" \| "fair" \| "poor" \| "critical"`) changed, including the first assessment after connecting. Downgrades are debounced; upgrades fire immediately. React to a degrading uplink here — warn the user, or drop a secondary track. |
244
+ | `onSpeechQualityChange({ degraded, realtimeFactor })` | Server-side text-to-speech generation crossed the realtime boundary: `degraded: true` when the TTS provider dropped below realtime (`realtimeFactor` < 1.0), synthesizing slower than it plays and starving playout, `degraded: false` once it climbs comfortably back above realtime. The degraded transition is raised **live during synthesis** (a long, slow utterance is reported while it happens, not at its end). Edge-triggered (no flapping at the boundary). A **distinct axis from `onConnectionQualityChange`** (that is network health) — react by warning the user or offering a text fallback. |
238
245
  | `onError(error)` | A fatal error occurred (signaling error, WebRTC connection failure/timeout, or signaling resume timed out). |
239
246
 
240
247
  ## How `start()` works
@@ -287,6 +294,53 @@ pass it to `publish` (or `replaceStream`) for that track type. A browser cannot
287
294
  silently reacquire a screen share after the user or operating system ends it, so
288
295
  `capture_ended` always requires host UI and a fresh `captureScreen()` call.
289
296
 
297
+ ## Connection quality
298
+
299
+ While connected, the publisher polls the peer connection's WebRTC stats every
300
+ `connectionStatsIntervalMs` (default 2s) and derives a coarse quality level so
301
+ you can react to a degrading uplink without parsing `getStats()` yourself. Each
302
+ poll delivers a raw `ConnectionStatsSample` to `onConnectionStats`; whenever the
303
+ derived level changes it delivers a `ConnectionQuality` to
304
+ `onConnectionQualityChange`.
305
+
306
+ ```ts
307
+ const pub = new Publisher({
308
+ gatewayURLs,
309
+ token,
310
+ callbacks: {
311
+ onConnectionQualityChange: ({ level, sample }) => {
312
+ if (level === "poor" || level === "critical") {
313
+ showBanner(`Weak connection — ${Math.round(sample.lossRatio * 100)}% packet loss`);
314
+ } else {
315
+ hideBanner();
316
+ }
317
+ },
318
+ },
319
+ });
320
+ ```
321
+
322
+ Packet loss is the primary signal; round-trip time, jitter, and a
323
+ bandwidth-limited encoder can only push the level worse, never better. To avoid
324
+ flapping on a momentary blip, **downgrades** are debounced — they require
325
+ `connectionQualityDebounceSamples` (default 2) consecutive worse samples before
326
+ committing — while **upgrades** are reported on the first improved sample so
327
+ recovery is reflected promptly. The first sample after connecting always emits
328
+ the baseline level.
329
+
330
+ The default `ConnectionQualityThresholds` (all overridable via
331
+ `connectionQualityThresholds`):
332
+
333
+ | Level | Packet loss | RTT | Jitter |
334
+ | --- | --- | --- | --- |
335
+ | `fair` | ≥ 2% | ≥ 300 ms | ≥ 50 ms |
336
+ | `poor` | ≥ 5% | ≥ 600 ms | ≥ 150 ms |
337
+ | `critical` | ≥ 12% | ≥ 1000 ms | — |
338
+
339
+ Loss ratio and send bitrate are windowed over each interval; RTT, jitter, and
340
+ available bitrate are point-in-time. A sample field is `null` when the browser
341
+ did not report the underlying stat. This is a detection surface only — the
342
+ publisher does not itself lower bitrate or resolution in response.
343
+
290
344
  ## Browser support
291
345
 
292
346
  Requires a browser with WebRTC (`RTCPeerConnection`) and `WebSocket` — all current evergreen browsers. There is no Node.js runtime support; this is a browser-only package.
package/dist/index.cjs CHANGED
@@ -94,6 +94,28 @@ function selectGatewayTURNURLs(advertised, policy = "all") {
94
94
  }
95
95
  return selected;
96
96
  }
97
+ var qualityLevels = ["good", "fair", "poor", "critical"];
98
+ function qualitySeverity(level) {
99
+ return qualityLevels.indexOf(level);
100
+ }
101
+ function nowMs() {
102
+ return typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
103
+ }
104
+ var limitationSeverity = { none: 0, other: 1, cpu: 2, bandwidth: 3 };
105
+ function worseLimitation(current, next) {
106
+ if (current === null) return next;
107
+ return (limitationSeverity[next] ?? 1) > (limitationSeverity[current] ?? 1) ? next : current;
108
+ }
109
+ function findNominatedCandidatePair(stats) {
110
+ let found;
111
+ stats.forEach((report) => {
112
+ const value = report;
113
+ if (!found && value.type === "candidate-pair" && value.state === "succeeded" && value.nominated === true) {
114
+ found = value;
115
+ }
116
+ });
117
+ return found;
118
+ }
97
119
  var defaultSignalingReconnectTimeoutMs = 2e4;
98
120
  var defaultGatewayHandshakeTimeoutMs = 2e4;
99
121
  var defaultPeerConnectionTimeoutMs = 3e4;
@@ -114,6 +136,18 @@ var negotiationReconnectGraceMs = 5e3;
114
136
  var minimumIntentionalTrackEndRetentionMs = 35e3;
115
137
  var maxUserTextBytes = 4 * 1024;
116
138
  var maxRetainedICECandidates = 64;
139
+ var defaultConnectionStatsIntervalMs = 2e3;
140
+ var defaultConnectionQualityDebounceSamples = 2;
141
+ var defaultConnectionQualityThresholds = {
142
+ fairLossRatio: 0.02,
143
+ poorLossRatio: 0.05,
144
+ criticalLossRatio: 0.12,
145
+ fairRttMs: 300,
146
+ poorRttMs: 600,
147
+ criticalRttMs: 1e3,
148
+ fairJitterMs: 50,
149
+ poorJitterMs: 150
150
+ };
117
151
  var ReportedPublisherError = class extends Error {
118
152
  constructor(message, fatal = false) {
119
153
  super(message);
@@ -156,6 +190,17 @@ var Publisher = class {
156
190
  gatewayURL = null;
157
191
  lastReportedICEPath = null;
158
192
  watchedICETransports = /* @__PURE__ */ new WeakSet();
193
+ // Periodic getStats() polling for connection-quality assessment. The timer runs
194
+ // only while connected; lastStatsSample anchors the windowed loss/bitrate deltas
195
+ // (loss is tracked per outbound SSRC so it can be paired to the remote's report),
196
+ // and currentQualityLevel/qualityDowngradeStreak drive the debounced classifier.
197
+ connectionStatsTimer = null;
198
+ // Guards against overlapping getStats() calls: if one outlives the interval,
199
+ // ticks are skipped until it resolves so samples never complete out of order.
200
+ statsSampleInFlight = false;
201
+ lastStatsSample = null;
202
+ currentQualityLevel = null;
203
+ qualityDowngradeStreak = 0;
159
204
  stopped = true;
160
205
  // Every start/stop boundary advances lifecycleGeneration. Async work captures
161
206
  // the generation it belongs to and may never mutate or terminate a later run.
@@ -368,10 +413,13 @@ var Publisher = class {
368
413
  if (state === "connected") {
369
414
  this.clearPeerConnectionTimeout();
370
415
  void this.reportSelectedICEPath(pc);
416
+ this.startConnectionStatsLoop(generation, pc);
371
417
  this.opts.callbacks?.onConnected?.();
372
418
  } else if (state === "failed") {
373
419
  this.clearPeerConnectionTimeout();
374
420
  this.terminateWithError(new Error("WebRTC connection failed"), true, generation);
421
+ } else {
422
+ this.stopConnectionStatsLoop();
375
423
  }
376
424
  };
377
425
  if (initialTrack) {
@@ -506,6 +554,7 @@ var Publisher = class {
506
554
  this.runAbort?.abort();
507
555
  this.runAbort = null;
508
556
  this.clearPeerConnectionTimeout();
557
+ this.stopConnectionStatsLoop();
509
558
  this.stopped = true;
510
559
  this.cancelAllMediaRecovery();
511
560
  this.reconnectGeneration++;
@@ -994,6 +1043,7 @@ var Publisher = class {
994
1043
  this.runAbort?.abort();
995
1044
  this.runAbort = null;
996
1045
  this.clearPeerConnectionTimeout();
1046
+ this.stopConnectionStatsLoop();
997
1047
  this.stopped = true;
998
1048
  this.cancelAllMediaRecovery();
999
1049
  this.reconnectGeneration++;
@@ -1071,6 +1121,17 @@ var Publisher = class {
1071
1121
  this.completeMediaRecovery(msg.track);
1072
1122
  break;
1073
1123
  }
1124
+ case "speech_slow": {
1125
+ this.opts.callbacks?.onSpeechQualityChange?.({
1126
+ degraded: true,
1127
+ realtimeFactor: msg.realtime_factor
1128
+ });
1129
+ break;
1130
+ }
1131
+ case "speech_recovered": {
1132
+ this.opts.callbacks?.onSpeechQualityChange?.({ degraded: false });
1133
+ break;
1134
+ }
1074
1135
  case "error": {
1075
1136
  const err = new ReportedPublisherError(msg.error, msg.fatal === true);
1076
1137
  const pending = this.pendingAnswer;
@@ -1464,6 +1525,249 @@ var Publisher = class {
1464
1525
  } catch {
1465
1526
  }
1466
1527
  }
1528
+ // startConnectionStatsLoop begins periodic getStats() sampling once the peer
1529
+ // connection is connected. It is a no-op when polling is disabled or no
1530
+ // consumer is listening, and it re-baselines on each call so a reconnect after
1531
+ // an ICE restart starts a fresh quality assessment.
1532
+ startConnectionStatsLoop(generation, pc) {
1533
+ const intervalMs = Math.max(
1534
+ 0,
1535
+ this.opts.connectionStatsIntervalMs ?? defaultConnectionStatsIntervalMs
1536
+ );
1537
+ const listening = !!this.opts.callbacks?.onConnectionStats || !!this.opts.callbacks?.onConnectionQualityChange;
1538
+ if (intervalMs === 0 || !listening) return;
1539
+ this.stopConnectionStatsLoop();
1540
+ const timer = setInterval(() => {
1541
+ if (this.connectionStatsTimer !== timer) return;
1542
+ if (!this.isActiveRun(generation, pc)) {
1543
+ this.stopConnectionStatsLoop();
1544
+ return;
1545
+ }
1546
+ if (this.statsSampleInFlight) return;
1547
+ this.statsSampleInFlight = true;
1548
+ void this.sampleConnectionQuality(generation, pc, timer);
1549
+ }, intervalMs);
1550
+ this.connectionStatsTimer = timer;
1551
+ }
1552
+ stopConnectionStatsLoop() {
1553
+ if (this.connectionStatsTimer !== null) clearInterval(this.connectionStatsTimer);
1554
+ this.connectionStatsTimer = null;
1555
+ this.statsSampleInFlight = false;
1556
+ this.lastStatsSample = null;
1557
+ this.currentQualityLevel = null;
1558
+ this.qualityDowngradeStreak = 0;
1559
+ }
1560
+ async sampleConnectionQuality(generation, pc, timer) {
1561
+ let stats = null;
1562
+ try {
1563
+ stats = await pc.getStats();
1564
+ } catch {
1565
+ }
1566
+ if (this.connectionStatsTimer !== timer) return;
1567
+ this.statsSampleInFlight = false;
1568
+ if (!stats || !this.isActiveRun(generation, pc) || pc.connectionState !== "connected") {
1569
+ return;
1570
+ }
1571
+ const sample = this.buildStatsSample(stats);
1572
+ this.opts.callbacks?.onConnectionStats?.(sample);
1573
+ if (this.connectionStatsTimer !== timer || !this.isActiveRun(generation, pc) || pc.connectionState !== "connected") {
1574
+ return;
1575
+ }
1576
+ this.updateConnectionQuality(sample);
1577
+ }
1578
+ // buildStatsSample derives one sample from a getStats() report. Loss is a mean of
1579
+ // per-stream loss fractions weighted by each stream's packets sent this window, so
1580
+ // every stream carrying traffic contributes. A stream uses its remote fractionLost
1581
+ // when present — the remote's loss ratio over its RR interval, self-aligned and
1582
+ // excluding retransmissions (which ride a separate SSRC); dividing the remote's
1583
+ // Δ(packetsLost) by the local Δ(packetsSent) would instead misalign an RTCP-timed
1584
+ // numerator with a continuously-updated denominator — and otherwise falls back to
1585
+ // its own windowed Δ(packetsLost) / Δ(distinct media packets sent), a denominator
1586
+ // that excludes retransmissions (packetsSent - retransmittedPacketsSent). Mixing the
1587
+ // two per stream keeps a lossy stream from being dropped when a sibling has fractionLost.
1588
+ //
1589
+ // Deltas are taken only over outbound stats-object ids present in BOTH this and the
1590
+ // previous sample. A track replace/unpublish (or a recycled SSRC) deletes the old
1591
+ // stats object and creates a new one with a new id; counting a vanished stream's
1592
+ // missing tail, or a fresh object's cumulative total as an interval delta, would
1593
+ // corrupt loss. Excluding the symmetric difference baselines new objects (they count
1594
+ // from their next sample) and drops departed ones, so continuous streams still measure
1595
+ // loss even when an SSRC number is reused across distinct stats objects.
1596
+ buildStatsSample(stats) {
1597
+ const timestamp = nowMs();
1598
+ let nackCount = 0;
1599
+ let pliCount = 0;
1600
+ let haveOutbound = false;
1601
+ let haveOutboundVideo = false;
1602
+ let rttSeconds = null;
1603
+ let jitterSeconds = null;
1604
+ let limitationReason = null;
1605
+ let selectedPairID;
1606
+ let transportBytes = null;
1607
+ const streams = /* @__PURE__ */ new Map();
1608
+ const ssrcToId = /* @__PURE__ */ new Map();
1609
+ stats.forEach((report) => {
1610
+ const value = report;
1611
+ switch (value.type) {
1612
+ case "outbound-rtp": {
1613
+ haveOutbound = true;
1614
+ if (value.kind === "video") haveOutboundVideo = true;
1615
+ const ssrc = typeof value.ssrc === "number" ? value.ssrc : NaN;
1616
+ const sent = typeof value.packetsSent === "number" ? value.packetsSent : 0;
1617
+ const retransmitted = typeof value.retransmittedPacketsSent === "number" ? value.retransmittedPacketsSent : 0;
1618
+ const bytesSent = typeof value.bytesSent === "number" ? value.bytesSent : 0;
1619
+ if (typeof value.nackCount === "number") nackCount += value.nackCount;
1620
+ if (typeof value.pliCount === "number") pliCount += value.pliCount;
1621
+ if (typeof value.qualityLimitationReason === "string") {
1622
+ limitationReason = worseLimitation(limitationReason, value.qualityLimitationReason);
1623
+ }
1624
+ if (typeof value.id === "string") {
1625
+ const expected = Math.max(0, sent - retransmitted);
1626
+ streams.set(value.id, { expected, lost: null, fractionLost: null, bytesSent });
1627
+ if (!Number.isNaN(ssrc)) ssrcToId.set(ssrc, value.id);
1628
+ }
1629
+ break;
1630
+ }
1631
+ case "remote-inbound-rtp": {
1632
+ if (typeof value.roundTripTime === "number") {
1633
+ rttSeconds = Math.max(rttSeconds ?? 0, value.roundTripTime);
1634
+ }
1635
+ if (typeof value.jitter === "number") {
1636
+ jitterSeconds = Math.max(jitterSeconds ?? 0, value.jitter);
1637
+ }
1638
+ break;
1639
+ }
1640
+ case "transport": {
1641
+ if (typeof value.selectedCandidatePairId === "string") {
1642
+ selectedPairID = value.selectedCandidatePairId;
1643
+ }
1644
+ if (typeof value.bytesSent === "number") {
1645
+ transportBytes = (transportBytes ?? 0) + value.bytesSent;
1646
+ }
1647
+ break;
1648
+ }
1649
+ default:
1650
+ break;
1651
+ }
1652
+ });
1653
+ stats.forEach((report) => {
1654
+ const value = report;
1655
+ if (value.type !== "remote-inbound-rtp") return;
1656
+ const outboundId = typeof value.localId === "string" && streams.has(value.localId) ? value.localId : typeof value.ssrc === "number" ? ssrcToId.get(value.ssrc) : void 0;
1657
+ if (outboundId === void 0) return;
1658
+ const stream = streams.get(outboundId);
1659
+ if (!stream) return;
1660
+ const lost = typeof value.packetsLost === "number" ? value.packetsLost : 0;
1661
+ stream.lost = (stream.lost ?? 0) + lost;
1662
+ if (typeof value.fractionLost === "number" && Number.isFinite(value.fractionLost)) {
1663
+ stream.fractionLost = Math.min(1, Math.max(0, value.fractionLost));
1664
+ }
1665
+ });
1666
+ const pair = (selectedPairID ? stats.get(selectedPairID) : void 0) ?? findNominatedCandidatePair(stats);
1667
+ const availableOutgoingBitrate = pair && typeof pair.availableOutgoingBitrate === "number" ? pair.availableOutgoingBitrate : null;
1668
+ if (rttSeconds === null && pair && typeof pair.currentRoundTripTime === "number") {
1669
+ rttSeconds = pair.currentRoundTripTime;
1670
+ }
1671
+ const prev = this.lastStatsSample;
1672
+ let weightedFractionSum = 0;
1673
+ let weightSum = 0;
1674
+ let intersectionBytesDelta = 0;
1675
+ let hadStreamOverlap = false;
1676
+ streams.forEach((current, id) => {
1677
+ const before = prev?.streams.get(id);
1678
+ if (!before) return;
1679
+ hadStreamOverlap = true;
1680
+ intersectionBytesDelta += Math.max(0, current.bytesSent - before.bytesSent);
1681
+ const deltaExpected = Math.max(0, current.expected - before.expected);
1682
+ if (deltaExpected <= 0) return;
1683
+ let fraction = null;
1684
+ if (current.fractionLost !== null) {
1685
+ fraction = current.fractionLost;
1686
+ } else if (current.lost !== null && before.lost !== null) {
1687
+ fraction = Math.min(1, Math.max(0, current.lost - before.lost) / deltaExpected);
1688
+ }
1689
+ if (fraction === null) return;
1690
+ weightedFractionSum += fraction * deltaExpected;
1691
+ weightSum += deltaExpected;
1692
+ });
1693
+ const deltaSeconds = prev ? (timestamp - prev.timestamp) / 1e3 : 0;
1694
+ this.lastStatsSample = { timestamp, transportBytes, streams };
1695
+ const lossRatio = weightSum > 0 ? Math.min(1, weightedFractionSum / weightSum) : 0;
1696
+ let sendBitrate = null;
1697
+ if (prev && deltaSeconds > 0) {
1698
+ if (transportBytes !== null && prev.transportBytes !== null) {
1699
+ sendBitrate = Math.max(0, transportBytes - prev.transportBytes) * 8 / deltaSeconds;
1700
+ } else if (hadStreamOverlap) {
1701
+ sendBitrate = intersectionBytesDelta * 8 / deltaSeconds;
1702
+ }
1703
+ }
1704
+ return {
1705
+ timestamp,
1706
+ lossRatio,
1707
+ rttMs: rttSeconds !== null ? rttSeconds * 1e3 : null,
1708
+ jitterMs: jitterSeconds !== null ? jitterSeconds * 1e3 : null,
1709
+ availableOutgoingBitrate,
1710
+ sendBitrate,
1711
+ qualityLimitationReason: haveOutboundVideo ? limitationReason ?? "none" : null,
1712
+ nackCount: haveOutbound ? nackCount : null,
1713
+ pliCount: haveOutbound ? pliCount : null
1714
+ };
1715
+ }
1716
+ resolveQualityThresholds() {
1717
+ return { ...defaultConnectionQualityThresholds, ...this.opts.connectionQualityThresholds ?? {} };
1718
+ }
1719
+ // classifyQuality maps a sample to a level. Loss is the primary axis; RTT,
1720
+ // jitter, and a bandwidth-limited encoder can only raise severity.
1721
+ classifyQuality(sample) {
1722
+ const t = this.resolveQualityThresholds();
1723
+ let severity = 0;
1724
+ if (sample.lossRatio >= t.criticalLossRatio) severity = Math.max(severity, 3);
1725
+ else if (sample.lossRatio >= t.poorLossRatio) severity = Math.max(severity, 2);
1726
+ else if (sample.lossRatio >= t.fairLossRatio) severity = Math.max(severity, 1);
1727
+ if (sample.rttMs !== null) {
1728
+ if (sample.rttMs >= t.criticalRttMs) severity = Math.max(severity, 3);
1729
+ else if (sample.rttMs >= t.poorRttMs) severity = Math.max(severity, 2);
1730
+ else if (sample.rttMs >= t.fairRttMs) severity = Math.max(severity, 1);
1731
+ }
1732
+ if (sample.jitterMs !== null) {
1733
+ if (sample.jitterMs >= t.poorJitterMs) severity = Math.max(severity, 2);
1734
+ else if (sample.jitterMs >= t.fairJitterMs) severity = Math.max(severity, 1);
1735
+ }
1736
+ if (sample.qualityLimitationReason === "bandwidth") severity = Math.max(severity, 1);
1737
+ return qualityLevels[severity];
1738
+ }
1739
+ // updateConnectionQuality commits level transitions with hysteresis: an
1740
+ // improvement is reported on the first better sample, while a degradation must
1741
+ // persist for connectionQualityDebounceSamples consecutive samples to commit,
1742
+ // so a single blip does not flap the reported level.
1743
+ updateConnectionQuality(sample) {
1744
+ const candidate = this.classifyQuality(sample);
1745
+ const current = this.currentQualityLevel;
1746
+ if (current === null || candidate === current) {
1747
+ this.qualityDowngradeStreak = 0;
1748
+ if (candidate !== current) {
1749
+ this.currentQualityLevel = candidate;
1750
+ this.opts.callbacks?.onConnectionQualityChange?.({ level: candidate, sample });
1751
+ }
1752
+ return;
1753
+ }
1754
+ if (qualitySeverity(candidate) < qualitySeverity(current)) {
1755
+ this.qualityDowngradeStreak = 0;
1756
+ this.currentQualityLevel = candidate;
1757
+ this.opts.callbacks?.onConnectionQualityChange?.({ level: candidate, sample });
1758
+ return;
1759
+ }
1760
+ const needed = Math.max(
1761
+ 1,
1762
+ this.opts.connectionQualityDebounceSamples ?? defaultConnectionQualityDebounceSamples
1763
+ );
1764
+ this.qualityDowngradeStreak += 1;
1765
+ if (this.qualityDowngradeStreak >= needed) {
1766
+ this.qualityDowngradeStreak = 0;
1767
+ this.currentQualityLevel = candidate;
1768
+ this.opts.callbacks?.onConnectionQualityChange?.({ level: candidate, sample });
1769
+ }
1770
+ }
1467
1771
  async reportSelectedICEPath(pc) {
1468
1772
  if (this.pc !== pc || this.stopped) return;
1469
1773
  let stats;