@reactor-team/js-sdk 3.0.2 → 3.1.0

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/dist/index.d.cts CHANGED
@@ -476,7 +476,7 @@ interface ReactorEventMap {
476
476
  * that want the binding's own identifier (e.g. for
477
477
  * `getTrackByMid`/`getStreamByMid`). */
478
478
  trackReceived: (name: string, track: MediaStreamTrack, stream: MediaStream, mid: string | undefined) => void;
479
- /** Fired every `STATS_INTERVAL_MS` while the session is "ready" — see
479
+ /** Fired every `LOCAL_STATS_INTERVAL_MS` while the session is "ready" — see
480
480
  * `getStats()`. */
481
481
  statsUpdate: (stats: ConnectionStats) => void;
482
482
  }
@@ -623,11 +623,14 @@ declare class Reactor implements Disposable {
623
623
  private capabilities;
624
624
  private stats;
625
625
  private connectionTimings;
626
- private statsPollHandle;
627
- /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
628
- * in-flight `getStats()` recognize it's stale once it resolves, even if
629
- * `this.client` hasn't changed in the meantime. */
630
- private statsPollGeneration;
626
+ /** The stop functions of the running stats pollers — see `pollPeerStats()`. */
627
+ private stopStatsPollers;
628
+ /** Whether this connection has already reported its time to connect —
629
+ * a one-time fact, sent on the first client-stats report that carries it
630
+ * and omitted on every one after. Set only once a batch actually went out
631
+ * with it, so a batch sent before the timings exist doesn't use it up.
632
+ * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */
633
+ private hasSentConnectTime;
631
634
  /** Set on the "connecting" status transition, cleared once `connectionTimings`
632
635
  * is finalized on "ready" — see `handleStatusChanged()`. */
633
636
  private connectStartTime;
@@ -897,7 +900,7 @@ declare class Reactor implements Disposable {
897
900
  * rejected call — whichever landed last. `undefined` until the first
898
901
  * failure. */
899
902
  getLastError(): ReactorError | undefined;
900
- /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
903
+ /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`
901
904
  * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
902
905
  getStats(): ConnectionStats | undefined;
903
906
  /** Timing breakdown from the most recent `connect()`/`reconnect()`
@@ -940,7 +943,24 @@ declare class Reactor implements Disposable {
940
943
  * → "ready" status sequence (see `ReactorStatus`), and starts/stops stats
941
944
  * polling around the "ready" window. */
942
945
  private handleStatusChanged;
946
+ /** Starts both stats pollers: the local one updates `getStats()` and emits
947
+ * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the
948
+ * extractor it computes bitrates with, so a bitrate covers its own
949
+ * poller's interval. */
943
950
  private startStatsPolling;
951
+ /** Report one quality batch to the runtime: a reading per negotiated
952
+ * track — audio and video, sent and received — see
953
+ * `createTrackStatsExtractor`, and the connection-wide reading — see
954
+ * `toClientConnectionStat`. The connection reading goes even while no
955
+ * track has one yet (none negotiated onto a named track, or no codec
956
+ * reported yet), so the runtime gets the bandwidth estimate, the
957
+ * round-trip time and the time to connect without waiting on the tracks.
958
+ * Skipped only when there is nothing at all to say; one is due again in
959
+ * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch
960
+ * actually sent for this connection — see `hasSentConnectTime`.
961
+ * `sendClientStats` throws synchronously on a closing connection; caught
962
+ * here for the same reason `getStats()`'s rejection is above. */
963
+ private reportClientStats;
944
964
  private stopStatsPolling;
945
965
  /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves
946
966
  * `client`/`schema` alone — that's `freeClient()`'s job, run separately
package/dist/index.d.ts CHANGED
@@ -476,7 +476,7 @@ interface ReactorEventMap {
476
476
  * that want the binding's own identifier (e.g. for
477
477
  * `getTrackByMid`/`getStreamByMid`). */
478
478
  trackReceived: (name: string, track: MediaStreamTrack, stream: MediaStream, mid: string | undefined) => void;
479
- /** Fired every `STATS_INTERVAL_MS` while the session is "ready" — see
479
+ /** Fired every `LOCAL_STATS_INTERVAL_MS` while the session is "ready" — see
480
480
  * `getStats()`. */
481
481
  statsUpdate: (stats: ConnectionStats) => void;
482
482
  }
@@ -623,11 +623,14 @@ declare class Reactor implements Disposable {
623
623
  private capabilities;
624
624
  private stats;
625
625
  private connectionTimings;
626
- private statsPollHandle;
627
- /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
628
- * in-flight `getStats()` recognize it's stale once it resolves, even if
629
- * `this.client` hasn't changed in the meantime. */
630
- private statsPollGeneration;
626
+ /** The stop functions of the running stats pollers — see `pollPeerStats()`. */
627
+ private stopStatsPollers;
628
+ /** Whether this connection has already reported its time to connect —
629
+ * a one-time fact, sent on the first client-stats report that carries it
630
+ * and omitted on every one after. Set only once a batch actually went out
631
+ * with it, so a batch sent before the timings exist doesn't use it up.
632
+ * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */
633
+ private hasSentConnectTime;
631
634
  /** Set on the "connecting" status transition, cleared once `connectionTimings`
632
635
  * is finalized on "ready" — see `handleStatusChanged()`. */
633
636
  private connectStartTime;
@@ -897,7 +900,7 @@ declare class Reactor implements Disposable {
897
900
  * rejected call — whichever landed last. `undefined` until the first
898
901
  * failure. */
899
902
  getLastError(): ReactorError | undefined;
900
- /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
903
+ /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`
901
904
  * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
902
905
  getStats(): ConnectionStats | undefined;
903
906
  /** Timing breakdown from the most recent `connect()`/`reconnect()`
@@ -940,7 +943,24 @@ declare class Reactor implements Disposable {
940
943
  * → "ready" status sequence (see `ReactorStatus`), and starts/stops stats
941
944
  * polling around the "ready" window. */
942
945
  private handleStatusChanged;
946
+ /** Starts both stats pollers: the local one updates `getStats()` and emits
947
+ * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the
948
+ * extractor it computes bitrates with, so a bitrate covers its own
949
+ * poller's interval. */
943
950
  private startStatsPolling;
951
+ /** Report one quality batch to the runtime: a reading per negotiated
952
+ * track — audio and video, sent and received — see
953
+ * `createTrackStatsExtractor`, and the connection-wide reading — see
954
+ * `toClientConnectionStat`. The connection reading goes even while no
955
+ * track has one yet (none negotiated onto a named track, or no codec
956
+ * reported yet), so the runtime gets the bandwidth estimate, the
957
+ * round-trip time and the time to connect without waiting on the tracks.
958
+ * Skipped only when there is nothing at all to say; one is due again in
959
+ * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch
960
+ * actually sent for this connection — see `hasSentConnectTime`.
961
+ * `sendClientStats` throws synchronously on a closing connection; caught
962
+ * here for the same reason `getStats()`'s rejection is above. */
963
+ private reportClientStats;
944
964
  private stopStatsPolling;
945
965
  /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves
946
966
  * `client`/`schema` alone — that's `freeClient()`'s job, run separately
package/dist/index.js CHANGED
@@ -306,14 +306,185 @@ function toPublicClip(clip) {
306
306
  }
307
307
 
308
308
  // src/internal/stats.ts
309
- var STATS_INTERVAL_MS = 2e3;
310
- function createRTCStatsExtractor() {
309
+ var LOCAL_STATS_INTERVAL_MS = 2e3;
310
+ var RUNTIME_REPORT_INTERVAL_MS = 5e3;
311
+ function pollPeerStats(client, intervalMs, onReport) {
312
+ let stopped = false;
313
+ let reading = false;
314
+ const handle = setInterval(() => {
315
+ if (reading) {
316
+ return;
317
+ }
318
+ const peerConnection = client.getPeerConnection();
319
+ if (!peerConnection) {
320
+ return;
321
+ }
322
+ reading = true;
323
+ void peerConnection.getStats().then(
324
+ (report) => {
325
+ if (stopped) {
326
+ return;
327
+ }
328
+ try {
329
+ onReport(report);
330
+ } catch (error) {
331
+ console.error("[Reactor] stats report handler threw:", error);
332
+ }
333
+ },
334
+ () => {
335
+ }
336
+ ).finally(() => {
337
+ reading = false;
338
+ });
339
+ }, intervalMs);
340
+ return () => {
341
+ stopped = true;
342
+ clearInterval(handle);
343
+ };
344
+ }
345
+ function roundMs(ms) {
346
+ return Math.round(ms * 1e3) / 1e3;
347
+ }
348
+ function secondsToMs(seconds) {
349
+ return roundMs(seconds * 1e3);
350
+ }
351
+ var WIRE_CODECS = {
352
+ video: /* @__PURE__ */ new Set(["vp8", "vp9", "av1", "h264", "h265"]),
353
+ audio: /* @__PURE__ */ new Set(["opus"])
354
+ };
355
+ function createTrackStatsExtractor() {
356
+ const lastBytes = /* @__PURE__ */ new Map();
357
+ return (report, tracks, pausedTracks) => {
358
+ const reportWithLookup = report;
359
+ const stats = [];
360
+ const seenStreams = /* @__PURE__ */ new Set();
361
+ const remoteInbound = /* @__PURE__ */ new Map();
362
+ report.forEach((stat) => {
363
+ if (stat.type === "remote-inbound-rtp" && stat.localId !== void 0) {
364
+ remoteInbound.set(stat.localId, stat);
365
+ }
366
+ });
367
+ report.forEach((stat) => {
368
+ const inbound = stat.type === "inbound-rtp";
369
+ if (!inbound && stat.type !== "outbound-rtp" || stat.mid === void 0) {
370
+ return;
371
+ }
372
+ const direction = inbound ? "recvonly" : "sendonly";
373
+ const streamKey = `${direction}:${stat.mid}`;
374
+ if (seenStreams.has(streamKey)) {
375
+ return;
376
+ }
377
+ const track = tracks.find((entry) => entry.mid === stat.mid && entry.direction === direction);
378
+ const codecStat = stat.codecId !== void 0 ? reportWithLookup.get(stat.codecId) : void 0;
379
+ const codec = codecStat?.mimeType?.split("/")[1]?.toLowerCase();
380
+ if (track === void 0 || codec === void 0 || !WIRE_CODECS[track.kind].has(codec)) {
381
+ return;
382
+ }
383
+ seenStreams.add(streamKey);
384
+ const metrics = {};
385
+ const put = (key, value) => {
386
+ if (value !== void 0) {
387
+ metrics[key] = value;
388
+ }
389
+ };
390
+ const bytes = inbound ? stat.bytesReceived : stat.bytesSent;
391
+ if (bytes !== void 0) {
392
+ const previous = lastBytes.get(stat.id);
393
+ if (previous !== void 0 && stat.timestamp > previous.timestamp && bytes >= previous.bytes) {
394
+ put("bitrate_bps", Math.round((bytes - previous.bytes) * 8 * 1e3 / (stat.timestamp - previous.timestamp)));
395
+ }
396
+ lastBytes.set(stat.id, { bytes, timestamp: stat.timestamp });
397
+ }
398
+ const keyframeRequests = stat.firCount !== void 0 || stat.pliCount !== void 0 ? (stat.firCount ?? 0) + (stat.pliCount ?? 0) : void 0;
399
+ if (inbound) {
400
+ put("packets_received", stat.packetsReceived);
401
+ put("packets_lost", stat.packetsLost);
402
+ put("jitter_ms", stat.jitter !== void 0 ? secondsToMs(stat.jitter) : void 0);
403
+ put("nack_count", stat.nackCount);
404
+ if (track.kind === "video") {
405
+ put("frames_per_second", stat.framesPerSecond);
406
+ put("frames_decoded", stat.framesDecoded);
407
+ put("frames_dropped", stat.framesDropped);
408
+ put("frame_width", stat.frameWidth);
409
+ put("frame_height", stat.frameHeight);
410
+ put("keyframe_requests", keyframeRequests);
411
+ } else {
412
+ put("concealed_samples", stat.concealedSamples);
413
+ put("total_samples_received", stat.totalSamplesReceived);
414
+ }
415
+ } else {
416
+ const remote = remoteInbound.get(stat.id);
417
+ put("packets_sent", stat.packetsSent);
418
+ put("retransmitted_packets_sent", stat.retransmittedPacketsSent);
419
+ put("nack_count", stat.nackCount);
420
+ put("packets_lost", remote?.packetsLost);
421
+ put("jitter_ms", remote?.jitter !== void 0 ? secondsToMs(remote.jitter) : void 0);
422
+ put("round_trip_time_ms", remote?.roundTripTime !== void 0 ? secondsToMs(remote.roundTripTime) : void 0);
423
+ if (track.kind === "video") {
424
+ put("frames_per_second", stat.framesPerSecond);
425
+ put("frames_encoded", stat.framesEncoded);
426
+ put("frame_width", stat.frameWidth);
427
+ put("frame_height", stat.frameHeight);
428
+ put("keyframe_requests", keyframeRequests);
429
+ }
430
+ }
431
+ stats.push({
432
+ timestamp: Date.now(),
433
+ trackName: track.name,
434
+ kind: track.kind,
435
+ direction,
436
+ codec,
437
+ paused: pausedTracks.includes(track.name),
438
+ metrics
439
+ });
440
+ });
441
+ return stats;
442
+ };
443
+ }
444
+ function toClientConnectionStat(report, timeToConnectMs) {
445
+ const pair = activeCandidatePair(report);
446
+ const metrics = {};
447
+ if (pair?.availableOutgoingBitrate !== void 0) {
448
+ metrics.available_outgoing_bitrate_bps = pair.availableOutgoingBitrate;
449
+ }
450
+ if (pair?.availableIncomingBitrate !== void 0) {
451
+ metrics.available_incoming_bitrate_bps = pair.availableIncomingBitrate;
452
+ }
453
+ if (pair?.currentRoundTripTime !== void 0) {
454
+ metrics.connection_rtt_ms = secondsToMs(pair.currentRoundTripTime);
455
+ }
456
+ if (timeToConnectMs !== void 0) {
457
+ metrics.time_to_connect_ms = roundMs(timeToConnectMs);
458
+ }
459
+ return { timestamp: Date.now(), metrics };
460
+ }
461
+ function activeCandidatePair(report) {
462
+ let namedByTransport;
463
+ let flaggedSelected;
464
+ let firstNominated;
465
+ report.forEach((stat) => {
466
+ if (stat.type === "transport" && stat.selectedCandidatePairId) {
467
+ namedByTransport ??= stat.selectedCandidatePairId;
468
+ }
469
+ if (stat.type === "candidate-pair" && stat.state === "succeeded") {
470
+ if (stat.selected) {
471
+ flaggedSelected ??= stat;
472
+ }
473
+ if (stat.nominated) {
474
+ firstNominated ??= stat;
475
+ }
476
+ }
477
+ });
478
+ const named = namedByTransport !== void 0 ? report.get(namedByTransport) : void 0;
479
+ const namedSucceeded = named?.state === "succeeded" ? named : void 0;
480
+ return namedSucceeded ?? flaggedSelected ?? firstNominated;
481
+ }
482
+ function createConnectionStatsExtractor() {
311
483
  let lastBytesReceived;
312
484
  let lastBytesSent;
313
485
  let lastCandPairTimestamp;
314
486
  let lastCandPairId;
315
487
  return (report) => {
316
- let candPairId;
317
488
  let rtt;
318
489
  let availableOutgoingBitrate;
319
490
  let availableIncomingBitrate;
@@ -324,40 +495,35 @@ function createRTCStatsExtractor() {
324
495
  let jitter;
325
496
  let packetLossRatio;
326
497
  let candidateType;
327
- const reportWithLookup = report;
328
- report.forEach((stat) => {
329
- if (candPairId === void 0 && stat.type === "candidate-pair" && stat.state === "succeeded" && stat.nominated) {
330
- candPairId = stat.id;
331
- if (stat.currentRoundTripTime !== void 0) {
332
- rtt = stat.currentRoundTripTime * 1e3;
333
- }
334
- if (stat.availableOutgoingBitrate !== void 0) {
335
- availableOutgoingBitrate = stat.availableOutgoingBitrate;
336
- }
337
- if (stat.availableIncomingBitrate !== void 0) {
338
- availableIncomingBitrate = stat.availableIncomingBitrate;
339
- }
340
- const localCandidate = stat.localCandidateId !== void 0 ? reportWithLookup.get(stat.localCandidateId) : void 0;
341
- if (localCandidate?.candidateType) {
342
- candidateType = localCandidate.candidateType;
343
- }
344
- const samePair = lastCandPairId === candPairId;
345
- const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? stat.timestamp - lastCandPairTimestamp : 0;
346
- if (stat.bytesReceived !== void 0) {
347
- if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
348
- incomingBitrate = (stat.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
349
- }
350
- lastBytesReceived = stat.bytesReceived;
498
+ const pair = activeCandidatePair(report);
499
+ if (pair !== void 0) {
500
+ if (pair.currentRoundTripTime !== void 0) {
501
+ rtt = pair.currentRoundTripTime * 1e3;
502
+ }
503
+ availableOutgoingBitrate = pair.availableOutgoingBitrate;
504
+ availableIncomingBitrate = pair.availableIncomingBitrate;
505
+ const localCandidate = pair.localCandidateId !== void 0 ? report.get(pair.localCandidateId) : void 0;
506
+ if (localCandidate?.candidateType) {
507
+ candidateType = localCandidate.candidateType;
508
+ }
509
+ const samePair = lastCandPairId === pair.id;
510
+ const timeDiff = samePair && lastCandPairTimestamp !== void 0 ? pair.timestamp - lastCandPairTimestamp : 0;
511
+ if (pair.bytesReceived !== void 0) {
512
+ if (samePair && lastBytesReceived !== void 0 && timeDiff > 0) {
513
+ incomingBitrate = (pair.bytesReceived - lastBytesReceived) * 8 / timeDiff * 1e3;
351
514
  }
352
- if (stat.bytesSent !== void 0) {
353
- if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
354
- outgoingBitrate = (stat.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
355
- }
356
- lastBytesSent = stat.bytesSent;
515
+ lastBytesReceived = pair.bytesReceived;
516
+ }
517
+ if (pair.bytesSent !== void 0) {
518
+ if (samePair && lastBytesSent !== void 0 && timeDiff > 0) {
519
+ outgoingBitrate = (pair.bytesSent - lastBytesSent) * 8 / timeDiff * 1e3;
357
520
  }
358
- lastCandPairTimestamp = stat.timestamp;
359
- lastCandPairId = candPairId;
521
+ lastBytesSent = pair.bytesSent;
360
522
  }
523
+ lastCandPairTimestamp = pair.timestamp;
524
+ lastCandPairId = pair.id;
525
+ }
526
+ report.forEach((stat) => {
361
527
  if (videoInboundRtpId === void 0 && stat.type === "inbound-rtp" && stat.kind === "video") {
362
528
  videoInboundRtpId = stat.id;
363
529
  if (stat.framesPerSecond !== void 0) {
@@ -412,7 +578,7 @@ async function importWasmModule() {
412
578
  // package.json
413
579
  var package_default = {
414
580
  name: "@reactor-team/js-sdk",
415
- version: "3.0.2",
581
+ version: "3.1.0",
416
582
  description: "Connect your JavaScript/TypeScript app to a live Reactor model in the browser.",
417
583
  license: "Apache-2.0",
418
584
  repository: {
@@ -888,11 +1054,14 @@ var Reactor = class {
888
1054
  capabilities;
889
1055
  stats;
890
1056
  connectionTimings;
891
- statsPollHandle;
892
- /** Bumped on every `startStatsPolling()`/`stopStatsPolling()` call — lets an
893
- * in-flight `getStats()` recognize it's stale once it resolves, even if
894
- * `this.client` hasn't changed in the meantime. */
895
- statsPollGeneration = 0;
1057
+ /** The stop functions of the running stats pollers — see `pollPeerStats()`. */
1058
+ stopStatsPollers = [];
1059
+ /** Whether this connection has already reported its time to connect —
1060
+ * a one-time fact, sent on the first client-stats report that carries it
1061
+ * and omitted on every one after. Set only once a batch actually went out
1062
+ * with it, so a batch sent before the timings exist doesn't use it up.
1063
+ * Reset per `startStatsPolling()` call, i.e. per connect()/reconnect(). */
1064
+ hasSentConnectTime = false;
896
1065
  /** Set on the "connecting" status transition, cleared once `connectionTimings`
897
1066
  * is finalized on "ready" — see `handleStatusChanged()`. */
898
1067
  connectStartTime;
@@ -1421,7 +1590,7 @@ var Reactor = class {
1421
1590
  getLastError() {
1422
1591
  return this._lastError;
1423
1592
  }
1424
- /** The most recent WebRTC connection stats, polled every `STATS_INTERVAL_MS`
1593
+ /** The most recent WebRTC connection stats, polled every `LOCAL_STATS_INTERVAL_MS`
1425
1594
  * while "ready" — see `statsUpdate`. `undefined` before the first sample. */
1426
1595
  getStats() {
1427
1596
  return this.stats;
@@ -1571,31 +1740,57 @@ var Reactor = class {
1571
1740
  this.stopStatsPolling();
1572
1741
  }
1573
1742
  }
1743
+ /** Starts both stats pollers: the local one updates `getStats()` and emits
1744
+ * `statsUpdate`, the runtime one sends a client-stats batch. Each owns the
1745
+ * extractor it computes bitrates with, so a bitrate covers its own
1746
+ * poller's interval. */
1574
1747
  startStatsPolling(client) {
1575
1748
  this.stopStatsPolling();
1576
- const generation = ++this.statsPollGeneration;
1577
- const extractStats = createRTCStatsExtractor();
1578
- this.statsPollHandle = setInterval(() => {
1579
- const peerConnection = client.getPeerConnection();
1580
- if (!peerConnection) {
1581
- return;
1582
- }
1583
- peerConnection.getStats().then((report) => {
1584
- if (generation !== this.statsPollGeneration) {
1585
- return;
1586
- }
1587
- this.stats = { ...extractStats(report), connectionTimings: this.connectionTimings };
1749
+ const extractConnectionStats = createConnectionStatsExtractor();
1750
+ const extractTrackStats = createTrackStatsExtractor();
1751
+ this.hasSentConnectTime = false;
1752
+ this.stopStatsPollers = [
1753
+ pollPeerStats(client, LOCAL_STATS_INTERVAL_MS, (report) => {
1754
+ this.stats = { ...extractConnectionStats(report), connectionTimings: this.connectionTimings };
1588
1755
  this.emitter.emit("statsUpdate", this.stats);
1589
- }).catch(() => {
1590
- });
1591
- }, STATS_INTERVAL_MS);
1756
+ }),
1757
+ pollPeerStats(client, RUNTIME_REPORT_INTERVAL_MS, (report) => {
1758
+ this.reportClientStats(client, report, extractTrackStats);
1759
+ })
1760
+ ];
1761
+ }
1762
+ /** Report one quality batch to the runtime: a reading per negotiated
1763
+ * track — audio and video, sent and received — see
1764
+ * `createTrackStatsExtractor`, and the connection-wide reading — see
1765
+ * `toClientConnectionStat`. The connection reading goes even while no
1766
+ * track has one yet (none negotiated onto a named track, or no codec
1767
+ * reported yet), so the runtime gets the bandwidth estimate, the
1768
+ * round-trip time and the time to connect without waiting on the tracks.
1769
+ * Skipped only when there is nothing at all to say; one is due again in
1770
+ * `RUNTIME_REPORT_INTERVAL_MS`. The time to connect goes on the first batch
1771
+ * actually sent for this connection — see `hasSentConnectTime`.
1772
+ * `sendClientStats` throws synchronously on a closing connection; caught
1773
+ * here for the same reason `getStats()`'s rejection is above. */
1774
+ reportClientStats(client, report, extractTrackStats) {
1775
+ const trackStats = extractTrackStats(report, this.trackMapping(), this.pausedTracks());
1776
+ const timeToConnectMs = this.hasSentConnectTime ? void 0 : this.connectionTimings?.totalMs;
1777
+ const connectionStat = toClientConnectionStat(report, timeToConnectMs);
1778
+ if (trackStats.length === 0 && Object.keys(connectionStat.metrics).length === 0) {
1779
+ return;
1780
+ }
1781
+ try {
1782
+ client.sendClientStats(trackStats, connectionStat);
1783
+ if (timeToConnectMs !== void 0) {
1784
+ this.hasSentConnectTime = true;
1785
+ }
1786
+ } catch {
1787
+ }
1592
1788
  }
1593
1789
  stopStatsPolling() {
1594
- this.statsPollGeneration += 1;
1595
- if (this.statsPollHandle !== void 0) {
1596
- clearInterval(this.statsPollHandle);
1597
- this.statsPollHandle = void 0;
1790
+ for (const stop of this.stopStatsPollers) {
1791
+ stop();
1598
1792
  }
1793
+ this.stopStatsPollers = [];
1599
1794
  this.stats = void 0;
1600
1795
  }
1601
1796
  /** Called on every `disconnect()` and on `[Symbol.dispose]`. Leaves