@blockcast/mmt-container 0.1.0-main.c71423b8a4e4 → 0.1.0-main.ce3c8aeb7f68

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.
Files changed (148) hide show
  1. package/dist/align.d.ts +6 -2
  2. package/dist/align.d.ts.map +1 -1
  3. package/dist/align.js.map +2 -2
  4. package/dist/audio-ring-buffer.js +23 -36
  5. package/dist/audio-ring-buffer.js.map +1 -1
  6. package/dist/browser-runtime.js +6865 -6485
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +3 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +21 -2
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.js +10 -0
  13. package/dist/catalog-fec-params.js.map +4 -4
  14. package/dist/cmaf-block-assembler.d.ts +42 -0
  15. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  16. package/dist/cmaf-block-assembler.js +542 -535
  17. package/dist/cmaf-block-assembler.js.map +2 -2
  18. package/dist/cmaf-group-batcher.js +27 -46
  19. package/dist/cmaf-group-batcher.js.map +2 -2
  20. package/dist/cmcd-producer.js +45 -66
  21. package/dist/cmcd-producer.js.map +1 -1
  22. package/dist/fec-manager.d.ts +13 -1
  23. package/dist/fec-manager.d.ts.map +1 -1
  24. package/dist/fec-manager.js +1151 -871
  25. package/dist/fec-manager.js.map +2 -2
  26. package/dist/fec-starvation-detector.js +25 -40
  27. package/dist/fec-starvation-detector.js.map +1 -1
  28. package/dist/fec-worker-setup.js +242 -225
  29. package/dist/fec-worker-setup.js.map +3 -3
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js.map +2 -2
  33. package/dist/iso-bmff-timing.js +63 -88
  34. package/dist/iso-bmff-timing.js.map +1 -1
  35. package/dist/loc.js +7 -4
  36. package/dist/loc.js.map +1 -1
  37. package/dist/manifest-auth-plan.js +292 -311
  38. package/dist/manifest-auth-plan.js.map +1 -1
  39. package/dist/media-router.d.ts +0 -99
  40. package/dist/media-router.d.ts.map +1 -1
  41. package/dist/media-router.js +270 -504
  42. package/dist/media-router.js.map +3 -3
  43. package/dist/mfu-reassembler.js +597 -607
  44. package/dist/mfu-reassembler.js.map +3 -3
  45. package/dist/mmtp-container-parser.d.ts +37 -0
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +1531 -1522
  48. package/dist/mmtp-container-parser.js.map +3 -3
  49. package/dist/mmtp-container-parser.no-modules.js +179 -102
  50. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  51. package/dist/mmtp-decode-pipeline.js +1641 -1651
  52. package/dist/mmtp-decode-pipeline.js.map +3 -3
  53. package/dist/mmtp-router.d.ts +34 -0
  54. package/dist/mmtp-router.d.ts.map +1 -1
  55. package/dist/mmtp-router.js +3676 -3390
  56. package/dist/mmtp-router.js.map +3 -3
  57. package/dist/mmtp-to-cmaf.d.ts +7 -1
  58. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  59. package/dist/mmtp-to-cmaf.js +109 -134
  60. package/dist/mmtp-to-cmaf.js.map +2 -2
  61. package/dist/multicast-input.d.ts +7 -35
  62. package/dist/multicast-input.d.ts.map +1 -1
  63. package/dist/multicast-input.js +21 -2
  64. package/dist/multicast-input.js.map +4 -4
  65. package/dist/multicast-manager.d.ts +10 -1
  66. package/dist/multicast-manager.d.ts.map +1 -1
  67. package/dist/multicast-manager.js +5584 -4961
  68. package/dist/multicast-manager.js.map +4 -4
  69. package/dist/multicast-transport.d.ts +7 -0
  70. package/dist/multicast-transport.d.ts.map +1 -1
  71. package/dist/multicast-transport.js +369 -421
  72. package/dist/multicast-transport.js.map +4 -4
  73. package/dist/multicast-unwrap.js +53 -30
  74. package/dist/multicast-unwrap.js.map +2 -2
  75. package/dist/no-modules.js +2096 -2097
  76. package/dist/no-modules.js.map +3 -3
  77. package/dist/sample-combiner.js +118 -139
  78. package/dist/sample-combiner.js.map +1 -1
  79. package/dist/signaling.js.map +2 -2
  80. package/dist/source-auth.js +353 -382
  81. package/dist/source-auth.js.map +1 -1
  82. package/dist/switching-set-alignment.js +14 -29
  83. package/dist/switching-set-alignment.js.map +1 -1
  84. package/dist/timestamp-codec.js +17 -11
  85. package/dist/timestamp-codec.js.map +2 -2
  86. package/dist/track-pipeline-setup.js +105 -125
  87. package/dist/track-pipeline-setup.js.map +1 -1
  88. package/dist/track-pipeline.js +107 -127
  89. package/dist/track-pipeline.js.map +1 -1
  90. package/dist/track-session.d.ts +16 -0
  91. package/dist/track-session.d.ts.map +1 -1
  92. package/dist/track-session.js +230 -243
  93. package/dist/track-session.js.map +2 -2
  94. package/dist/transport-pool.js +24 -38
  95. package/dist/transport-pool.js.map +1 -1
  96. package/dist/wasm-mfu-reassembler.d.ts +6 -1
  97. package/dist/wasm-mfu-reassembler.d.ts.map +1 -1
  98. package/dist/wasm-mfu-reassembler.js +127 -144
  99. package/dist/wasm-mfu-reassembler.js.map +2 -2
  100. package/dist/wasm-mmtp-container-parser.js +1659 -1650
  101. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  102. package/node_modules/@blockcast/fec-worker/README.md +5 -1
  103. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +8 -2
  104. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -1
  105. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +89 -16
  106. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -1
  107. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +48 -3
  108. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -1
  109. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +55 -8
  110. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +2 -2
  111. package/node_modules/@blockcast/fec-worker/dist/index.d.ts +1 -1
  112. package/node_modules/@blockcast/fec-worker/dist/index.d.ts.map +1 -1
  113. package/node_modules/@blockcast/fec-worker/dist/index.js.map +1 -1
  114. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +97 -17
  115. package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +46 -2
  116. package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +78 -10
  117. package/node_modules/@blockcast/fec-worker/src/index.ts +2 -0
  118. package/node_modules/@blockcast/mmt-base/README.md +1 -0
  119. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  120. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  121. package/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  122. package/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  123. package/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  124. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/README.md +1 -0
  125. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  126. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  127. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  128. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  129. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  130. package/package.json +7 -6
  131. package/schemas/catalog.schema.json +1 -1
  132. package/src/align.ts +6 -2
  133. package/src/carp-catalog.ts +13 -3
  134. package/src/cmaf-block-assembler.ts +90 -81
  135. package/src/fec-manager.ts +530 -146
  136. package/src/index.ts +2 -2
  137. package/src/media-router.ts +0 -397
  138. package/src/mmtp-container-parser.ts +97 -21
  139. package/src/mmtp-router.ts +302 -125
  140. package/src/mmtp-to-cmaf.ts +21 -7
  141. package/src/multicast-input.ts +23 -3
  142. package/src/multicast-manager.ts +83 -11
  143. package/src/multicast-transport.ts +56 -17
  144. package/src/track-session.ts +16 -0
  145. package/src/wasm-mfu-reassembler.ts +40 -24
  146. package/test-vectors/catalog/README.md +2 -0
  147. package/test-vectors/catalog/negative/multicast-packet-id-signaling.json +26 -0
  148. package/test-vectors/catalog-validation.json +11 -0
@@ -1,20 +1,3 @@
1
- var __typeError = (msg) => {
2
- throw TypeError(msg);
3
- };
4
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
- var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
9
- var __privateWrapper = (obj, member, setter, getter) => ({
10
- set _(value) {
11
- __privateSet(obj, member, value, setter);
12
- },
13
- get _() {
14
- return __privateGet(obj, member, getter);
15
- }
16
- });
17
-
18
1
  // src/track-session.ts
19
2
  import { fecBlockBudgetMs } from "@blockcast/mmt-fec";
20
3
  function computeFecDeliveryWindowMs(config) {
@@ -52,55 +35,114 @@ function newFecCounters() {
52
35
  greenFillFrames: 0
53
36
  };
54
37
  }
55
- var _fecDecoders, _workerClients, _syncDecoderBlockOwners, _decoderBlockOwners, _fecK, _fecSymbolSize, _fecTimeoutMs, _trackConfigs, _fecStats, _fecTrackStats, _fecWorkerStats, _fecStatsObservers, _activeBlocks, _activeBlockDeadlinesMs, _activeBlockTimeoutOwners, _lifecycleTrace, _pendingWorkerCleanups, _pendingWorkerCleanupClients, _blockSourceCounts, _blockSourceEsis, _blockRepairRsIds, _completedBlocks, _seenSymbols, _blockPathCounts, _blockCatalogTrackNames, _startupAlignedPackets, _startupPartialBlocks, _startupRequireRepairReady, _startupRepairReadyPackets, _startupRepairBoundaryCounts, _startupRepairFailOpenPackets, _cleanlyCompletedBlocks, _repairRequestedBlocks, _repairDeadlines, _workerRecoveredBlocks, _fpsDetected, _fecFps, _fecInterleaveDepthMs, _workerErrorCounts, _decoderUnavailableEvents, _repairSymbolSizeMismatchCount, _FECManager_instances, streamKey_fn, belongsToPacket_fn, belongsToStream_fn, packetIdsForStreamKeys_fn, parseStreamKey_fn, blockKey_fn, parseBlockKey_fn, decoderForPacket_fn, workerForPacket_fn, routableWorkerForPacket_fn, claimDecoderBlock_fn, decoderBlockCatalogTrackName_fn, resetDecoderBlockOwners_fn, discardFecDecoderClient_fn, assertExclusiveDecoderClient_fn, statsForPacket_fn, markPathBlockComplete_fn, clearRepairDeadline_fn, requestRepair_fn, traceLifecycle_fn, defaultTrackConfig_fn, resolveTrackConfig_fn, computeTimeout_fn, repairDeadlineMs_fn, repairGraceMs_fn, armBlockTimeout_fn, upsertTrackConfig_fn, normalizeSymbolData_fn, blockKeysFor_fn, observeBlockCatalogTrackName_fn, markStartupPartial_fn, retireWorker_fn, releaseWorkerClient_fn, settleOwedCleanup_fn, evictDisposedWorker_fn, routeSyncCleanup_fn, failBlock_fn;
38
+ function dropOldest(collection, count) {
39
+ const dropped = [];
40
+ for (const key of collection.keys()) {
41
+ if (dropped.length >= count) break;
42
+ dropped.push(key);
43
+ }
44
+ for (const key of dropped) collection.delete(key);
45
+ return dropped;
46
+ }
47
+ var TerminalQueue = class {
48
+ #records = [];
49
+ #head = 0;
50
+ push(record) {
51
+ this.#records.push(record);
52
+ }
53
+ peek() {
54
+ return this.#records[this.#head];
55
+ }
56
+ shift() {
57
+ this.#head++;
58
+ if (this.#head * 2 >= this.#records.length) {
59
+ this.#records = this.#records.slice(this.#head);
60
+ this.#head = 0;
61
+ }
62
+ }
63
+ };
56
64
  var FECManager = class {
57
65
  constructor() {
58
- __privateAdd(this, _FECManager_instances);
59
66
  // Per-track WASM RaptorQ decoders, keyed by physical stream identity.
60
- __privateAdd(this, _fecDecoders, /* @__PURE__ */ new Map());
67
+ this.#fecDecoders = /* @__PURE__ */ new Map();
61
68
  /** @deprecated Use setFecDecoder(packetId, ...). Backwards-compat shim. */
62
69
  // Per-track Worker-backed FEC decoders, keyed by physical stream identity.
63
70
  // Worker-backed tracks use async decode — recovered frames arrive via onFrame callback,
64
71
  // not synchronous return from feedSourceSymbol/feedRepairSymbol.
65
- __privateAdd(this, _workerClients, /* @__PURE__ */ new Map());
72
+ this.#workerClients = /* @__PURE__ */ new Map();
66
73
  // Worker setup can finish while an interleaved block is already collecting
67
74
  // on the sync decoder. Keep that block on its original decoder so later
68
75
  // source/repair symbols do not split across two RaptorQ states.
69
- __privateAdd(this, _syncDecoderBlockOwners, /* @__PURE__ */ new Map());
70
- __privateAdd(this, _decoderBlockOwners, /* @__PURE__ */ new WeakMap());
71
- __privateAdd(this, _fecK, 4);
72
- __privateAdd(this, _fecSymbolSize, 0);
73
- __privateAdd(this, _fecTimeoutMs, 500);
76
+ this.#syncDecoderBlockOwners = /* @__PURE__ */ new Map();
77
+ this.#decoderBlockOwners = /* @__PURE__ */ new WeakMap();
78
+ this.#fecK = 4;
79
+ this.#fecSymbolSize = 0;
80
+ this.#fecTimeoutMs = 500;
74
81
  // default 500ms; refined by setFramerate() when fps known
75
- __privateAdd(this, _trackConfigs, /* @__PURE__ */ new Map());
76
- __privateAdd(this, _fecStats, newFecCounters());
77
- __privateAdd(this, _fecTrackStats, /* @__PURE__ */ new Map());
78
- __privateAdd(this, _fecWorkerStats, /* @__PURE__ */ new Map());
79
- __privateAdd(this, _fecStatsObservers, /* @__PURE__ */ new Set());
80
- // Block inactivity tracking: (packetId, SBN) -> timer. The deadline is
81
- // derived from catalog geometry and refreshed on progress; only an idle
82
- // block fails.
83
- __privateAdd(this, _activeBlocks, /* @__PURE__ */ new Map());
84
- __privateAdd(this, _activeBlockDeadlinesMs, /* @__PURE__ */ new Map());
85
- __privateAdd(this, _activeBlockTimeoutOwners, /* @__PURE__ */ new Map());
86
- __privateAdd(this, _lifecycleTrace, []);
82
+ this.#trackConfigs = /* @__PURE__ */ new Map();
83
+ this.#fecStats = newFecCounters();
84
+ this.#fecTrackStats = /* @__PURE__ */ new Map();
85
+ this.#fecWorkerStats = /* @__PURE__ */ new Map();
86
+ this.#fecStatsObservers = /* @__PURE__ */ new Set();
87
+ // Block inactivity tracking: (packetId, SBN) -> the one armed timer. The
88
+ // deadline is derived from catalog geometry and refreshed on progress; only
89
+ // an idle block fails. #activeBlockDeadlinesMs is the authoritative
90
+ // deadline; the timer re-checks it when it fires (see DeadlineTimer).
91
+ this.#activeBlocks = /* @__PURE__ */ new Map();
92
+ this.#activeBlockDeadlinesMs = /* @__PURE__ */ new Map();
93
+ this.#lifecycleTrace = [];
87
94
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
88
95
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
89
- __privateAdd(this, _pendingWorkerCleanups, /* @__PURE__ */ new Set());
90
- __privateAdd(this, _pendingWorkerCleanupClients, /* @__PURE__ */ new Map());
96
+ this.#pendingWorkerCleanups = /* @__PURE__ */ new Set();
97
+ this.#pendingWorkerCleanupClients = /* @__PURE__ */ new Map();
91
98
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
92
- __privateAdd(this, _blockSourceCounts, /* @__PURE__ */ new Map());
93
- __privateAdd(this, _blockSourceEsis, /* @__PURE__ */ new Map());
94
- __privateAdd(this, _blockRepairRsIds, /* @__PURE__ */ new Map());
99
+ this.#blockSourceCounts = /* @__PURE__ */ new Map();
100
+ this.#blockSourceEsis = /* @__PURE__ */ new Map();
101
+ // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
102
+ // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
103
+ // media units, usually before it holds K symbols, and fec-raptorq
104
+ // force_complete() encodes it as a K-symbol RaptorQ block whose ESIs
105
+ // SSB_length..K-1 are zero padding that is never sent. Such a block is clean
106
+ // at SSB_length source arrivals and recoverable from SSB_length received
107
+ // symbols; waiting for K fails every one of them.
108
+ this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
109
+ this.#ssbLengthConflictCount = 0;
110
+ this.#blockRepairRsIds = /* @__PURE__ */ new Map();
95
111
  // Blocks already recovered — prevents late source symbols from restarting timeouts.
96
112
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
97
113
  // which would falsely start new timeouts without this guard.
98
- __privateAdd(this, _completedBlocks, /* @__PURE__ */ new Set());
99
- __privateAdd(this, _seenSymbols, /* @__PURE__ */ new Set());
100
- __privateAdd(this, _blockPathCounts, /* @__PURE__ */ new Map());
114
+ //
115
+ // Every insertion goes through #markTerminal, which retires the key one
116
+ // catalog-derived block lifetime later (terminalRetentionMsForPacket). The
117
+ // previous bound (trim to 500 at 1000) lived in cancelBlockTimeout alone, so
118
+ // a stream whose blocks only failed grew this set without limit (BLO-36599).
119
+ this.#completedBlocks = /* @__PURE__ */ new Set();
120
+ this.#terminalExpiryMs = /* @__PURE__ */ new Map();
121
+ this.#terminalQueues = /* @__PURE__ */ new Map();
122
+ // sbn -> (block key -> packetId) for every key held by #activeBlocks,
123
+ // #blockSourceCounts, #blockCatalogTrackNames or #completedBlocks. A lookup
124
+ // without a catalog name used to string-parse every key of all of those on
125
+ // each source packet, which is O(retained blocks) per packet (BLO-36599).
126
+ this.#blockKeysBySbn = /* @__PURE__ */ new Map();
127
+ // Stable per-name encodings for stream and block keys, bounded by the
128
+ // catalog's track names; #blockKey is built several times per packet.
129
+ this.#encodedTrackNames = /* @__PURE__ */ new Map();
130
+ // The last block and stream key built. One packet asks for the same block's
131
+ // key from every FECManager entry point it passes through (~6 per source
132
+ // symbol), so each key is built once per packet rather than once per call
133
+ // (BLO-36599). Both keys are pure functions of their arguments.
134
+ this.#lastBlockKeySbn = -1;
135
+ this.#lastBlockKeyPacketId = -1;
136
+ this.#lastBlockKeyTrackName = void 0;
137
+ this.#lastBlockKey = "";
138
+ this.#lastStreamKeyPacketId = -1;
139
+ this.#lastStreamKeyTrackName = void 0;
140
+ this.#lastStreamKey = "";
141
+ this.#seenSymbols = /* @__PURE__ */ new Set();
142
+ this.#blockPathCounts = /* @__PURE__ */ new Map();
101
143
  // Exact catalog identity observed on accepted symbols for each FEC block.
102
144
  // Conflicting identities collapse to null so recovery fails closed.
103
- __privateAdd(this, _blockCatalogTrackNames, /* @__PURE__ */ new Map());
145
+ this.#blockCatalogTrackNames = /* @__PURE__ */ new Map();
104
146
  // A receiver joins an already-running live stream in the middle of D
105
147
  // interleaved source blocks. This applies to both multicast and reliable MoQ:
106
148
  // a MoQ group boundary is not an FEC ESI=0 boundary. Those blocks are not
@@ -108,18 +150,18 @@ var FECManager = class {
108
150
  // each such block until ESI=0 establishes a complete boundary for the track.
109
151
  // After that boundary, a first observed ESI>0 is real delivery loss and must
110
152
  // continue through normal FEC recovery/failure accounting.
111
- __privateAdd(this, _startupAlignedPackets, /* @__PURE__ */ new Set());
112
- __privateAdd(this, _startupPartialBlocks, /* @__PURE__ */ new Set());
153
+ this.#startupAlignedPackets = /* @__PURE__ */ new Set();
154
+ this.#startupPartialBlocks = /* @__PURE__ */ new Set();
113
155
  // A live multicast join can observe an ESI=0 source boundary before the
114
156
  // repair lane catches up. Returning false here also drops that media packet
115
157
  // at MmtpRouter, so the readiness probe is multicast-only and bounded: an
116
158
  // actual multicast repair unlocks the next boundary, while a second source
117
159
  // boundary fails open. Reliable MoQ media continues through normal startup
118
160
  // alignment and retained MoQ repair cannot prove multicast readiness.
119
- __privateAdd(this, _startupRequireRepairReady, false);
120
- __privateAdd(this, _startupRepairReadyPackets, /* @__PURE__ */ new Set());
121
- __privateAdd(this, _startupRepairBoundaryCounts, /* @__PURE__ */ new Map());
122
- __privateAdd(this, _startupRepairFailOpenPackets, /* @__PURE__ */ new Set());
161
+ this.#startupRequireRepairReady = false;
162
+ this.#startupRepairReadyPackets = /* @__PURE__ */ new Set();
163
+ this.#startupRepairBoundaryCounts = /* @__PURE__ */ new Map();
164
+ this.#startupRepairFailOpenPackets = /* @__PURE__ */ new Set();
123
165
  // SBNs that reached K source-symbol arrivals via trackBlock. Used by the
124
166
  // worker recovery suppression check (see onFrame handler below) so we only
125
167
  // suppress `recovered=true` emits for blocks that ALSO completed cleanly
@@ -128,24 +170,26 @@ var FECManager = class {
128
170
  // callers) was the BLO-3323 L15 fix: the prior predicate caused blocksRecovered
129
171
  // to stay at 0 because the SBN was always in #completedBlocks by the time the
130
172
  // worker fired recovered=true.
131
- __privateAdd(this, _cleanlyCompletedBlocks, /* @__PURE__ */ new Set());
173
+ this.#cleanlyCompletedBlocks = /* @__PURE__ */ new Set();
132
174
  // D-28: blocks whose repair deadline already fired onRepairNeeded. At most
133
175
  // one repair request per block; entries are removed when the block
134
176
  // completes, recovers, or fails.
135
- __privateAdd(this, _repairRequestedBlocks, /* @__PURE__ */ new Set());
136
- // D-28: repair-deadline timers refreshed by accepted source progress until
137
- // the first repair request. A `null` value marks a deadline that already
138
- // fired (never re-armed). At most K accepted source symbols can refresh the
139
- // horizon, so browser scheduling delay cannot create an early loss signal
140
- // and repair traffic cannot keep a block alive indefinitely.
141
- __privateAdd(this, _repairDeadlines, /* @__PURE__ */ new Map());
177
+ this.#repairRequestedBlocks = /* @__PURE__ */ new Set();
178
+ // D-28: repair deadlines refreshed by accepted source progress until the
179
+ // first repair request. A `null` value marks a deadline that already fired
180
+ // and requested repair (never re-armed). At most K accepted source symbols
181
+ // can refresh the horizon, so browser scheduling delay cannot create an
182
+ // early loss signal and repair traffic cannot keep a block alive
183
+ // indefinitely. #repairDeadlineAtMs is the authoritative deadline; the one
184
+ // armed timer re-checks it when it fires (see DeadlineTimer).
185
+ this.#repairDeadlines = /* @__PURE__ */ new Map();
186
+ this.#repairDeadlineAtMs = /* @__PURE__ */ new Map();
142
187
  // Worker recovery emits all K source symbols. Track recovery once per block
143
188
  // while routing only ESI slots that were absent from the direct source path.
144
- __privateAdd(this, _workerRecoveredBlocks, /* @__PURE__ */ new Set());
189
+ this.#workerRecoveredBlocks = /* @__PURE__ */ new Set();
145
190
  // Framerate detection state
146
- __privateAdd(this, _fpsDetected, false);
147
- __privateAdd(this, _fecFps);
148
- __privateAdd(this, _fecInterleaveDepthMs, 0);
191
+ this.#fpsDetected = false;
192
+ this.#fecInterleaveDepthMs = 0;
149
193
  // Worker error log rate-limiter — bounds console.warn output and exported
150
194
  // error cardinality when the FEC Worker emits the same failure repeatedly
151
195
  // with volatile packet details (e.g. ssStart) in the message text.
@@ -155,9 +199,9 @@ var FECManager = class {
155
199
  // overlapping message processing). Without this, Point 5 of the 7-point
156
200
  // validation harness — which caps headless warnings at 500 — fails even
157
201
  // though the errors are duplicates of a single underlying event.
158
- __privateAdd(this, _workerErrorCounts, /* @__PURE__ */ new Map());
159
- __privateAdd(this, _decoderUnavailableEvents, 0);
160
- __privateAdd(this, _repairSymbolSizeMismatchCount, 0);
202
+ this.#workerErrorCounts = /* @__PURE__ */ new Map();
203
+ this.#decoderUnavailableEvents = 0;
204
+ this.#repairSymbolSizeMismatchCount = 0;
161
205
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
162
206
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
163
207
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
@@ -192,40 +236,514 @@ var FECManager = class {
192
236
  this.onFecStatsUpdate = null;
193
237
  this.onGreenFill = null;
194
238
  }
239
+ #fecDecoders;
240
+ #workerClients;
241
+ #syncDecoderBlockOwners;
242
+ #decoderBlockOwners;
243
+ #fecK;
244
+ #fecSymbolSize;
245
+ #fecTimeoutMs;
246
+ #trackConfigs;
247
+ #fecStats;
248
+ #fecTrackStats;
249
+ #fecWorkerStats;
250
+ #fecStatsObservers;
251
+ #activeBlocks;
252
+ #activeBlockDeadlinesMs;
253
+ #lifecycleTrace;
254
+ #pendingWorkerCleanups;
255
+ #pendingWorkerCleanupClients;
256
+ #blockSourceCounts;
257
+ #blockSourceEsis;
258
+ #blockAuthoredLengths;
259
+ #ssbLengthConflictCount;
260
+ #blockRepairRsIds;
261
+ #completedBlocks;
262
+ #terminalExpiryMs;
263
+ #terminalQueues;
264
+ #blockKeysBySbn;
265
+ #encodedTrackNames;
266
+ #lastBlockKeySbn;
267
+ #lastBlockKeyPacketId;
268
+ #lastBlockKeyTrackName;
269
+ #lastBlockKey;
270
+ #lastStreamKeyPacketId;
271
+ #lastStreamKeyTrackName;
272
+ #lastStreamKey;
273
+ #seenSymbols;
274
+ #blockPathCounts;
275
+ #blockCatalogTrackNames;
276
+ #startupAlignedPackets;
277
+ #startupPartialBlocks;
278
+ #startupRequireRepairReady;
279
+ #startupRepairReadyPackets;
280
+ #startupRepairBoundaryCounts;
281
+ #startupRepairFailOpenPackets;
282
+ #cleanlyCompletedBlocks;
283
+ #repairRequestedBlocks;
284
+ #repairDeadlines;
285
+ #repairDeadlineAtMs;
286
+ #workerRecoveredBlocks;
287
+ #fpsDetected;
288
+ #fecFps;
289
+ #fecInterleaveDepthMs;
290
+ #workerErrorCounts;
291
+ #decoderUnavailableEvents;
292
+ #repairSymbolSizeMismatchCount;
293
+ #encodeTrackName(catalogTrackName) {
294
+ let encoded = this.#encodedTrackNames.get(catalogTrackName);
295
+ if (encoded === void 0) {
296
+ encoded = encodeURIComponent(catalogTrackName);
297
+ this.#encodedTrackNames.set(catalogTrackName, encoded);
298
+ }
299
+ return encoded;
300
+ }
301
+ #streamKey(packetId, catalogTrackName) {
302
+ if (packetId === this.#lastStreamKeyPacketId && catalogTrackName === this.#lastStreamKeyTrackName) {
303
+ return this.#lastStreamKey;
304
+ }
305
+ const key = catalogTrackName === void 0 ? `${packetId}` : `${packetId}:${this.#encodeTrackName(catalogTrackName)}`;
306
+ this.#lastStreamKeyPacketId = packetId;
307
+ this.#lastStreamKeyTrackName = catalogTrackName;
308
+ this.#lastStreamKey = key;
309
+ return key;
310
+ }
311
+ #belongsToPacket(key, packetId) {
312
+ return Number(key.split(":", 1)[0]) === packetId;
313
+ }
314
+ #belongsToStream(key, packetId, catalogTrackName) {
315
+ if (!this.#belongsToPacket(key, packetId)) return false;
316
+ const parts = key.split(":");
317
+ const encodedTrackName = this.#encodeTrackName(catalogTrackName);
318
+ if (parts.length === 2) return parts[1] === encodedTrackName;
319
+ if (parts.length >= 3) return parts[2] === encodedTrackName;
320
+ return false;
321
+ }
322
+ #packetIdsForStreamKeys(keys) {
323
+ return [...new Set([...keys].map((key) => Number(key.split(":", 1)[0])))];
324
+ }
325
+ #parseStreamKey(key) {
326
+ const separator = key.indexOf(":");
327
+ if (separator < 0) return { packetId: Number(key) || 0 };
328
+ return {
329
+ packetId: Number(key.slice(0, separator)) || 0,
330
+ catalogTrackName: decodeURIComponent(key.slice(separator + 1))
331
+ };
332
+ }
333
+ #blockKey(sbn, packetId, catalogTrackName) {
334
+ if (sbn === this.#lastBlockKeySbn && packetId === this.#lastBlockKeyPacketId && catalogTrackName === this.#lastBlockKeyTrackName) {
335
+ return this.#lastBlockKey;
336
+ }
337
+ const base = `${packetId}:${sbn}`;
338
+ const key = catalogTrackName === void 0 ? base : `${base}:${this.#encodeTrackName(catalogTrackName)}`;
339
+ this.#lastBlockKeySbn = sbn;
340
+ this.#lastBlockKeyPacketId = packetId;
341
+ this.#lastBlockKeyTrackName = catalogTrackName;
342
+ this.#lastBlockKey = key;
343
+ return key;
344
+ }
345
+ /** Record that `key` (block `sbn` on `packetId`) is held by a lookup set. */
346
+ #indexBlockKey(key, sbn, packetId) {
347
+ let keys = this.#blockKeysBySbn.get(sbn);
348
+ if (!keys) {
349
+ keys = /* @__PURE__ */ new Map();
350
+ this.#blockKeysBySbn.set(sbn, keys);
351
+ }
352
+ keys.set(key, packetId);
353
+ }
354
+ /** True while any set a catalog-name-less lookup consults still holds `key`. */
355
+ #isBlockKeyHeld(key) {
356
+ return this.#activeBlocks.has(key) || this.#blockSourceCounts.has(key) || this.#blockCatalogTrackNames.has(key) || this.#completedBlocks.has(key);
357
+ }
358
+ /** Drop `key` from the SBN index once no lookup set holds it any more. */
359
+ #unindexBlockKey(key) {
360
+ if (this.#isBlockKeyHeld(key)) return;
361
+ const sbn = this.#parseBlockKey(key).sbn;
362
+ const keys = this.#blockKeysBySbn.get(sbn);
363
+ if (!keys) return;
364
+ keys.delete(key);
365
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn);
366
+ }
367
+ /**
368
+ * Make `key` terminal: late symbols for it are duplicates from now on. The
369
+ * key is retired one block lifetime later, when no copy of any of its
370
+ * symbols can still be in flight on either transport (see
371
+ * terminalRetentionMsForPacket). Retirement is swept lazily here, on the
372
+ * stream's own terminal events, so it needs no timer.
373
+ */
374
+ #markTerminal(key, sbn, packetId, clean) {
375
+ const nowMs = performance.now();
376
+ this.#retireTerminalBlocks(packetId, nowMs);
377
+ this.#completedBlocks.add(key);
378
+ if (clean) this.#cleanlyCompletedBlocks.add(key);
379
+ this.#indexBlockKey(key, sbn, packetId);
380
+ const expiresAtMs = nowMs + this.terminalRetentionMsForPacket(packetId);
381
+ this.#terminalExpiryMs.set(key, expiresAtMs);
382
+ let queue = this.#terminalQueues.get(packetId);
383
+ if (!queue) {
384
+ queue = new TerminalQueue();
385
+ this.#terminalQueues.set(packetId, queue);
386
+ }
387
+ queue.push({ key, expiresAtMs });
388
+ }
389
+ #retireTerminalBlocks(packetId, nowMs) {
390
+ const queue = this.#terminalQueues.get(packetId);
391
+ if (!queue) return;
392
+ for (let record = queue.peek(); record !== void 0; record = queue.peek()) {
393
+ if (record.expiresAtMs > nowMs) return;
394
+ queue.shift();
395
+ if (this.#terminalExpiryMs.get(record.key) !== record.expiresAtMs) continue;
396
+ this.#terminalExpiryMs.delete(record.key);
397
+ this.#completedBlocks.delete(record.key);
398
+ this.#cleanlyCompletedBlocks.delete(record.key);
399
+ this.#workerRecoveredBlocks.delete(record.key);
400
+ this.#unindexBlockKey(record.key);
401
+ }
402
+ }
403
+ /** Cancel and forget a block's inactivity timer and deadline. */
404
+ #clearBlockTimer(key) {
405
+ const timer = this.#activeBlocks.get(key);
406
+ if (timer?.handle != null) clearTimeout(timer.handle);
407
+ this.#activeBlocks.delete(key);
408
+ this.#activeBlockDeadlinesMs.delete(key);
409
+ }
410
+ #parseBlockKey(key) {
411
+ const [packetIdText, sbnText, ...catalogParts] = key.split(":");
412
+ const catalogTrackName = catalogParts.length > 0 ? decodeURIComponent(catalogParts.join(":")) : void 0;
413
+ return {
414
+ packetId: Number(packetIdText) || 0,
415
+ sbn: Number(sbnText) || 0,
416
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
417
+ };
418
+ }
419
+ #decoderForPacket(packetId, catalogTrackName) {
420
+ return this.#fecDecoders.get(this.#streamKey(packetId, catalogTrackName)) ?? this.#fecDecoders.get(this.#streamKey(packetId));
421
+ }
422
+ #workerForPacket(packetId, catalogTrackName) {
423
+ return this.#workerClients.get(this.#streamKey(packetId, catalogTrackName)) ?? this.#workerClients.get(this.#streamKey(packetId));
424
+ }
425
+ /**
426
+ * The stream's Worker client for routing, or undefined after evicting a
427
+ * registered client that was already disposed. A disposed client throws on
428
+ * every command, so it leaves routing here before a symbol reaches it and
429
+ * the stream reports its decoder unavailable instead.
430
+ */
431
+ #routableWorkerForPacket(packetId, catalogTrackName) {
432
+ const client = this.#workerForPacket(packetId, catalogTrackName);
433
+ if (client === void 0 || client.disposed !== true) return client;
434
+ this.#evictDisposedWorker(client);
435
+ return void 0;
436
+ }
437
+ #claimDecoderBlock(client, sbn, catalogTrackName) {
438
+ let blocks = this.#decoderBlockOwners.get(client);
439
+ if (!blocks) {
440
+ blocks = /* @__PURE__ */ new Map();
441
+ this.#decoderBlockOwners.set(client, blocks);
442
+ }
443
+ const owner = blocks.get(sbn);
444
+ if (!owner) {
445
+ blocks.set(sbn, { catalogTrackName, conflicted: false });
446
+ if (blocks.size > 512) {
447
+ const stale = [...blocks.keys()].slice(0, 256);
448
+ for (const key of stale) blocks.delete(key);
449
+ }
450
+ return true;
451
+ }
452
+ if (owner.conflicted) return false;
453
+ if (owner.catalogTrackName === catalogTrackName) return true;
454
+ owner.conflicted = true;
455
+ return false;
456
+ }
457
+ #decoderBlockCatalogTrackName(client, sbn) {
458
+ const owner = this.#decoderBlockOwners.get(client)?.get(sbn);
459
+ return owner?.conflicted ? void 0 : owner?.catalogTrackName;
460
+ }
461
+ #resetDecoderBlockOwners(client, catalogTrackName) {
462
+ const blocks = this.#decoderBlockOwners.get(client);
463
+ if (!blocks) return;
464
+ for (const [sbn, owner] of blocks) {
465
+ if (owner.catalogTrackName === catalogTrackName || owner.conflicted) {
466
+ blocks.delete(sbn);
467
+ }
468
+ }
469
+ if (blocks.size === 0) this.#decoderBlockOwners.delete(client);
470
+ }
471
+ #discardFecDecoderClient(client) {
472
+ for (const [key, entry] of this.#fecDecoders) {
473
+ if (entry.client === client) this.#fecDecoders.delete(key);
474
+ }
475
+ this.#decoderBlockOwners.delete(client);
476
+ }
477
+ #assertExclusiveDecoderClient(streamKey, client, registrations, kind) {
478
+ for (const [registeredKey, registeredClient] of registrations) {
479
+ if (registeredClient !== client || registeredKey === streamKey) continue;
480
+ throw new Error(
481
+ `[FECManager] ${kind} client is already registered for stream ${registeredKey}; create one client per physical stream`
482
+ );
483
+ }
484
+ }
485
+ #statsForPacket(packetId) {
486
+ let stats = this.#fecTrackStats.get(packetId);
487
+ if (!stats) {
488
+ stats = newFecCounters();
489
+ this.#fecTrackStats.set(packetId, stats);
490
+ }
491
+ return stats;
492
+ }
493
+ #markPathBlockComplete(sbn, packetId, catalogTrackName) {
494
+ const block = this.#blockPathCounts.get(this.#blockKey(sbn, packetId, catalogTrackName));
495
+ if (block) block.complete = true;
496
+ }
497
+ /** Cancel and forget a block's D-28 repair-deadline timer. */
498
+ #clearRepairDeadline(key) {
499
+ const timer = this.#repairDeadlines.get(key);
500
+ if (timer?.handle != null) clearTimeout(timer.handle);
501
+ this.#repairDeadlines.delete(key);
502
+ this.#repairDeadlineAtMs.delete(key);
503
+ }
504
+ /**
505
+ * Move a block's D-28 repair deadline to `delayMs` from now. The timer
506
+ * already armed for an earlier moment fires first and re-arms for the
507
+ * remainder, so repeated source progress costs no timer operation.
508
+ */
509
+ #armRepairDeadline(key, sbn, packetId, catalogTrackName, delayMs) {
510
+ const deadlineMs = performance.now() + delayMs;
511
+ this.#repairDeadlineAtMs.set(key, deadlineMs);
512
+ const armed = this.#repairDeadlines.get(key);
513
+ if (armed?.handle != null) {
514
+ if (armed.fireAtMs <= deadlineMs) return;
515
+ clearTimeout(armed.handle);
516
+ }
517
+ const timer = { handle: null, fireAtMs: deadlineMs };
518
+ const onFire = () => {
519
+ if (this.#repairDeadlines.get(key) !== timer) return;
520
+ const currentDeadlineMs = this.#repairDeadlineAtMs.get(key);
521
+ const nowMs = performance.now();
522
+ if (currentDeadlineMs !== void 0 && currentDeadlineMs > nowMs) {
523
+ timer.fireAtMs = currentDeadlineMs;
524
+ timer.handle = setTimeout(onFire, Math.ceil(currentDeadlineMs - nowMs));
525
+ return;
526
+ }
527
+ timer.handle = null;
528
+ this.#requestRepair(sbn, packetId, catalogTrackName);
529
+ };
530
+ timer.handle = setTimeout(onFire, delayMs);
531
+ this.#repairDeadlines.set(key, timer);
532
+ }
533
+ #requestRepair(sbn, packetId, catalogTrackName) {
534
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
535
+ if (this.#completedBlocks.has(key) || !this.onRepairNeeded || this.#repairRequestedBlocks.has(key)) return;
536
+ const deadline = this.#repairDeadlines.get(key);
537
+ if (deadline?.handle != null) clearTimeout(deadline.handle);
538
+ this.#repairDeadlines.set(key, null);
539
+ this.#repairDeadlineAtMs.delete(key);
540
+ this.#repairRequestedBlocks.add(key);
541
+ const config = this.#resolveTrackConfig(packetId);
542
+ const graceMs = this.#repairGraceMs(config);
543
+ const now = performance.now();
544
+ const currentDeadline = this.#activeBlockDeadlinesMs.get(key) ?? now;
545
+ this.#armBlockTimeout(
546
+ sbn,
547
+ packetId,
548
+ catalogTrackName,
549
+ Math.max(1, Math.ceil(Math.max(now, currentDeadline) + graceMs - now))
550
+ );
551
+ this.#traceLifecycle("repair-requested", sbn, packetId, catalogTrackName);
552
+ if (catalogTrackName === void 0) {
553
+ this.onRepairNeeded(sbn, packetId);
554
+ } else {
555
+ this.onRepairNeeded(sbn, packetId, catalogTrackName);
556
+ }
557
+ }
558
+ #traceLifecycle(event, sbn, packetId, catalogTrackName, rsId) {
559
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
560
+ const deadline = this.#activeBlockDeadlinesMs.get(key);
561
+ const decoderPath = this.#syncDecoderBlockOwners.has(key) ? "sync" : this.#workerForPacket(packetId, catalogTrackName) ? "worker" : this.#decoderForPacket(packetId, catalogTrackName) ? "sync" : "none";
562
+ this.#lifecycleTrace.push({
563
+ atMs: Date.now(),
564
+ event,
565
+ packetId,
566
+ sbn,
567
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName },
568
+ sourceCount: this.#blockSourceCounts.get(key) ?? 0,
569
+ sourceEsis: [...this.#blockSourceEsis.get(key) ?? []].sort((a, b) => a - b),
570
+ repairRsIds: [...this.#blockRepairRsIds.get(key) ?? []].sort((a, b) => a - b),
571
+ decoderPath,
572
+ ...deadline === void 0 ? {} : { deadlineRemainingMs: Math.max(0, deadline - performance.now()) },
573
+ pendingCleanup: this.#pendingWorkerCleanups.has(key),
574
+ ...rsId === void 0 ? {} : { rsId }
575
+ });
576
+ if (this.#lifecycleTrace.length > 64) this.#lifecycleTrace.splice(0, 32);
577
+ }
578
+ #defaultTrackConfig() {
579
+ return {
580
+ k: this.#fecK,
581
+ symbolSize: this.#fecSymbolSize,
582
+ interleaveDepthMs: this.#fecInterleaveDepthMs,
583
+ fps: this.#fecFps,
584
+ timeoutMs: this.#fecTimeoutMs
585
+ };
586
+ }
587
+ #resolveTrackConfig(packetId) {
588
+ return this.#trackConfigs.get(packetId) ?? this.#defaultTrackConfig();
589
+ }
590
+ #computeTimeout(config) {
591
+ if (config.timeoutMs && config.timeoutMs > 0) return config.timeoutMs;
592
+ if (config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS) {
593
+ return Math.max(
594
+ this.#fecTimeoutMs,
595
+ computeFecDeliveryWindowMs({
596
+ interleaveDepthMs: config.interleaveDepthMs,
597
+ sourceSymbols: config.k,
598
+ mediaUnitsPerSecond: config.fps
599
+ })
600
+ );
601
+ }
602
+ return this.#fecTimeoutMs;
603
+ }
604
+ #repairDeadlineMs(config) {
605
+ const halfFailBoundMs = Math.ceil(config.timeoutMs / 2);
606
+ if (config.k > 0 && config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS && config.fps !== void 0 && Number.isFinite(config.fps) && config.fps > 0) {
607
+ const mediaUnitMs = 1e3 / config.fps;
608
+ const interleaveUnits = deriveFecInterleaveDepth(
609
+ config.interleaveDepthMs,
610
+ mediaUnitMs
611
+ );
612
+ const sourceHorizonMs = Math.ceil(config.k * interleaveUnits * mediaUnitMs);
613
+ if (sourceHorizonMs < config.timeoutMs) return sourceHorizonMs;
614
+ }
615
+ return halfFailBoundMs;
616
+ }
617
+ #repairGraceMs(config) {
618
+ return Math.max(1, config.timeoutMs - this.#repairDeadlineMs(config));
619
+ }
620
+ #armBlockTimeout(sbn, packetId, catalogTrackName, delayMs) {
621
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
622
+ const boundedDelayMs = Math.max(1, Math.ceil(delayMs));
623
+ const deadlineMs = performance.now() + boundedDelayMs;
624
+ this.#activeBlockDeadlinesMs.set(key, deadlineMs);
625
+ const armed = this.#activeBlocks.get(key);
626
+ if (armed?.handle != null) {
627
+ if (armed.fireAtMs <= deadlineMs) return;
628
+ clearTimeout(armed.handle);
629
+ }
630
+ const timer = { handle: null, fireAtMs: deadlineMs };
631
+ const onFire = () => {
632
+ if (this.#activeBlocks.get(key) !== timer) return;
633
+ const currentDeadlineMs = this.#activeBlockDeadlinesMs.get(key);
634
+ const nowMs = performance.now();
635
+ if (currentDeadlineMs !== void 0 && currentDeadlineMs > nowMs) {
636
+ timer.fireAtMs = currentDeadlineMs;
637
+ timer.handle = setTimeout(onFire, Math.ceil(currentDeadlineMs - nowMs));
638
+ return;
639
+ }
640
+ this.#activeBlocks.delete(key);
641
+ this.#activeBlockDeadlinesMs.delete(key);
642
+ this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
643
+ const syncOwner = this.#syncDecoderBlockOwners.get(key);
644
+ if (syncOwner) {
645
+ this.#routeSyncCleanup(syncOwner, sbn, packetId);
646
+ this.#failBlock(sbn, packetId, false, catalogTrackName);
647
+ return;
648
+ }
649
+ const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
650
+ if (workerClient) {
651
+ this.#pendingWorkerCleanups.add(key);
652
+ this.#pendingWorkerCleanupClients.set(key, workerClient);
653
+ workerClient.cleanup(sbn);
654
+ } else {
655
+ const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
656
+ if (decoder) {
657
+ this.#routeSyncCleanup(decoder, sbn, packetId);
658
+ this.#failBlock(sbn, packetId, false, catalogTrackName);
659
+ } else {
660
+ this.#failBlock(sbn, packetId, false, catalogTrackName);
661
+ }
662
+ }
663
+ };
664
+ timer.handle = setTimeout(onFire, boundedDelayMs);
665
+ this.#activeBlocks.set(key, timer);
666
+ this.#indexBlockKey(key, sbn, packetId);
667
+ }
668
+ #upsertTrackConfig(packetId, config) {
669
+ const previous = this.#trackConfigs.get(packetId) ?? this.#defaultTrackConfig();
670
+ const timingChanged = config.k !== void 0 || config.interleaveDepthMs !== void 0 || config.fps !== void 0;
671
+ const next = {
672
+ k: config.k ?? previous.k,
673
+ symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previous.symbolSize,
674
+ interleaveDepthMs: config.interleaveDepthMs ?? previous.interleaveDepthMs,
675
+ fps: config.fps ?? previous.fps,
676
+ timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs)
677
+ };
678
+ next.timeoutMs = this.#computeTimeout(next);
679
+ this.#trackConfigs.set(packetId, next);
680
+ return next;
681
+ }
682
+ #normalizeSymbolData(packetId, data) {
683
+ const symbolSize = this.symbolSizeForPacket(packetId);
684
+ if (symbolSize <= 0 || data.byteLength === symbolSize) return data;
685
+ const normalized = new Uint8Array(symbolSize);
686
+ normalized.set(data.subarray(0, symbolSize));
687
+ return normalized;
688
+ }
689
+ #blockKeysFor(sbn, packetId, catalogTrackName) {
690
+ if (packetId != null && catalogTrackName !== void 0) {
691
+ return [this.#blockKey(sbn, packetId, catalogTrackName)];
692
+ }
693
+ const keys = [];
694
+ const candidates = this.#blockKeysBySbn.get(sbn);
695
+ if (candidates) {
696
+ for (const [key, keyPacketId] of candidates) {
697
+ if (packetId !== void 0 && keyPacketId !== packetId) continue;
698
+ if (!this.#isBlockKeyHeld(key)) {
699
+ candidates.delete(key);
700
+ continue;
701
+ }
702
+ keys.push(key);
703
+ }
704
+ if (candidates.size === 0) this.#blockKeysBySbn.delete(sbn);
705
+ }
706
+ if (packetId !== void 0) {
707
+ if (keys.length === 0) return [this.#blockKey(sbn, packetId)];
708
+ return keys.length === 1 ? keys : [];
709
+ }
710
+ return keys.length > 0 ? keys : [this.#blockKey(sbn, 0, catalogTrackName)];
711
+ }
195
712
  // -----------------------------------------------------------------------
196
713
  // Accessors
197
714
  // -----------------------------------------------------------------------
198
715
  /** Internal state for diagnostics — not part of the public stats API. */
199
716
  get diagnostics() {
200
717
  return {
201
- timeoutMs: __privateGet(this, _fecTimeoutMs),
202
- activeBlocks: __privateGet(this, _activeBlocks).size,
203
- completedBlocks: __privateGet(this, _completedBlocks).size,
204
- pendingCounts: Object.fromEntries(__privateGet(this, _blockSourceCounts)),
205
- fpsDetected: __privateGet(this, _fpsDetected),
206
- interleaveDepthMs: __privateGet(this, _fecInterleaveDepthMs),
207
- startupAlignedPackets: __privateMethod(this, _FECManager_instances, packetIdsForStreamKeys_fn).call(this, __privateGet(this, _startupAlignedPackets)),
208
- startupPartialBlocks: __privateGet(this, _startupPartialBlocks).size,
209
- startupRepairReadyPackets: __privateMethod(this, _FECManager_instances, packetIdsForStreamKeys_fn).call(this, __privateGet(this, _startupRepairReadyPackets)),
210
- startupRepairFailOpenPackets: __privateMethod(this, _FECManager_instances, packetIdsForStreamKeys_fn).call(this, __privateGet(this, _startupRepairFailOpenPackets)),
211
- pendingWorkerCleanups: __privateGet(this, _pendingWorkerCleanups).size,
212
- decoderUnavailableEvents: __privateGet(this, _decoderUnavailableEvents),
213
- repairTrackedBlocks: __privateGet(this, _blockRepairRsIds).size,
214
- lifecycleTrace: __privateGet(this, _lifecycleTrace).map((entry) => ({ ...entry }))
718
+ timeoutMs: this.#fecTimeoutMs,
719
+ activeBlocks: this.#activeBlocks.size,
720
+ completedBlocks: this.#completedBlocks.size,
721
+ cleanlyCompletedBlocks: this.#cleanlyCompletedBlocks.size,
722
+ pendingCounts: Object.fromEntries(this.#blockSourceCounts),
723
+ fpsDetected: this.#fpsDetected,
724
+ interleaveDepthMs: this.#fecInterleaveDepthMs,
725
+ startupAlignedPackets: this.#packetIdsForStreamKeys(this.#startupAlignedPackets),
726
+ startupPartialBlocks: this.#startupPartialBlocks.size,
727
+ startupRepairReadyPackets: this.#packetIdsForStreamKeys(this.#startupRepairReadyPackets),
728
+ startupRepairFailOpenPackets: this.#packetIdsForStreamKeys(this.#startupRepairFailOpenPackets),
729
+ pendingWorkerCleanups: this.#pendingWorkerCleanups.size,
730
+ decoderUnavailableEvents: this.#decoderUnavailableEvents,
731
+ repairTrackedBlocks: this.#blockRepairRsIds.size,
732
+ lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
215
733
  };
216
734
  }
217
735
  get fecStats() {
218
- const s = __privateGet(this, _fecStats);
736
+ const s = this.#fecStats;
219
737
  const affected = s.blocksRecovered + s.blocksFailed;
220
738
  const total = s.blocksClean + affected;
221
- const tracks = [...__privateGet(this, _fecTrackStats).entries()].sort(([left], [right]) => left - right).map(([packetId, stats]) => {
739
+ const tracks = [...this.#fecTrackStats.entries()].sort(([left], [right]) => left - right).map(([packetId, stats]) => {
222
740
  const trackAffected = stats.blocksRecovered + stats.blocksFailed;
223
741
  const trackTotal = stats.blocksClean + trackAffected;
224
742
  return {
225
743
  ...stats,
226
744
  packetId,
227
745
  blocksComplete: trackTotal,
228
- k: __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).k,
746
+ k: this.#resolveTrackConfig(packetId).k,
229
747
  recoveryRate: trackAffected > 0 ? stats.blocksRecovered / trackAffected * 100 : 100,
230
748
  packetLossRate: trackTotal > 0 ? trackAffected / trackTotal * 100 : 0
231
749
  };
@@ -233,16 +751,16 @@ var FECManager = class {
233
751
  return {
234
752
  ...s,
235
753
  blocksComplete: total,
236
- mixedPathBlocks: Array.from(__privateGet(this, _blockPathCounts).values()).filter(
754
+ mixedPathBlocks: Array.from(this.#blockPathCounts.values()).filter(
237
755
  (block) => block.multicastSymbols > 0 && block.moqSymbols > 0
238
756
  ).length,
239
- recentBlockPathCounts: Array.from(__privateGet(this, _blockPathCounts).values()).slice(-24),
240
- k: __privateGet(this, _fecK),
757
+ recentBlockPathCounts: Array.from(this.#blockPathCounts.values()).slice(-24),
758
+ k: this.#fecK,
241
759
  // True recovery rate: of blocks that HAD loss, how many were recovered?
242
760
  recoveryRate: affected > 0 ? s.blocksRecovered / affected * 100 : 100,
243
761
  packetLossRate: total > 0 ? affected / total * 100 : 0,
244
762
  tracks,
245
- workers: [...__privateGet(this, _fecWorkerStats).entries()].sort(([left], [right]) => left - right).map(([packetId, stats]) => ({
763
+ workers: [...this.#fecWorkerStats.entries()].sort(([left], [right]) => left - right).map(([packetId, stats]) => ({
246
764
  ...stats,
247
765
  config: {
248
766
  ...stats.config,
@@ -253,8 +771,8 @@ var FECManager = class {
253
771
  altaFailedDetails: stats.altaFailedDetails?.map((detail) => ({ ...detail })),
254
772
  packetId
255
773
  })),
256
- repairSymbolSizeMismatches: __privateGet(this, _repairSymbolSizeMismatchCount),
257
- workerErrors: Object.fromEntries(__privateGet(this, _workerErrorCounts))
774
+ repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
775
+ workerErrors: Object.fromEntries(this.#workerErrorCounts)
258
776
  };
259
777
  }
260
778
  /**
@@ -264,17 +782,17 @@ var FECManager = class {
264
782
  * another's callback.
265
783
  */
266
784
  addFecStatsObserver(observer) {
267
- __privateGet(this, _fecStatsObservers).add(observer);
268
- return () => __privateGet(this, _fecStatsObservers).delete(observer);
785
+ this.#fecStatsObservers.add(observer);
786
+ return () => this.#fecStatsObservers.delete(observer);
269
787
  }
270
788
  /** Start a new multicast transport join without discarding track/decoder state. */
271
789
  beginMulticastJoin() {
272
- __privateGet(this, _startupAlignedPackets).clear();
273
- __privateGet(this, _startupPartialBlocks).clear();
274
- __privateSet(this, _startupRequireRepairReady, true);
275
- __privateGet(this, _startupRepairReadyPackets).clear();
276
- __privateGet(this, _startupRepairBoundaryCounts).clear();
277
- __privateGet(this, _startupRepairFailOpenPackets).clear();
790
+ this.#startupAlignedPackets.clear();
791
+ this.#startupPartialBlocks.clear();
792
+ this.#startupRequireRepairReady = true;
793
+ this.#startupRepairReadyPackets.clear();
794
+ this.#startupRepairBoundaryCounts.clear();
795
+ this.#startupRepairFailOpenPackets.clear();
278
796
  }
279
797
  /** Begin a fresh decode epoch for one physical stream. */
280
798
  resetTrack(packetId, catalogTrackName) {
@@ -286,47 +804,55 @@ var FECManager = class {
286
804
  }
287
805
  const resetMap = (map) => {
288
806
  for (const key of map.keys()) {
289
- if (!__privateMethod(this, _FECManager_instances, belongsToStream_fn).call(this, key, packetId, catalogTrackName)) continue;
807
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue;
290
808
  map.delete(key);
291
809
  }
292
810
  };
293
811
  const resetTimerMap = (map) => {
294
812
  for (const [key, timer] of map) {
295
- if (!__privateMethod(this, _FECManager_instances, belongsToStream_fn).call(this, key, packetId, catalogTrackName)) continue;
296
- if (timer != null) clearTimeout(timer);
813
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue;
814
+ if (timer?.handle != null) clearTimeout(timer.handle);
297
815
  map.delete(key);
298
816
  }
299
817
  };
300
818
  const resetSet = (set) => {
301
819
  for (const key of set) {
302
- if (__privateMethod(this, _FECManager_instances, belongsToStream_fn).call(this, key, packetId, catalogTrackName)) set.delete(key);
820
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) set.delete(key);
303
821
  }
304
822
  };
305
- resetTimerMap(__privateGet(this, _activeBlocks));
306
- resetTimerMap(__privateGet(this, _repairDeadlines));
307
- resetMap(__privateGet(this, _activeBlockDeadlinesMs));
308
- resetMap(__privateGet(this, _activeBlockTimeoutOwners));
309
- resetMap(__privateGet(this, _pendingWorkerCleanupClients));
310
- resetMap(__privateGet(this, _blockSourceCounts));
311
- resetMap(__privateGet(this, _blockSourceEsis));
312
- resetMap(__privateGet(this, _blockRepairRsIds));
313
- resetMap(__privateGet(this, _blockPathCounts));
314
- resetMap(__privateGet(this, _blockCatalogTrackNames));
315
- resetMap(__privateGet(this, _syncDecoderBlockOwners));
316
- resetMap(__privateGet(this, _startupRepairBoundaryCounts));
317
- resetSet(__privateGet(this, _pendingWorkerCleanups));
318
- resetSet(__privateGet(this, _completedBlocks));
319
- resetSet(__privateGet(this, _cleanlyCompletedBlocks));
320
- resetSet(__privateGet(this, _repairRequestedBlocks));
321
- resetSet(__privateGet(this, _workerRecoveredBlocks));
322
- resetSet(__privateGet(this, _startupAlignedPackets));
323
- resetSet(__privateGet(this, _startupPartialBlocks));
324
- resetSet(__privateGet(this, _startupRepairReadyPackets));
325
- resetSet(__privateGet(this, _startupRepairFailOpenPackets));
326
- resetSet(__privateGet(this, _seenSymbols));
823
+ resetTimerMap(this.#activeBlocks);
824
+ resetTimerMap(this.#repairDeadlines);
825
+ resetMap(this.#activeBlockDeadlinesMs);
826
+ resetMap(this.#repairDeadlineAtMs);
827
+ resetMap(this.#terminalExpiryMs);
828
+ resetMap(this.#pendingWorkerCleanupClients);
829
+ resetMap(this.#blockSourceCounts);
830
+ resetMap(this.#blockSourceEsis);
831
+ resetMap(this.#blockAuthoredLengths);
832
+ resetMap(this.#blockRepairRsIds);
833
+ resetMap(this.#blockPathCounts);
834
+ resetMap(this.#blockCatalogTrackNames);
835
+ resetMap(this.#syncDecoderBlockOwners);
836
+ resetMap(this.#startupRepairBoundaryCounts);
837
+ resetSet(this.#pendingWorkerCleanups);
838
+ resetSet(this.#completedBlocks);
839
+ resetSet(this.#cleanlyCompletedBlocks);
840
+ resetSet(this.#repairRequestedBlocks);
841
+ resetSet(this.#workerRecoveredBlocks);
842
+ resetSet(this.#startupAlignedPackets);
843
+ resetSet(this.#startupPartialBlocks);
844
+ resetSet(this.#startupRepairReadyPackets);
845
+ resetSet(this.#startupRepairFailOpenPackets);
846
+ resetSet(this.#seenSymbols);
847
+ for (const [sbn, keys] of this.#blockKeysBySbn) {
848
+ for (const key of keys.keys()) {
849
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) keys.delete(key);
850
+ }
851
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn);
852
+ }
327
853
  const decoderClients = /* @__PURE__ */ new Set();
328
- for (const [key, entry] of __privateGet(this, _fecDecoders)) {
329
- if (__privateMethod(this, _FECManager_instances, belongsToStream_fn).call(this, key, packetId, catalogTrackName)) {
854
+ for (const [key, entry] of this.#fecDecoders) {
855
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) {
330
856
  decoderClients.add(entry.client);
331
857
  }
332
858
  }
@@ -338,74 +864,74 @@ var FECManager = class {
338
864
  client.reset_stats();
339
865
  clients.add(client);
340
866
  } catch {
341
- __privateMethod(this, _FECManager_instances, discardFecDecoderClient_fn).call(this, client);
867
+ this.#discardFecDecoderClient(client);
342
868
  }
343
869
  } else {
344
- __privateMethod(this, _FECManager_instances, discardFecDecoderClient_fn).call(this, client);
870
+ this.#discardFecDecoderClient(client);
345
871
  }
346
872
  }
347
- for (const [key, client] of [...__privateGet(this, _workerClients)]) {
348
- if (!__privateMethod(this, _FECManager_instances, belongsToStream_fn).call(this, key, packetId, catalogTrackName)) continue;
873
+ for (const [key, client] of [...this.#workerClients]) {
874
+ if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue;
349
875
  if (client.disposed === true) {
350
- __privateMethod(this, _FECManager_instances, evictDisposedWorker_fn).call(this, client);
876
+ this.#evictDisposedWorker(client);
351
877
  continue;
352
878
  }
353
879
  client.reset();
354
880
  clients.add(client);
355
881
  }
356
- for (const client of clients) __privateMethod(this, _FECManager_instances, resetDecoderBlockOwners_fn).call(this, client, catalogTrackName);
882
+ for (const client of clients) this.#resetDecoderBlockOwners(client, catalogTrackName);
357
883
  }
358
884
  /** Record a transport symbol and reject later duplicates of the same packetId/SBN/ESI. */
359
885
  feedSymbolFromSource(packetId, sbn, esi, _data, source, catalogTrackName) {
360
- const blockKey = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
361
- const streamKey = __privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName);
886
+ const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
887
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
362
888
  const k = this.kForPacket(packetId);
363
889
  const isSourceSymbol = esi >= 0 && esi < k;
364
- const isStartupPartial = __privateGet(this, _startupPartialBlocks).has(blockKey);
365
- const isReadyMulticastRepair = __privateGet(this, _startupRequireRepairReady) && source === "multicast" && !isSourceSymbol && __privateGet(this, _startupRepairReadyPackets).has(streamKey);
366
- const awaitingMulticastRepair = __privateGet(this, _startupRequireRepairReady) && source === "multicast" && !__privateGet(this, _startupRepairReadyPackets).has(streamKey) && !__privateGet(this, _startupRepairFailOpenPackets).has(streamKey);
890
+ const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
891
+ const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
892
+ const awaitingMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
367
893
  if (awaitingMulticastRepair) {
368
894
  if (!isSourceSymbol) {
369
- __privateGet(this, _startupRepairReadyPackets).add(streamKey);
370
- __privateGet(this, _startupRepairBoundaryCounts).delete(streamKey);
371
- __privateMethod(this, _FECManager_instances, markStartupPartial_fn).call(this, blockKey);
895
+ this.#startupRepairReadyPackets.add(streamKey);
896
+ this.#startupRepairBoundaryCounts.delete(streamKey);
897
+ this.#markStartupPartial(blockKey);
372
898
  return false;
373
899
  }
374
900
  if (esi === 0) {
375
- const boundaries = (__privateGet(this, _startupRepairBoundaryCounts).get(streamKey) ?? 0) + 1;
376
- __privateGet(this, _startupRepairBoundaryCounts).set(streamKey, boundaries);
901
+ const boundaries = (this.#startupRepairBoundaryCounts.get(streamKey) ?? 0) + 1;
902
+ this.#startupRepairBoundaryCounts.set(streamKey, boundaries);
377
903
  if (boundaries >= STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES) {
378
- __privateGet(this, _startupRepairBoundaryCounts).delete(streamKey);
379
- __privateGet(this, _startupRepairFailOpenPackets).add(streamKey);
904
+ this.#startupRepairBoundaryCounts.delete(streamKey);
905
+ this.#startupRepairFailOpenPackets.add(streamKey);
380
906
  } else {
381
- __privateMethod(this, _FECManager_instances, markStartupPartial_fn).call(this, blockKey);
907
+ this.#markStartupPartial(blockKey);
382
908
  return false;
383
909
  }
384
910
  } else {
385
- __privateMethod(this, _FECManager_instances, markStartupPartial_fn).call(this, blockKey);
911
+ this.#markStartupPartial(blockKey);
386
912
  return false;
387
913
  }
388
914
  }
389
915
  if (isSourceSymbol && esi === 0) {
390
- __privateGet(this, _startupPartialBlocks).delete(blockKey);
391
- __privateGet(this, _startupAlignedPackets).add(streamKey);
392
- } else if (isStartupPartial && !isReadyMulticastRepair || !__privateGet(this, _startupAlignedPackets).has(streamKey) && !isReadyMulticastRepair) {
393
- __privateMethod(this, _FECManager_instances, markStartupPartial_fn).call(this, blockKey);
916
+ this.#startupPartialBlocks.delete(blockKey);
917
+ this.#startupAlignedPackets.add(streamKey);
918
+ } else if (isStartupPartial && !isReadyMulticastRepair || !this.#startupAlignedPackets.has(streamKey) && !isReadyMulticastRepair) {
919
+ this.#markStartupPartial(blockKey);
394
920
  return false;
395
921
  }
396
- if (__privateGet(this, _completedBlocks).has(blockKey)) {
397
- __privateGet(this, _fecStats).duplicateSymbols++;
398
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).duplicateSymbols++;
922
+ if (this.#completedBlocks.has(blockKey)) {
923
+ this.#fecStats.duplicateSymbols++;
924
+ this.#statsForPacket(packetId).duplicateSymbols++;
399
925
  return false;
400
926
  }
401
927
  const symbolKey = `${blockKey}:${esi}`;
402
- if (__privateGet(this, _seenSymbols).has(symbolKey)) {
403
- __privateGet(this, _fecStats).duplicateSymbols++;
404
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).duplicateSymbols++;
928
+ if (this.#seenSymbols.has(symbolKey)) {
929
+ this.#fecStats.duplicateSymbols++;
930
+ this.#statsForPacket(packetId).duplicateSymbols++;
405
931
  return false;
406
932
  }
407
- __privateGet(this, _seenSymbols).add(symbolKey);
408
- const counts = __privateGet(this, _blockPathCounts).get(blockKey) ?? {
933
+ this.#seenSymbols.add(symbolKey);
934
+ const counts = this.#blockPathCounts.get(blockKey) ?? {
409
935
  packetId,
410
936
  sbn,
411
937
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
@@ -415,49 +941,71 @@ var FECManager = class {
415
941
  };
416
942
  if (source === "multicast") counts.multicastSymbols++;
417
943
  else counts.moqSymbols++;
418
- __privateGet(this, _blockPathCounts).set(blockKey, counts);
419
- __privateMethod(this, _FECManager_instances, observeBlockCatalogTrackName_fn).call(this, blockKey, catalogTrackName);
420
- if (__privateGet(this, _seenSymbols).size > 4096) {
421
- __privateSet(this, _seenSymbols, new Set(Array.from(__privateGet(this, _seenSymbols)).slice(-2048)));
944
+ this.#blockPathCounts.set(blockKey, counts);
945
+ this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
946
+ if (this.#seenSymbols.size > 4096) {
947
+ dropOldest(this.#seenSymbols, this.#seenSymbols.size - 2048);
422
948
  }
423
- if (__privateGet(this, _blockPathCounts).size > 512) {
424
- __privateSet(this, _blockPathCounts, new Map(Array.from(__privateGet(this, _blockPathCounts)).slice(-256)));
949
+ if (this.#blockPathCounts.size > 512) {
950
+ dropOldest(this.#blockPathCounts, this.#blockPathCounts.size - 256);
425
951
  }
426
- if (__privateGet(this, _blockCatalogTrackNames).size > 512) {
427
- __privateSet(this, _blockCatalogTrackNames, new Map(
428
- Array.from(__privateGet(this, _blockCatalogTrackNames)).slice(-256)
429
- ));
952
+ if (this.#blockCatalogTrackNames.size > 512) {
953
+ for (const key of dropOldest(
954
+ this.#blockCatalogTrackNames,
955
+ this.#blockCatalogTrackNames.size - 256
956
+ )) {
957
+ this.#unindexBlockKey(key);
958
+ }
430
959
  }
431
960
  return true;
432
961
  }
962
+ #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
963
+ if (catalogTrackName === void 0) return;
964
+ if (!this.#blockCatalogTrackNames.has(blockKey)) {
965
+ this.#blockCatalogTrackNames.set(blockKey, catalogTrackName);
966
+ this.#indexBlockKey(blockKey, sbn, packetId);
967
+ return;
968
+ }
969
+ if (this.#blockCatalogTrackNames.get(blockKey) !== catalogTrackName) {
970
+ this.#blockCatalogTrackNames.set(blockKey, null);
971
+ }
972
+ }
433
973
  /** Exact catalog identity retained for async recovery, if unambiguous. */
434
974
  catalogTrackNameForBlock(sbn, packetId, catalogTrackName) {
435
975
  if (catalogTrackName !== void 0) {
436
- return __privateGet(this, _blockCatalogTrackNames).get(
437
- __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName)
976
+ return this.#blockCatalogTrackNames.get(
977
+ this.#blockKey(sbn, packetId, catalogTrackName)
438
978
  ) ?? void 0;
439
979
  }
440
980
  const names = /* @__PURE__ */ new Set();
441
- for (const [key, name] of __privateGet(this, _blockCatalogTrackNames)) {
442
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
981
+ for (const [key, name] of this.#blockCatalogTrackNames) {
982
+ const block = this.#parseBlockKey(key);
443
983
  if (block.packetId === packetId && block.sbn === sbn && name !== null) names.add(name);
444
984
  }
445
985
  return names.size === 1 ? [...names][0] : void 0;
446
986
  }
987
+ #markStartupPartial(blockKey) {
988
+ this.#startupPartialBlocks.add(blockKey);
989
+ if (this.#startupPartialBlocks.size > 128) {
990
+ this.#startupPartialBlocks = new Set(
991
+ Array.from(this.#startupPartialBlocks).slice(-64)
992
+ );
993
+ }
994
+ }
447
995
  /** Per-block state snapshot for FecBlockGrid visualization.
448
996
  * Returns the most recent blocks (active + recently completed). */
449
997
  getBlockStates() {
450
998
  const blocks = [];
451
- for (const [key] of __privateGet(this, _activeBlocks)) {
452
- const { packetId, sbn } = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
453
- const count = __privateGet(this, _blockSourceCounts).get(key) ?? 0;
454
- const k = this.kForPacket(packetId);
999
+ for (const [key] of this.#activeBlocks) {
1000
+ const { packetId, sbn } = this.#parseBlockKey(key);
1001
+ const count = this.#blockSourceCounts.get(key) ?? 0;
1002
+ const k = this.#blockAuthoredLengths.get(key) ?? this.kForPacket(packetId);
455
1003
  blocks.push({ sbn, packetId, state: "collecting", sourceCount: count, k, progress: k > 0 ? Math.min(count / k, 1) : 0 });
456
1004
  }
457
- const completed = [...__privateGet(this, _completedBlocks)].slice(-16);
1005
+ const completed = [...this.#completedBlocks].slice(-16);
458
1006
  for (const key of completed) {
459
- const { packetId, sbn } = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
460
- if (!__privateGet(this, _activeBlocks).has(key)) {
1007
+ const { packetId, sbn } = this.#parseBlockKey(key);
1008
+ if (!this.#activeBlocks.has(key)) {
461
1009
  const k = this.kForPacket(packetId);
462
1010
  blocks.push({ sbn, packetId, state: "complete", sourceCount: k, k, progress: 1 });
463
1011
  }
@@ -467,87 +1015,105 @@ var FECManager = class {
467
1015
  }
468
1016
  /** The raw WASM decoder for stats access (first registered decoder) */
469
1017
  get wasmDecoder() {
470
- return __privateGet(this, _fecDecoders).values().next().value?.client ?? null;
1018
+ return this.#fecDecoders.values().next().value?.client ?? null;
471
1019
  }
472
1020
  get k() {
473
- return __privateGet(this, _fecK);
1021
+ return this.#fecK;
474
1022
  }
475
1023
  kForPacket(packetId) {
476
- return __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).k;
1024
+ return this.#resolveTrackConfig(packetId).k;
477
1025
  }
478
1026
  /** FEC symbol size in bytes. */
479
1027
  get symbolSize() {
480
- return __privateGet(this, _fecSymbolSize);
1028
+ return this.#fecSymbolSize;
481
1029
  }
482
1030
  symbolSizeForPacket(packetId) {
483
- return __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).symbolSize;
1031
+ return this.#resolveTrackConfig(packetId).symbolSize;
484
1032
  }
485
1033
  /** FEC block span in milliseconds (0 = no interleaving). */
486
1034
  get interleaveDepthMs() {
487
- return __privateGet(this, _fecInterleaveDepthMs);
1035
+ return this.#fecInterleaveDepthMs;
488
1036
  }
489
1037
  interleaveDepthMsForPacket(packetId) {
490
- return __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).interleaveDepthMs;
1038
+ return this.#resolveTrackConfig(packetId).interleaveDepthMs;
491
1039
  }
492
1040
  /** Resolved per-track block fail bound in milliseconds. */
493
1041
  timeoutMsForPacket(packetId) {
494
- return __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).timeoutMs;
1042
+ return this.#resolveTrackConfig(packetId).timeoutMs;
495
1043
  }
496
1044
  /** Resolved per-track D-28 repair request deadline in milliseconds. */
497
1045
  repairDeadlineMsForPacket(packetId) {
498
- return __privateMethod(this, _FECManager_instances, repairDeadlineMs_fn).call(this, __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId));
1046
+ return this.#repairDeadlineMs(this.#resolveTrackConfig(packetId));
1047
+ }
1048
+ /**
1049
+ * How long a terminal (clean, recovered or failed) block stays authoritative
1050
+ * for late symbols: one full block lifetime, i.e. the inactivity fail bound
1051
+ * plus the D-28 repair grace a repair-requested block may be granted. No
1052
+ * copy of a block's symbols is useful, or awaited, beyond the moment the
1053
+ * block itself would have been failed, so a copy arriving later is dropped
1054
+ * by the other bounded ledgers rather than by this one. Both terms come from
1055
+ * the track's catalog geometry; there is no separate cap.
1056
+ */
1057
+ terminalRetentionMsForPacket(packetId) {
1058
+ const config = this.#resolveTrackConfig(packetId);
1059
+ return config.timeoutMs + this.#repairGraceMs(config);
499
1060
  }
500
1061
  /** Remaining fetch budget for a specific repair-requested block. */
501
1062
  repairFetchTimeoutMsForBlock(sbn, packetId, catalogTrackName) {
502
- const deadlineMs = __privateGet(this, _activeBlockDeadlinesMs).get(
503
- __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName)
1063
+ const deadlineMs = this.#activeBlockDeadlinesMs.get(
1064
+ this.#blockKey(sbn, packetId, catalogTrackName)
504
1065
  );
505
1066
  if (deadlineMs !== void 0) {
506
1067
  return Math.max(1, Math.ceil(deadlineMs - performance.now()));
507
1068
  }
508
- const trackConfig = __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId);
509
- return Math.max(1, trackConfig.timeoutMs - __privateMethod(this, _FECManager_instances, repairDeadlineMs_fn).call(this, trackConfig));
1069
+ const trackConfig = this.#resolveTrackConfig(packetId);
1070
+ return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
510
1071
  }
511
1072
  // -----------------------------------------------------------------------
512
1073
  // Configuration
513
1074
  // -----------------------------------------------------------------------
514
1075
  /** Configure FEC parameters. */
515
1076
  configure(config) {
516
- if (config.k != null) __privateSet(this, _fecK, config.k);
517
- if (config.symbolSize != null && config.symbolSize > 0) __privateSet(this, _fecSymbolSize, config.symbolSize);
518
- if (config.interleaveDepthMs != null) __privateSet(this, _fecInterleaveDepthMs, config.interleaveDepthMs);
1077
+ if (config.k != null) this.#fecK = config.k;
1078
+ if (config.symbolSize != null && config.symbolSize > 0) this.#fecSymbolSize = config.symbolSize;
1079
+ if (config.interleaveDepthMs != null) this.#fecInterleaveDepthMs = config.interleaveDepthMs;
519
1080
  if (config.fps != null && Number.isFinite(config.fps) && config.fps > 0) {
520
- __privateSet(this, _fecFps, config.fps);
1081
+ this.#fecFps = config.fps;
521
1082
  }
522
1083
  if (config.interleaveDepthMs != null && config.interleaveDepthMs > 0 && config.interleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS) {
523
1084
  console.warn(`[FECManager] interleaveDepthMs=${config.interleaveDepthMs} looks like frame count, not milliseconds (\xA75.1 requires ms). Expected range: ${MIN_INTERLEAVE_DEPTH_MS}-10000ms.`);
524
1085
  }
525
1086
  if (config.timeoutMs != null && config.timeoutMs > 0) {
526
- __privateSet(this, _fecTimeoutMs, config.timeoutMs);
1087
+ this.#fecTimeoutMs = config.timeoutMs;
527
1088
  } else if (config.interleaveDepthMs != null && config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS) {
528
- __privateSet(this, _fecTimeoutMs, computeFecDeliveryWindowMs({
1089
+ this.#fecTimeoutMs = computeFecDeliveryWindowMs({
529
1090
  interleaveDepthMs: config.interleaveDepthMs,
530
- sourceSymbols: __privateGet(this, _fecK),
531
- symbolSize: __privateGet(this, _fecSymbolSize),
1091
+ sourceSymbols: this.#fecK,
1092
+ symbolSize: this.#fecSymbolSize,
532
1093
  mediaUnitsPerSecond: config.fps
533
- }));
1094
+ });
534
1095
  }
535
- for (const [packetId, track] of __privateGet(this, _trackConfigs)) {
536
- if (track.timeoutMs < __privateGet(this, _fecTimeoutMs)) {
537
- __privateGet(this, _trackConfigs).set(packetId, { ...track, timeoutMs: __privateGet(this, _fecTimeoutMs) });
1096
+ for (const [packetId, track] of this.#trackConfigs) {
1097
+ if (track.timeoutMs < this.#fecTimeoutMs) {
1098
+ this.#trackConfigs.set(packetId, { ...track, timeoutMs: this.#fecTimeoutMs });
538
1099
  }
539
1100
  }
540
1101
  }
541
1102
  /** Configure FEC parameters for one packetId without changing legacy defaults. */
542
1103
  configureTrack(packetId, config) {
543
- __privateMethod(this, _FECManager_instances, upsertTrackConfig_fn).call(this, packetId, config);
1104
+ this.#upsertTrackConfig(packetId, config);
544
1105
  }
545
1106
  /** Register a FEC decoder for a specific packetId (track). */
546
1107
  setFecDecoder(packetId, client, k, config, catalogTrackName) {
547
- const streamKey = __privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName);
548
- __privateMethod(this, _FECManager_instances, assertExclusiveDecoderClient_fn).call(this, streamKey, client, [...__privateGet(this, _fecDecoders)].map(([key, entry]) => [key, entry.client]), "decoder");
549
- const trackConfig = __privateMethod(this, _FECManager_instances, upsertTrackConfig_fn).call(this, packetId, { ...config, k });
550
- __privateGet(this, _fecDecoders).set(streamKey, { client, k: trackConfig.k });
1108
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
1109
+ this.#assertExclusiveDecoderClient(
1110
+ streamKey,
1111
+ client,
1112
+ [...this.#fecDecoders].map(([key, entry]) => [key, entry.client]),
1113
+ "decoder"
1114
+ );
1115
+ const trackConfig = this.#upsertTrackConfig(packetId, { ...config, k });
1116
+ this.#fecDecoders.set(streamKey, { client, k: trackConfig.k });
551
1117
  }
552
1118
  /**
553
1119
  * Register a Worker-backed FEC decoder for a specific packetId (track).
@@ -568,49 +1134,69 @@ var FECManager = class {
568
1134
  `[FECManager] packetId=${packetId} Worker requires an explicit positive symbolSize`
569
1135
  );
570
1136
  }
571
- const streamKey = __privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName);
572
- __privateMethod(this, _FECManager_instances, assertExclusiveDecoderClient_fn).call(this, streamKey, client, __privateGet(this, _workerClients), "worker");
573
- const incumbent = __privateGet(this, _workerClients).get(streamKey);
1137
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
1138
+ this.#assertExclusiveDecoderClient(
1139
+ streamKey,
1140
+ client,
1141
+ this.#workerClients,
1142
+ "worker"
1143
+ );
1144
+ const incumbent = this.#workerClients.get(streamKey);
574
1145
  if (incumbent !== void 0 && incumbent !== client) {
575
1146
  throw new Error(
576
1147
  `[FECManager] stream ${streamKey} already routes to a Worker; call clearFecWorker before registering another`
577
1148
  );
578
1149
  }
579
- if (config) __privateMethod(this, _FECManager_instances, upsertTrackConfig_fn).call(this, packetId, config);
580
- const workerK = __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).k;
581
- __privateGet(this, _workerClients).set(streamKey, client);
1150
+ if (config) this.#upsertTrackConfig(packetId, config);
1151
+ const workerK = this.#resolveTrackConfig(packetId).k;
1152
+ this.#workerClients.set(streamKey, client);
582
1153
  client.onFrame((data, meta) => {
583
1154
  if (meta.recovered) {
584
- if (!Number.isInteger(meta.esi) || meta.esi < 0 || meta.esi >= workerK) {
1155
+ if (!Number.isInteger(meta.ssbLength) || meta.ssbLength <= 0 || meta.ssbLength > workerK) {
1156
+ const kind = "recovered-symbol-ssb-length-invalid";
1157
+ const seen = this.#workerErrorCounts.get(kind) ?? 0;
1158
+ this.#workerErrorCounts.set(kind, seen + 1);
1159
+ if (seen < WORKER_ERROR_LOG_CAP) {
1160
+ console.warn(
1161
+ `[FECManager] Dropping recovered symbol with invalid SSB_length: pid=${packetId} sbn=${meta.sbn} ssbLength=${String(meta.ssbLength)}`
1162
+ );
1163
+ }
1164
+ return;
1165
+ }
1166
+ if (!Number.isInteger(meta.esi) || meta.esi < 0 || meta.esi >= meta.ssbLength) {
585
1167
  const kind = "recovered-symbol-missing-esi";
586
- const seen = __privateGet(this, _workerErrorCounts).get(kind) ?? 0;
587
- __privateGet(this, _workerErrorCounts).set(kind, seen + 1);
1168
+ const seen = this.#workerErrorCounts.get(kind) ?? 0;
1169
+ this.#workerErrorCounts.set(kind, seen + 1);
588
1170
  if (seen < WORKER_ERROR_LOG_CAP) {
589
1171
  console.warn(
590
- `[FECManager] Dropping recovered symbol without valid ESI: pid=${packetId} sbn=${meta.sbn} esi=${String(meta.esi)}`
1172
+ `[FECManager] Dropping recovered symbol without valid ESI: pid=${packetId} sbn=${meta.sbn} esi=${String(meta.esi)} ssbLength=${String(meta.ssbLength)}`
591
1173
  );
592
1174
  }
593
1175
  return;
594
1176
  }
595
1177
  const esi = meta.esi;
596
- const recoveredCatalogTrackName = catalogTrackName ?? __privateMethod(this, _FECManager_instances, decoderBlockCatalogTrackName_fn).call(this, client, meta.sbn);
597
- if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, client, meta.sbn, recoveredCatalogTrackName)) return;
598
- const blockKey = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, meta.sbn, packetId, recoveredCatalogTrackName);
599
- const cleanlyCompleted = __privateGet(this, _cleanlyCompletedBlocks).has(blockKey);
1178
+ const recoveredCatalogTrackName = catalogTrackName ?? this.#decoderBlockCatalogTrackName(client, meta.sbn);
1179
+ if (!this.#claimDecoderBlock(client, meta.sbn, recoveredCatalogTrackName)) return;
1180
+ const blockKey = this.#blockKey(meta.sbn, packetId, recoveredCatalogTrackName);
1181
+ const cleanlyCompleted = this.#cleanlyCompletedBlocks.has(blockKey);
600
1182
  if (!cleanlyCompleted) {
601
- if (!__privateGet(this, _workerRecoveredBlocks).has(blockKey)) {
602
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "recovered", meta.sbn, packetId, recoveredCatalogTrackName);
603
- __privateGet(this, _workerRecoveredBlocks).add(blockKey);
604
- __privateGet(this, _fecStats).blocksRecovered++;
605
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).blocksRecovered++;
606
- if (__privateGet(this, _workerRecoveredBlocks).size > 1e3) {
607
- const stale = Array.from(__privateGet(this, _workerRecoveredBlocks)).slice(0, 500);
608
- for (const key of stale) __privateGet(this, _workerRecoveredBlocks).delete(key);
1183
+ if (!this.#workerRecoveredBlocks.has(blockKey)) {
1184
+ this.#traceLifecycle(
1185
+ "recovered",
1186
+ meta.sbn,
1187
+ packetId,
1188
+ recoveredCatalogTrackName
1189
+ );
1190
+ this.#workerRecoveredBlocks.add(blockKey);
1191
+ this.#fecStats.blocksRecovered++;
1192
+ this.#statsForPacket(packetId).blocksRecovered++;
1193
+ if (this.#workerRecoveredBlocks.size > 1e3) {
1194
+ dropOldest(this.#workerRecoveredBlocks, 500);
609
1195
  }
610
1196
  }
611
1197
  const symbolKey = `${blockKey}:${esi}`;
612
- if (!__privateGet(this, _seenSymbols).has(symbolKey)) {
613
- __privateGet(this, _seenSymbols).add(symbolKey);
1198
+ if (!this.#seenSymbols.has(symbolKey)) {
1199
+ this.#seenSymbols.add(symbolKey);
614
1200
  this.onBlockRecovered?.(
615
1201
  meta.sbn,
616
1202
  packetId,
@@ -620,7 +1206,7 @@ var FECManager = class {
620
1206
  );
621
1207
  }
622
1208
  }
623
- if (esi >= workerK - 1 && !__privateGet(this, _completedBlocks).has(blockKey)) {
1209
+ if (esi >= meta.ssbLength - 1 && !this.#completedBlocks.has(blockKey)) {
624
1210
  this.cancelBlockTimeout(meta.sbn, packetId, recoveredCatalogTrackName);
625
1211
  if (recoveredCatalogTrackName === void 0) {
626
1212
  this.onBlockComplete?.(meta.sbn, packetId);
@@ -633,18 +1219,18 @@ var FECManager = class {
633
1219
  }
634
1220
  }
635
1221
  } else {
636
- const completedCatalogTrackName = catalogTrackName ?? __privateMethod(this, _FECManager_instances, decoderBlockCatalogTrackName_fn).call(this, client, meta.sbn);
1222
+ const completedCatalogTrackName = catalogTrackName ?? this.#decoderBlockCatalogTrackName(client, meta.sbn);
637
1223
  this.markBlockCompleted(meta.sbn, packetId, completedCatalogTrackName);
638
1224
  }
639
1225
  });
640
1226
  client.onSnapshot((stats) => {
641
- __privateGet(this, _fecWorkerStats).set(packetId, stats);
1227
+ this.#fecWorkerStats.set(packetId, stats);
642
1228
  try {
643
1229
  this.onFecStatsUpdate?.(packetId, stats);
644
1230
  } catch (error) {
645
1231
  console.warn("[FECManager] FEC stats callback failed:", error);
646
1232
  }
647
- for (const observer of __privateGet(this, _fecStatsObservers)) {
1233
+ for (const observer of this.#fecStatsObservers) {
648
1234
  try {
649
1235
  observer(packetId, stats);
650
1236
  } catch (error) {
@@ -653,22 +1239,22 @@ var FECManager = class {
653
1239
  }
654
1240
  });
655
1241
  client.onGreenFill((sbn, data) => {
656
- __privateGet(this, _fecStats).greenFillFrames++;
657
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).greenFillFrames++;
1242
+ this.#fecStats.greenFillFrames++;
1243
+ this.#statsForPacket(packetId).greenFillFrames++;
658
1244
  this.onGreenFill?.(sbn, packetId, data);
659
1245
  });
660
1246
  client.onCleanupComplete((sbn) => {
661
- const cleanupKeys = [...__privateGet(this, _pendingWorkerCleanups)].filter((key) => {
662
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
663
- return block.packetId === packetId && block.sbn === sbn && __privateGet(this, _pendingWorkerCleanupClients).get(key) === client;
1247
+ const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
1248
+ const block = this.#parseBlockKey(key);
1249
+ return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
664
1250
  });
665
- for (const key of cleanupKeys) __privateMethod(this, _FECManager_instances, settleOwedCleanup_fn).call(this, key, "cleanup-ack");
1251
+ for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
666
1252
  });
667
1253
  client.onError((msg, code) => {
668
1254
  const requestedKind = code ?? msg;
669
- const kind = __privateGet(this, _workerErrorCounts).has(requestedKind) || __privateGet(this, _workerErrorCounts).size < WORKER_ERROR_KIND_CAP - 1 ? requestedKind : WORKER_ERROR_OVERFLOW_KIND;
670
- const seen = __privateGet(this, _workerErrorCounts).get(kind) ?? 0;
671
- __privateGet(this, _workerErrorCounts).set(kind, seen + 1);
1255
+ const kind = this.#workerErrorCounts.has(requestedKind) || this.#workerErrorCounts.size < WORKER_ERROR_KIND_CAP - 1 ? requestedKind : WORKER_ERROR_OVERFLOW_KIND;
1256
+ const seen = this.#workerErrorCounts.get(kind) ?? 0;
1257
+ this.#workerErrorCounts.set(kind, seen + 1);
672
1258
  if (seen < WORKER_ERROR_LOG_CAP) {
673
1259
  console.warn("[FECManager] Worker error:", msg);
674
1260
  } else if (seen === WORKER_ERROR_LOG_CAP) {
@@ -691,32 +1277,85 @@ var FECManager = class {
691
1277
  * evicted on its next symbol or reset with reason 'disposed'.
692
1278
  */
693
1279
  clearFecWorker(packetId, catalogTrackName) {
694
- const streamKey = __privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName);
695
- const client = __privateGet(this, _workerClients).get(streamKey);
1280
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
1281
+ const client = this.#workerClients.get(streamKey);
696
1282
  if (!client) return false;
697
- __privateMethod(this, _FECManager_instances, retireWorker_fn).call(this, streamKey, client, "cleared");
1283
+ this.#retireWorker(streamKey, client, "cleared");
698
1284
  return true;
699
1285
  }
1286
+ /**
1287
+ * Take a Worker client out of routing under one stream key, fail the blocks
1288
+ * whose completion it still owed, and report the stream's decoder
1289
+ * unavailable together with whatever still decodes the stream.
1290
+ */
1291
+ #retireWorker(streamKey, client, reason) {
1292
+ this.#workerClients.delete(streamKey);
1293
+ this.#releaseWorkerClient(client);
1294
+ this.#decoderUnavailableEvents++;
1295
+ const stream = this.#parseStreamKey(streamKey);
1296
+ const fallbackDecoder = this.#decoderForPacket(stream.packetId, stream.catalogTrackName) ? "sync" : "none";
1297
+ this.onDecoderUnavailable?.({
1298
+ packetId: stream.packetId,
1299
+ ...stream.catalogTrackName === void 0 ? {} : { catalogTrackName: stream.catalogTrackName },
1300
+ reason,
1301
+ fallbackDecoder
1302
+ });
1303
+ }
1304
+ /**
1305
+ * Fail every block whose Worker cleanup acknowledgement is owed by `client`
1306
+ * and drop its block ownership, so no block waits on a message the Worker
1307
+ * will never post.
1308
+ */
1309
+ #releaseWorkerClient(client) {
1310
+ const owed = [...this.#pendingWorkerCleanupClients].filter(([, owner]) => owner === client).map(([key]) => key);
1311
+ for (const key of owed) this.#settleOwedCleanup(key, "decoder-unavailable");
1312
+ this.#decoderBlockOwners.delete(client);
1313
+ }
1314
+ /**
1315
+ * Resolve one owed Worker cleanup: drop the pending entry and fail the block
1316
+ * unless it already completed. Shared by the cleanup acknowledgement and by
1317
+ * Worker retirement, so the two paths cannot drift in their bookkeeping.
1318
+ */
1319
+ #settleOwedCleanup(key, event) {
1320
+ this.#pendingWorkerCleanups.delete(key);
1321
+ this.#pendingWorkerCleanupClients.delete(key);
1322
+ if (this.#completedBlocks.has(key)) return;
1323
+ const block = this.#parseBlockKey(key);
1324
+ this.#traceLifecycle(event, block.sbn, block.packetId, block.catalogTrackName);
1325
+ this.#failBlock(block.sbn, block.packetId, false, block.catalogTrackName);
1326
+ }
1327
+ /** Evict a disposed client under every stream key that still maps to it. */
1328
+ #evictDisposedWorker(client) {
1329
+ for (const [key, registered] of [...this.#workerClients]) {
1330
+ if (registered !== client) continue;
1331
+ const stream = this.#parseStreamKey(key);
1332
+ const track = stream.catalogTrackName === void 0 ? "" : ` track=${stream.catalogTrackName}`;
1333
+ console.warn(
1334
+ `[FECManager] packetId=${stream.packetId}${track} Worker decoder was disposed while still registered; evicting it`
1335
+ );
1336
+ this.#retireWorker(key, client, "disposed");
1337
+ }
1338
+ }
700
1339
  /** Called by player when framerate is known (from decoder output). Refines FEC block timeout. */
701
1340
  setFramerate(fps) {
702
- if (__privateGet(this, _fpsDetected) || fps <= 0) return;
703
- __privateSet(this, _fpsDetected, true);
704
- __privateSet(this, _fecFps, fps);
705
- if (__privateGet(this, _fecInterleaveDepthMs) >= MIN_INTERLEAVE_DEPTH_MS) {
706
- __privateSet(this, _fecTimeoutMs, computeFecDeliveryWindowMs({
707
- interleaveDepthMs: __privateGet(this, _fecInterleaveDepthMs),
708
- sourceSymbols: __privateGet(this, _fecK),
709
- symbolSize: __privateGet(this, _fecSymbolSize),
1341
+ if (this.#fpsDetected || fps <= 0) return;
1342
+ this.#fpsDetected = true;
1343
+ this.#fecFps = fps;
1344
+ if (this.#fecInterleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS) {
1345
+ this.#fecTimeoutMs = computeFecDeliveryWindowMs({
1346
+ interleaveDepthMs: this.#fecInterleaveDepthMs,
1347
+ sourceSymbols: this.#fecK,
1348
+ symbolSize: this.#fecSymbolSize,
710
1349
  mediaUnitsPerSecond: fps
711
- }));
1350
+ });
712
1351
  }
713
- for (const [packetId, config] of __privateGet(this, _trackConfigs)) {
1352
+ for (const [packetId, config] of this.#trackConfigs) {
714
1353
  if (config.fps !== void 0 || config.interleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS) continue;
715
- __privateGet(this, _trackConfigs).set(packetId, {
1354
+ this.#trackConfigs.set(packetId, {
716
1355
  ...config,
717
1356
  fps,
718
1357
  timeoutMs: Math.max(
719
- __privateGet(this, _fecTimeoutMs),
1358
+ this.#fecTimeoutMs,
720
1359
  computeFecDeliveryWindowMs({
721
1360
  interleaveDepthMs: config.interleaveDepthMs,
722
1361
  sourceSymbols: config.k,
@@ -741,16 +1380,16 @@ var FECManager = class {
741
1380
  * block completion state via `markBlockCompleted()`.
742
1381
  */
743
1382
  feedSourceSymbol(packetId, ssId, symbolData, alta, catalogTrackName) {
744
- __privateGet(this, _fecStats).sourcePackets++;
745
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).sourcePackets++;
746
- const fecData = __privateMethod(this, _FECManager_instances, normalizeSymbolData_fn).call(this, packetId, symbolData);
1383
+ this.#fecStats.sourcePackets++;
1384
+ this.#statsForPacket(packetId).sourcePackets++;
1385
+ const fecData = this.#normalizeSymbolData(packetId, symbolData);
747
1386
  const sbn = Math.floor(ssId / this.kForPacket(packetId));
748
- const blockKey = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
749
- const syncBlockOwner = __privateGet(this, _syncDecoderBlockOwners).get(blockKey);
750
- const workerClient = __privateMethod(this, _FECManager_instances, routableWorkerForPacket_fn).call(this, packetId, catalogTrackName);
1387
+ const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
1388
+ const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
1389
+ const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
751
1390
  if (workerClient && !syncBlockOwner) {
752
- if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, workerClient, sbn, catalogTrackName)) return null;
753
- const buf = fecData.buffer.slice(
1391
+ if (!this.#claimDecoderBlock(workerClient, sbn, catalogTrackName)) return null;
1392
+ const buf = fecData !== symbolData ? fecData.buffer : fecData.buffer.slice(
754
1393
  fecData.byteOffset,
755
1394
  fecData.byteOffset + fecData.byteLength
756
1395
  );
@@ -768,18 +1407,18 @@ var FECManager = class {
768
1407
  }
769
1408
  return null;
770
1409
  }
771
- const entry = __privateMethod(this, _FECManager_instances, decoderForPacket_fn).call(this, packetId, catalogTrackName);
1410
+ const entry = this.#decoderForPacket(packetId, catalogTrackName);
772
1411
  const client = syncBlockOwner ?? entry?.client;
773
1412
  if (!client) return null;
774
- if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, client, sbn, catalogTrackName)) return null;
775
- __privateGet(this, _syncDecoderBlockOwners).set(blockKey, client);
1413
+ if (!this.#claimDecoderBlock(client, sbn, catalogTrackName)) return null;
1414
+ this.#syncDecoderBlockOwners.set(blockKey, client);
776
1415
  let recovered = null;
777
1416
  try {
778
1417
  recovered = client.add_source(ssId, fecData, performance.now());
779
1418
  } catch {
780
1419
  }
781
- if (recovered || __privateGet(this, _completedBlocks).has(blockKey)) {
782
- __privateGet(this, _syncDecoderBlockOwners).delete(blockKey);
1420
+ if (recovered || this.#completedBlocks.has(blockKey)) {
1421
+ this.#syncDecoderBlockOwners.delete(blockKey);
783
1422
  }
784
1423
  return recovered;
785
1424
  }
@@ -791,12 +1430,12 @@ var FECManager = class {
791
1430
  * block completion state via `markBlockCompleted()`.
792
1431
  */
793
1432
  feedRepairSymbol(packetId, ssStart, ssbLength, rsId, repairData, catalogTrackName) {
794
- __privateGet(this, _fecStats).repairPackets++;
795
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).repairPackets++;
1433
+ this.#fecStats.repairPackets++;
1434
+ this.#statsForPacket(packetId).repairPackets++;
796
1435
  const symbolSize = this.symbolSizeForPacket(packetId);
797
1436
  if (symbolSize > 0 && repairData.byteLength !== symbolSize) {
798
- __privateWrapper(this, _repairSymbolSizeMismatchCount)._++;
799
- if (__privateGet(this, _repairSymbolSizeMismatchCount) <= 5 || __privateGet(this, _repairSymbolSizeMismatchCount) % 100 === 0) {
1437
+ this.#repairSymbolSizeMismatchCount++;
1438
+ if (this.#repairSymbolSizeMismatchCount <= 5 || this.#repairSymbolSizeMismatchCount % 100 === 0) {
800
1439
  console.warn(
801
1440
  `[FECManager] Dropping repair symbol with invalid size: got ${repairData.byteLength}B, expected ${symbolSize}B (packetId=${packetId}, ssStart=${ssStart}, ssbLength=${ssbLength}, rsId=${rsId})`
802
1441
  );
@@ -808,21 +1447,69 @@ var FECManager = class {
808
1447
  if (ssbLength <= 0 || ssbLength > k || ssStart % k !== 0) return null;
809
1448
  const sbn = Math.floor(ssStart / k);
810
1449
  this.noteBlockActivity(sbn, packetId, catalogTrackName);
811
- const blockKey = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
812
- if (__privateGet(this, _completedBlocks).has(blockKey)) return null;
813
- const syncBlockOwner = __privateGet(this, _syncDecoderBlockOwners).get(blockKey);
814
- let repairIds = __privateGet(this, _blockRepairRsIds).get(blockKey);
1450
+ const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
1451
+ if (this.#completedBlocks.has(blockKey)) return null;
1452
+ if (!this.#noteAuthoredLength(blockKey, sbn, packetId, ssbLength, catalogTrackName)) {
1453
+ return null;
1454
+ }
1455
+ let repairIds = this.#blockRepairRsIds.get(blockKey);
815
1456
  if (!repairIds) {
816
1457
  repairIds = /* @__PURE__ */ new Set();
817
- __privateGet(this, _blockRepairRsIds).set(blockKey, repairIds);
1458
+ this.#blockRepairRsIds.set(blockKey, repairIds);
818
1459
  }
819
1460
  repairIds.add(rsId);
820
- if (__privateGet(this, _repairRequestedBlocks).has(blockKey)) {
821
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "repair-arrived", sbn, packetId, catalogTrackName, rsId);
1461
+ if (this.#repairRequestedBlocks.has(blockKey)) {
1462
+ this.#traceLifecycle("repair-arrived", sbn, packetId, catalogTrackName, rsId);
822
1463
  }
823
- const workerClient = __privateMethod(this, _FECManager_instances, routableWorkerForPacket_fn).call(this, packetId, catalogTrackName);
1464
+ const cleanOnArrival = (this.#blockSourceCounts.get(blockKey) ?? 0) >= ssbLength;
1465
+ const recovered = this.#dispatchRepairSymbol(
1466
+ blockKey,
1467
+ sbn,
1468
+ packetId,
1469
+ ssStart,
1470
+ ssbLength,
1471
+ rsId,
1472
+ fecData,
1473
+ catalogTrackName
1474
+ );
1475
+ if (cleanOnArrival) {
1476
+ this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
1477
+ return null;
1478
+ }
1479
+ return recovered;
1480
+ }
1481
+ /**
1482
+ * Record a block's authored SSB_length from a repair symbol. Returns false,
1483
+ * leaving the block unchanged, when the symbol contradicts the block: a
1484
+ * different SSB_length than an earlier repair symbol declared is dropped,
1485
+ * and an SSB_length that places an already-received source ESI inside the
1486
+ * zero padding fails the block, since its geometry can no longer be trusted.
1487
+ */
1488
+ #noteAuthoredLength(blockKey, sbn, packetId, ssbLength, catalogTrackName) {
1489
+ const known = this.#blockAuthoredLengths.get(blockKey);
1490
+ if (known === ssbLength) return true;
1491
+ if (known !== void 0) {
1492
+ this.#ssbLengthConflictCount++;
1493
+ if (this.#ssbLengthConflictCount <= 5 || this.#ssbLengthConflictCount % 100 === 0) {
1494
+ console.warn(
1495
+ `[FECManager] Dropping repair symbol whose SSB_length ${ssbLength} conflicts with ${known} for packetId=${packetId} sbn=${sbn}`
1496
+ );
1497
+ }
1498
+ return false;
1499
+ }
1500
+ const sourceEsis = this.#blockSourceEsis.get(blockKey);
1501
+ if (sourceEsis && [...sourceEsis].some((esi) => esi >= ssbLength)) {
1502
+ this.#failBlock(sbn, packetId, false, catalogTrackName);
1503
+ return false;
1504
+ }
1505
+ this.#blockAuthoredLengths.set(blockKey, ssbLength);
1506
+ return true;
1507
+ }
1508
+ #dispatchRepairSymbol(blockKey, sbn, packetId, ssStart, ssbLength, rsId, fecData, catalogTrackName) {
1509
+ const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
1510
+ const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
824
1511
  if (workerClient && !syncBlockOwner) {
825
- if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, workerClient, sbn, catalogTrackName)) return null;
1512
+ if (!this.#claimDecoderBlock(workerClient, sbn, catalogTrackName)) return null;
826
1513
  const buf = fecData.buffer.slice(
827
1514
  fecData.byteOffset,
828
1515
  fecData.byteOffset + fecData.byteLength
@@ -830,38 +1517,74 @@ var FECManager = class {
830
1517
  workerClient.feedRepair(ssStart, ssbLength, rsId, buf, performance.now());
831
1518
  return null;
832
1519
  }
833
- const entry = __privateMethod(this, _FECManager_instances, decoderForPacket_fn).call(this, packetId, catalogTrackName);
1520
+ const entry = this.#decoderForPacket(packetId, catalogTrackName);
834
1521
  const client = syncBlockOwner ?? entry?.client;
835
1522
  if (!client) return null;
836
- if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, client, sbn, catalogTrackName)) return null;
837
- __privateGet(this, _syncDecoderBlockOwners).set(blockKey, client);
1523
+ if (!this.#claimDecoderBlock(client, sbn, catalogTrackName)) return null;
1524
+ this.#syncDecoderBlockOwners.set(blockKey, client);
838
1525
  let recovered = null;
839
1526
  try {
840
1527
  recovered = client.add_repair(ssStart, ssbLength, rsId, fecData, performance.now());
841
1528
  } catch {
842
1529
  }
843
- if (recovered) __privateGet(this, _syncDecoderBlockOwners).delete(blockKey);
1530
+ if (recovered) this.#syncDecoderBlockOwners.delete(blockKey);
844
1531
  return recovered;
845
1532
  }
1533
+ #routeSyncCleanup(decoder, sbn, packetId) {
1534
+ let framed;
1535
+ try {
1536
+ framed = decoder.cleanup_blocks_detailed(Uint32Array.of(sbn));
1537
+ } catch (error) {
1538
+ console.warn(`[FECManager] Scoped cleanup failed for SBN ${sbn}:`, error);
1539
+ return;
1540
+ }
1541
+ const view = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);
1542
+ let offset = 0;
1543
+ while (offset < framed.byteLength) {
1544
+ if (framed.byteLength - offset < 8) {
1545
+ console.warn(`[FECManager] Scoped cleanup returned a truncated record for SBN ${sbn}`);
1546
+ return;
1547
+ }
1548
+ const fillSbn = view.getUint32(offset, false);
1549
+ const length = view.getUint32(offset + 4, false);
1550
+ offset += 8;
1551
+ if (length > framed.byteLength - offset) {
1552
+ console.warn(`[FECManager] Scoped cleanup returned a truncated payload for SBN ${sbn}`);
1553
+ return;
1554
+ }
1555
+ const data = framed.slice(offset, offset + length).buffer;
1556
+ offset += length;
1557
+ this.#fecStats.greenFillFrames++;
1558
+ this.#statsForPacket(packetId).greenFillFrames++;
1559
+ this.onGreenFill?.(fillSbn, packetId, data);
1560
+ }
1561
+ }
846
1562
  // -----------------------------------------------------------------------
847
1563
  // Block lifecycle
848
1564
  // -----------------------------------------------------------------------
849
1565
  /**
850
1566
  * Track a source symbol for an FEC block. Refreshes the inactivity deadline
851
- * on each symbol and marks the block clean when K source symbols arrive.
1567
+ * on each symbol and marks the block clean when all of its authored source
1568
+ * symbols arrived: the SSB_length a repair symbol declared, otherwise K.
852
1569
  */
853
1570
  trackBlock(sbn, packetId, catalogTrackName, esi) {
854
- const key = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
855
- const trackConfig = __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId);
1571
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
1572
+ const trackConfig = this.#resolveTrackConfig(packetId);
856
1573
  const k = trackConfig.k;
857
- if (__privateGet(this, _completedBlocks).has(key)) return;
858
- const count = (__privateGet(this, _blockSourceCounts).get(key) ?? 0) + 1;
859
- __privateGet(this, _blockSourceCounts).set(key, count);
1574
+ if (this.#completedBlocks.has(key)) return;
1575
+ const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
1576
+ if (Number.isInteger(esi) && esi >= authoredLength) {
1577
+ this.#failBlock(sbn, packetId, false, catalogTrackName);
1578
+ return;
1579
+ }
1580
+ const count = (this.#blockSourceCounts.get(key) ?? 0) + 1;
1581
+ this.#blockSourceCounts.set(key, count);
1582
+ if (count === 1) this.#indexBlockKey(key, sbn, packetId);
860
1583
  if (Number.isInteger(esi) && esi >= 0 && esi < k) {
861
- let sourceEsis = __privateGet(this, _blockSourceEsis).get(key);
1584
+ let sourceEsis = this.#blockSourceEsis.get(key);
862
1585
  if (!sourceEsis) {
863
1586
  sourceEsis = /* @__PURE__ */ new Set();
864
- __privateGet(this, _blockSourceEsis).set(key, sourceEsis);
1587
+ this.#blockSourceEsis.set(key, sourceEsis);
865
1588
  }
866
1589
  sourceEsis.add(esi);
867
1590
  }
@@ -872,61 +1595,95 @@ var FECManager = class {
872
1595
  this.onBlockStarted?.(sbn, packetId, catalogTrackName);
873
1596
  }
874
1597
  }
875
- if (k > 0 && count >= k) {
876
- __privateGet(this, _fecStats).blocksClean++;
877
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).blocksClean++;
878
- this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
879
- __privateGet(this, _blockSourceCounts).delete(key);
880
- __privateGet(this, _blockSourceEsis).delete(key);
881
- __privateGet(this, _blockRepairRsIds).delete(key);
882
- __privateGet(this, _completedBlocks).add(key);
883
- __privateGet(this, _cleanlyCompletedBlocks).add(key);
884
- __privateMethod(this, _FECManager_instances, markPathBlockComplete_fn).call(this, sbn, packetId, catalogTrackName);
885
- if (catalogTrackName === void 0) {
886
- this.onBlockComplete?.(sbn, packetId);
887
- } else {
888
- this.onBlockComplete?.(sbn, packetId, catalogTrackName);
889
- }
890
- queueMicrotask(() => __privateGet(this, _syncDecoderBlockOwners).delete(key));
1598
+ if (k > 0 && count >= authoredLength) {
1599
+ this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
891
1600
  return;
892
1601
  }
893
1602
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
894
1603
  }
1604
+ #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
1605
+ this.#fecStats.blocksClean++;
1606
+ this.#statsForPacket(packetId).blocksClean++;
1607
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
1608
+ this.#blockSourceCounts.delete(key);
1609
+ this.#blockSourceEsis.delete(key);
1610
+ this.#blockAuthoredLengths.delete(key);
1611
+ this.#blockRepairRsIds.delete(key);
1612
+ this.#markTerminal(key, sbn, packetId, true);
1613
+ this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
1614
+ if (catalogTrackName === void 0) {
1615
+ this.onBlockComplete?.(sbn, packetId);
1616
+ } else {
1617
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
1618
+ }
1619
+ queueMicrotask(() => this.#syncDecoderBlockOwners.delete(key));
1620
+ }
895
1621
  /** Refresh deadlines after accepted block activity. */
896
1622
  noteBlockActivity(sbn, packetId, catalogTrackName, sourceProgress = false) {
897
- const key = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
898
- if (__privateGet(this, _completedBlocks).has(key)) return;
899
- if (__privateGet(this, _pendingWorkerCleanups).has(key)) return;
900
- if (__privateGet(this, _repairRequestedBlocks).has(key)) return;
901
- const trackConfig = __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId);
1623
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
1624
+ if (this.#completedBlocks.has(key)) return;
1625
+ if (this.#pendingWorkerCleanups.has(key)) return;
1626
+ if (this.#repairRequestedBlocks.has(key)) return;
1627
+ const trackConfig = this.#resolveTrackConfig(packetId);
902
1628
  const timeoutMs = trackConfig.timeoutMs;
903
1629
  if (timeoutMs <= 0) return;
904
- const repairDeadline = __privateGet(this, _repairDeadlines).get(key);
1630
+ const repairDeadline = this.#repairDeadlines.get(key);
905
1631
  if (this.onRepairNeeded && (repairDeadline === void 0 || sourceProgress)) {
906
- if (repairDeadline != null) clearTimeout(repairDeadline);
907
- __privateGet(this, _repairDeadlines).set(
1632
+ this.#armRepairDeadline(
908
1633
  key,
909
- setTimeout(() => {
910
- __privateMethod(this, _FECManager_instances, requestRepair_fn).call(this, sbn, packetId, catalogTrackName);
911
- }, __privateMethod(this, _FECManager_instances, repairDeadlineMs_fn).call(this, trackConfig))
1634
+ sbn,
1635
+ packetId,
1636
+ catalogTrackName,
1637
+ this.#repairDeadlineMs(trackConfig)
912
1638
  );
913
1639
  }
914
- __privateMethod(this, _FECManager_instances, armBlockTimeout_fn).call(this, sbn, packetId, catalogTrackName, timeoutMs);
1640
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
1641
+ }
1642
+ #failBlock(sbn, packetId, countGreenFill, catalogTrackName) {
1643
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
1644
+ this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
1645
+ this.#clearRepairDeadline(key);
1646
+ this.#clearBlockTimer(key);
1647
+ if (this.#repairRequestedBlocks.delete(key)) {
1648
+ if (catalogTrackName === void 0) {
1649
+ this.onRepairResolved?.(sbn, packetId, "failed");
1650
+ } else {
1651
+ this.onRepairResolved?.(sbn, packetId, "failed", catalogTrackName);
1652
+ }
1653
+ }
1654
+ this.#blockSourceCounts.delete(key);
1655
+ this.#blockSourceEsis.delete(key);
1656
+ this.#blockAuthoredLengths.delete(key);
1657
+ this.#blockRepairRsIds.delete(key);
1658
+ this.#syncDecoderBlockOwners.delete(key);
1659
+ this.#markTerminal(key, sbn, packetId, false);
1660
+ this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
1661
+ this.#fecStats.blocksFailed++;
1662
+ this.#statsForPacket(packetId).blocksFailed++;
1663
+ if (countGreenFill) {
1664
+ this.#fecStats.greenFillFrames++;
1665
+ this.#statsForPacket(packetId).greenFillFrames++;
1666
+ }
1667
+ if (catalogTrackName === void 0) {
1668
+ this.onBlockFailed?.(sbn, packetId);
1669
+ } else {
1670
+ this.onBlockFailed?.(sbn, packetId, catalogTrackName);
1671
+ }
915
1672
  }
916
1673
  /** Check whether a block has already been completed (clean or recovered). */
917
1674
  isBlockCompleted(sbn, packetId, catalogTrackName) {
918
- return __privateMethod(this, _FECManager_instances, blockKeysFor_fn).call(this, sbn, packetId, catalogTrackName).some((key) => __privateGet(this, _completedBlocks).has(key));
1675
+ return this.#blockKeysFor(sbn, packetId, catalogTrackName).some((key) => this.#completedBlocks.has(key));
919
1676
  }
920
1677
  /** Mark a block as completed externally (e.g., after routing recovered data). */
921
1678
  markBlockCompleted(sbn, packetId, catalogTrackName) {
922
- for (const key of __privateMethod(this, _FECManager_instances, blockKeysFor_fn).call(this, sbn, packetId, catalogTrackName)) {
923
- __privateGet(this, _completedBlocks).add(key);
924
- __privateGet(this, _pendingWorkerCleanups).delete(key);
925
- __privateGet(this, _pendingWorkerCleanupClients).delete(key);
926
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
927
- __privateMethod(this, _FECManager_instances, markPathBlockComplete_fn).call(this, block.sbn, block.packetId, block.catalogTrackName);
928
- __privateMethod(this, _FECManager_instances, clearRepairDeadline_fn).call(this, key);
929
- if (__privateGet(this, _repairRequestedBlocks).delete(key)) {
1679
+ for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
1680
+ const block = this.#parseBlockKey(key);
1681
+ this.#markTerminal(key, block.sbn, block.packetId, false);
1682
+ this.#pendingWorkerCleanups.delete(key);
1683
+ this.#pendingWorkerCleanupClients.delete(key);
1684
+ this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName);
1685
+ this.#clearRepairDeadline(key);
1686
+ if (this.#repairRequestedBlocks.delete(key)) {
930
1687
  if (block.catalogTrackName === void 0) {
931
1688
  this.onRepairResolved?.(block.sbn, block.packetId, "completed");
932
1689
  } else {
@@ -938,22 +1695,17 @@ var FECManager = class {
938
1695
  );
939
1696
  }
940
1697
  }
941
- __privateGet(this, _blockSourceCounts).delete(key);
942
- __privateGet(this, _blockSourceEsis).delete(key);
943
- __privateGet(this, _blockRepairRsIds).delete(key);
944
- const timer = __privateGet(this, _activeBlocks).get(key);
945
- if (timer) {
946
- clearTimeout(timer);
947
- __privateGet(this, _activeBlocks).delete(key);
948
- }
949
- __privateGet(this, _activeBlockDeadlinesMs).delete(key);
950
- __privateGet(this, _activeBlockTimeoutOwners).delete(key);
1698
+ this.#blockSourceCounts.delete(key);
1699
+ this.#blockSourceEsis.delete(key);
1700
+ this.#blockAuthoredLengths.delete(key);
1701
+ this.#blockRepairRsIds.delete(key);
1702
+ this.#clearBlockTimer(key);
951
1703
  }
952
1704
  }
953
1705
  /** Increment blocksRecovered stat (called by MmtpRouter after routing recovery). */
954
1706
  countRecovery(packetId) {
955
- __privateGet(this, _fecStats).blocksRecovered++;
956
- if (packetId != null) __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).blocksRecovered++;
1707
+ this.#fecStats.blocksRecovered++;
1708
+ if (packetId != null) this.#statsForPacket(packetId).blocksRecovered++;
957
1709
  }
958
1710
  /**
959
1711
  * Strict delivery provenance for one FEC block.
@@ -976,20 +1728,20 @@ var FECManager = class {
976
1728
  }
977
1729
  /** Per-path symbol counts for one block (D-28 gate logging), if tracked. */
978
1730
  blockPathCount(sbn, packetId, catalogTrackName) {
979
- return __privateGet(this, _blockPathCounts).get(
980
- __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName)
1731
+ return this.#blockPathCounts.get(
1732
+ this.#blockKey(sbn, packetId, catalogTrackName)
981
1733
  ) ?? null;
982
1734
  }
983
1735
  /** Cancel block timeout (block completed via clean reception or FEC recovery). */
984
1736
  cancelBlockTimeout(sbn, packetId, catalogTrackName) {
985
- for (const key of __privateMethod(this, _FECManager_instances, blockKeysFor_fn).call(this, sbn, packetId, catalogTrackName)) {
986
- __privateGet(this, _completedBlocks).add(key);
987
- __privateGet(this, _pendingWorkerCleanups).delete(key);
988
- __privateGet(this, _pendingWorkerCleanupClients).delete(key);
989
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
990
- __privateMethod(this, _FECManager_instances, markPathBlockComplete_fn).call(this, block.sbn, block.packetId, block.catalogTrackName);
991
- __privateMethod(this, _FECManager_instances, clearRepairDeadline_fn).call(this, key);
992
- if (__privateGet(this, _repairRequestedBlocks).delete(key)) {
1737
+ for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
1738
+ const block = this.#parseBlockKey(key);
1739
+ this.#markTerminal(key, block.sbn, block.packetId, false);
1740
+ this.#pendingWorkerCleanups.delete(key);
1741
+ this.#pendingWorkerCleanupClients.delete(key);
1742
+ this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName);
1743
+ this.#clearRepairDeadline(key);
1744
+ if (this.#repairRequestedBlocks.delete(key)) {
993
1745
  if (block.catalogTrackName === void 0) {
994
1746
  this.onRepairResolved?.(block.sbn, block.packetId, "completed");
995
1747
  } else {
@@ -1001,526 +1753,54 @@ var FECManager = class {
1001
1753
  );
1002
1754
  }
1003
1755
  }
1004
- __privateGet(this, _blockSourceCounts).delete(key);
1005
- __privateGet(this, _blockSourceEsis).delete(key);
1006
- __privateGet(this, _blockRepairRsIds).delete(key);
1007
- const timer = __privateGet(this, _activeBlocks).get(key);
1008
- if (timer) {
1009
- clearTimeout(timer);
1010
- __privateGet(this, _activeBlocks).delete(key);
1011
- }
1012
- __privateGet(this, _activeBlockDeadlinesMs).delete(key);
1013
- __privateGet(this, _activeBlockTimeoutOwners).delete(key);
1014
- }
1015
- if (__privateGet(this, _completedBlocks).size > 1e3) {
1016
- const iter = __privateGet(this, _completedBlocks).values();
1017
- for (let i = 0; i < 500; i++) iter.next();
1018
- const keep = /* @__PURE__ */ new Set();
1019
- for (const v of iter) keep.add(v);
1020
- __privateSet(this, _completedBlocks, keep);
1756
+ this.#blockSourceCounts.delete(key);
1757
+ this.#blockSourceEsis.delete(key);
1758
+ this.#blockAuthoredLengths.delete(key);
1759
+ this.#blockRepairRsIds.delete(key);
1760
+ this.#clearBlockTimer(key);
1021
1761
  }
1022
1762
  }
1023
1763
  // -----------------------------------------------------------------------
1024
1764
  // Cleanup
1025
1765
  // -----------------------------------------------------------------------
1026
1766
  dispose() {
1027
- for (const timer of __privateGet(this, _activeBlocks).values()) clearTimeout(timer);
1028
- __privateGet(this, _activeBlocks).clear();
1029
- __privateGet(this, _activeBlockDeadlinesMs).clear();
1030
- __privateGet(this, _activeBlockTimeoutOwners).clear();
1031
- __privateGet(this, _pendingWorkerCleanups).clear();
1032
- __privateGet(this, _pendingWorkerCleanupClients).clear();
1033
- for (const timer of __privateGet(this, _repairDeadlines).values()) {
1034
- if (timer != null) clearTimeout(timer);
1035
- }
1036
- __privateGet(this, _repairDeadlines).clear();
1037
- __privateGet(this, _blockSourceCounts).clear();
1038
- __privateGet(this, _blockSourceEsis).clear();
1039
- __privateGet(this, _blockRepairRsIds).clear();
1040
- __privateGet(this, _completedBlocks).clear();
1041
- __privateGet(this, _cleanlyCompletedBlocks).clear();
1042
- __privateGet(this, _repairRequestedBlocks).clear();
1043
- __privateGet(this, _workerRecoveredBlocks).clear();
1044
- __privateGet(this, _syncDecoderBlockOwners).clear();
1045
- __privateGet(this, _startupAlignedPackets).clear();
1046
- __privateGet(this, _startupPartialBlocks).clear();
1047
- __privateSet(this, _startupRequireRepairReady, false);
1048
- __privateGet(this, _startupRepairReadyPackets).clear();
1049
- __privateGet(this, _startupRepairBoundaryCounts).clear();
1050
- __privateGet(this, _startupRepairFailOpenPackets).clear();
1051
- __privateGet(this, _seenSymbols).clear();
1052
- __privateGet(this, _blockPathCounts).clear();
1053
- __privateGet(this, _blockCatalogTrackNames).clear();
1054
- __privateGet(this, _trackConfigs).clear();
1055
- __privateGet(this, _fecDecoders).clear();
1056
- for (const client of new Set(__privateGet(this, _workerClients).values())) client.dispose();
1057
- __privateGet(this, _workerClients).clear();
1058
- }
1059
- };
1060
- _fecDecoders = new WeakMap();
1061
- _workerClients = new WeakMap();
1062
- _syncDecoderBlockOwners = new WeakMap();
1063
- _decoderBlockOwners = new WeakMap();
1064
- _fecK = new WeakMap();
1065
- _fecSymbolSize = new WeakMap();
1066
- _fecTimeoutMs = new WeakMap();
1067
- _trackConfigs = new WeakMap();
1068
- _fecStats = new WeakMap();
1069
- _fecTrackStats = new WeakMap();
1070
- _fecWorkerStats = new WeakMap();
1071
- _fecStatsObservers = new WeakMap();
1072
- _activeBlocks = new WeakMap();
1073
- _activeBlockDeadlinesMs = new WeakMap();
1074
- _activeBlockTimeoutOwners = new WeakMap();
1075
- _lifecycleTrace = new WeakMap();
1076
- _pendingWorkerCleanups = new WeakMap();
1077
- _pendingWorkerCleanupClients = new WeakMap();
1078
- _blockSourceCounts = new WeakMap();
1079
- _blockSourceEsis = new WeakMap();
1080
- _blockRepairRsIds = new WeakMap();
1081
- _completedBlocks = new WeakMap();
1082
- _seenSymbols = new WeakMap();
1083
- _blockPathCounts = new WeakMap();
1084
- _blockCatalogTrackNames = new WeakMap();
1085
- _startupAlignedPackets = new WeakMap();
1086
- _startupPartialBlocks = new WeakMap();
1087
- _startupRequireRepairReady = new WeakMap();
1088
- _startupRepairReadyPackets = new WeakMap();
1089
- _startupRepairBoundaryCounts = new WeakMap();
1090
- _startupRepairFailOpenPackets = new WeakMap();
1091
- _cleanlyCompletedBlocks = new WeakMap();
1092
- _repairRequestedBlocks = new WeakMap();
1093
- _repairDeadlines = new WeakMap();
1094
- _workerRecoveredBlocks = new WeakMap();
1095
- _fpsDetected = new WeakMap();
1096
- _fecFps = new WeakMap();
1097
- _fecInterleaveDepthMs = new WeakMap();
1098
- _workerErrorCounts = new WeakMap();
1099
- _decoderUnavailableEvents = new WeakMap();
1100
- _repairSymbolSizeMismatchCount = new WeakMap();
1101
- _FECManager_instances = new WeakSet();
1102
- streamKey_fn = function(packetId, catalogTrackName) {
1103
- return catalogTrackName === void 0 ? `${packetId}` : `${packetId}:${encodeURIComponent(catalogTrackName)}`;
1104
- };
1105
- belongsToPacket_fn = function(key, packetId) {
1106
- return Number(key.split(":", 1)[0]) === packetId;
1107
- };
1108
- belongsToStream_fn = function(key, packetId, catalogTrackName) {
1109
- if (!__privateMethod(this, _FECManager_instances, belongsToPacket_fn).call(this, key, packetId)) return false;
1110
- const parts = key.split(":");
1111
- const encodedTrackName = encodeURIComponent(catalogTrackName);
1112
- if (parts.length === 2) return parts[1] === encodedTrackName;
1113
- if (parts.length >= 3) return parts[2] === encodedTrackName;
1114
- return false;
1115
- };
1116
- packetIdsForStreamKeys_fn = function(keys) {
1117
- return [...new Set([...keys].map((key) => Number(key.split(":", 1)[0])))];
1118
- };
1119
- parseStreamKey_fn = function(key) {
1120
- const separator = key.indexOf(":");
1121
- if (separator < 0) return { packetId: Number(key) || 0 };
1122
- return {
1123
- packetId: Number(key.slice(0, separator)) || 0,
1124
- catalogTrackName: decodeURIComponent(key.slice(separator + 1))
1125
- };
1126
- };
1127
- blockKey_fn = function(sbn, packetId, catalogTrackName) {
1128
- const base = `${packetId}:${sbn}`;
1129
- return catalogTrackName === void 0 ? base : `${base}:${encodeURIComponent(catalogTrackName)}`;
1130
- };
1131
- parseBlockKey_fn = function(key) {
1132
- const [packetIdText, sbnText, ...catalogParts] = key.split(":");
1133
- const catalogTrackName = catalogParts.length > 0 ? decodeURIComponent(catalogParts.join(":")) : void 0;
1134
- return {
1135
- packetId: Number(packetIdText) || 0,
1136
- sbn: Number(sbnText) || 0,
1137
- ...catalogTrackName === void 0 ? {} : { catalogTrackName }
1138
- };
1139
- };
1140
- decoderForPacket_fn = function(packetId, catalogTrackName) {
1141
- return __privateGet(this, _fecDecoders).get(__privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName)) ?? __privateGet(this, _fecDecoders).get(__privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId));
1142
- };
1143
- workerForPacket_fn = function(packetId, catalogTrackName) {
1144
- return __privateGet(this, _workerClients).get(__privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName)) ?? __privateGet(this, _workerClients).get(__privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId));
1145
- };
1146
- /**
1147
- * The stream's Worker client for routing, or undefined after evicting a
1148
- * registered client that was already disposed. A disposed client throws on
1149
- * every command, so it leaves routing here before a symbol reaches it and
1150
- * the stream reports its decoder unavailable instead.
1151
- */
1152
- routableWorkerForPacket_fn = function(packetId, catalogTrackName) {
1153
- const client = __privateMethod(this, _FECManager_instances, workerForPacket_fn).call(this, packetId, catalogTrackName);
1154
- if (client === void 0 || client.disposed !== true) return client;
1155
- __privateMethod(this, _FECManager_instances, evictDisposedWorker_fn).call(this, client);
1156
- return void 0;
1157
- };
1158
- claimDecoderBlock_fn = function(client, sbn, catalogTrackName) {
1159
- let blocks = __privateGet(this, _decoderBlockOwners).get(client);
1160
- if (!blocks) {
1161
- blocks = /* @__PURE__ */ new Map();
1162
- __privateGet(this, _decoderBlockOwners).set(client, blocks);
1163
- }
1164
- const owner = blocks.get(sbn);
1165
- if (!owner) {
1166
- blocks.set(sbn, { catalogTrackName, conflicted: false });
1167
- if (blocks.size > 512) {
1168
- const stale = [...blocks.keys()].slice(0, 256);
1169
- for (const key of stale) blocks.delete(key);
1170
- }
1171
- return true;
1172
- }
1173
- if (owner.conflicted) return false;
1174
- if (owner.catalogTrackName === catalogTrackName) return true;
1175
- owner.conflicted = true;
1176
- return false;
1177
- };
1178
- decoderBlockCatalogTrackName_fn = function(client, sbn) {
1179
- const owner = __privateGet(this, _decoderBlockOwners).get(client)?.get(sbn);
1180
- return owner?.conflicted ? void 0 : owner?.catalogTrackName;
1181
- };
1182
- resetDecoderBlockOwners_fn = function(client, catalogTrackName) {
1183
- const blocks = __privateGet(this, _decoderBlockOwners).get(client);
1184
- if (!blocks) return;
1185
- for (const [sbn, owner] of blocks) {
1186
- if (owner.catalogTrackName === catalogTrackName || owner.conflicted) {
1187
- blocks.delete(sbn);
1188
- }
1189
- }
1190
- if (blocks.size === 0) __privateGet(this, _decoderBlockOwners).delete(client);
1191
- };
1192
- discardFecDecoderClient_fn = function(client) {
1193
- for (const [key, entry] of __privateGet(this, _fecDecoders)) {
1194
- if (entry.client === client) __privateGet(this, _fecDecoders).delete(key);
1195
- }
1196
- __privateGet(this, _decoderBlockOwners).delete(client);
1197
- };
1198
- assertExclusiveDecoderClient_fn = function(streamKey, client, registrations, kind) {
1199
- for (const [registeredKey, registeredClient] of registrations) {
1200
- if (registeredClient !== client || registeredKey === streamKey) continue;
1201
- throw new Error(
1202
- `[FECManager] ${kind} client is already registered for stream ${registeredKey}; create one client per physical stream`
1203
- );
1204
- }
1205
- };
1206
- statsForPacket_fn = function(packetId) {
1207
- let stats = __privateGet(this, _fecTrackStats).get(packetId);
1208
- if (!stats) {
1209
- stats = newFecCounters();
1210
- __privateGet(this, _fecTrackStats).set(packetId, stats);
1211
- }
1212
- return stats;
1213
- };
1214
- markPathBlockComplete_fn = function(sbn, packetId, catalogTrackName) {
1215
- const block = __privateGet(this, _blockPathCounts).get(__privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName));
1216
- if (block) block.complete = true;
1217
- };
1218
- /** Cancel and forget a block's D-28 repair-deadline timer. */
1219
- clearRepairDeadline_fn = function(key) {
1220
- const timer = __privateGet(this, _repairDeadlines).get(key);
1221
- if (timer != null) clearTimeout(timer);
1222
- __privateGet(this, _repairDeadlines).delete(key);
1223
- };
1224
- requestRepair_fn = function(sbn, packetId, catalogTrackName) {
1225
- const key = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
1226
- if (__privateGet(this, _completedBlocks).has(key) || !this.onRepairNeeded || __privateGet(this, _repairRequestedBlocks).has(key)) return;
1227
- const deadline = __privateGet(this, _repairDeadlines).get(key);
1228
- if (deadline) clearTimeout(deadline);
1229
- __privateGet(this, _repairDeadlines).set(key, null);
1230
- __privateGet(this, _repairRequestedBlocks).add(key);
1231
- const config = __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId);
1232
- const graceMs = __privateMethod(this, _FECManager_instances, repairGraceMs_fn).call(this, config);
1233
- const now = performance.now();
1234
- const currentDeadline = __privateGet(this, _activeBlockDeadlinesMs).get(key) ?? now;
1235
- __privateMethod(this, _FECManager_instances, armBlockTimeout_fn).call(this, sbn, packetId, catalogTrackName, Math.max(1, Math.ceil(Math.max(now, currentDeadline) + graceMs - now)));
1236
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "repair-requested", sbn, packetId, catalogTrackName);
1237
- if (catalogTrackName === void 0) {
1238
- this.onRepairNeeded(sbn, packetId);
1239
- } else {
1240
- this.onRepairNeeded(sbn, packetId, catalogTrackName);
1241
- }
1242
- };
1243
- traceLifecycle_fn = function(event, sbn, packetId, catalogTrackName, rsId) {
1244
- const key = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
1245
- const deadline = __privateGet(this, _activeBlockDeadlinesMs).get(key);
1246
- const decoderPath = __privateGet(this, _syncDecoderBlockOwners).has(key) ? "sync" : __privateMethod(this, _FECManager_instances, workerForPacket_fn).call(this, packetId, catalogTrackName) ? "worker" : __privateMethod(this, _FECManager_instances, decoderForPacket_fn).call(this, packetId, catalogTrackName) ? "sync" : "none";
1247
- __privateGet(this, _lifecycleTrace).push({
1248
- atMs: Date.now(),
1249
- event,
1250
- packetId,
1251
- sbn,
1252
- ...catalogTrackName === void 0 ? {} : { catalogTrackName },
1253
- sourceCount: __privateGet(this, _blockSourceCounts).get(key) ?? 0,
1254
- sourceEsis: [...__privateGet(this, _blockSourceEsis).get(key) ?? []].sort((a, b) => a - b),
1255
- repairRsIds: [...__privateGet(this, _blockRepairRsIds).get(key) ?? []].sort((a, b) => a - b),
1256
- decoderPath,
1257
- ...deadline === void 0 ? {} : { deadlineRemainingMs: Math.max(0, deadline - performance.now()) },
1258
- pendingCleanup: __privateGet(this, _pendingWorkerCleanups).has(key),
1259
- ...rsId === void 0 ? {} : { rsId }
1260
- });
1261
- if (__privateGet(this, _lifecycleTrace).length > 64) __privateGet(this, _lifecycleTrace).splice(0, 32);
1262
- };
1263
- defaultTrackConfig_fn = function() {
1264
- return {
1265
- k: __privateGet(this, _fecK),
1266
- symbolSize: __privateGet(this, _fecSymbolSize),
1267
- interleaveDepthMs: __privateGet(this, _fecInterleaveDepthMs),
1268
- fps: __privateGet(this, _fecFps),
1269
- timeoutMs: __privateGet(this, _fecTimeoutMs)
1270
- };
1271
- };
1272
- resolveTrackConfig_fn = function(packetId) {
1273
- return __privateGet(this, _trackConfigs).get(packetId) ?? __privateMethod(this, _FECManager_instances, defaultTrackConfig_fn).call(this);
1274
- };
1275
- computeTimeout_fn = function(config) {
1276
- if (config.timeoutMs && config.timeoutMs > 0) return config.timeoutMs;
1277
- if (config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS) {
1278
- return Math.max(
1279
- __privateGet(this, _fecTimeoutMs),
1280
- computeFecDeliveryWindowMs({
1281
- interleaveDepthMs: config.interleaveDepthMs,
1282
- sourceSymbols: config.k,
1283
- mediaUnitsPerSecond: config.fps
1284
- })
1285
- );
1286
- }
1287
- return __privateGet(this, _fecTimeoutMs);
1288
- };
1289
- repairDeadlineMs_fn = function(config) {
1290
- const halfFailBoundMs = Math.ceil(config.timeoutMs / 2);
1291
- if (config.k > 0 && config.interleaveDepthMs >= MIN_INTERLEAVE_DEPTH_MS && config.fps !== void 0 && Number.isFinite(config.fps) && config.fps > 0) {
1292
- const mediaUnitMs = 1e3 / config.fps;
1293
- const interleaveUnits = deriveFecInterleaveDepth(
1294
- config.interleaveDepthMs,
1295
- mediaUnitMs
1296
- );
1297
- const sourceHorizonMs = Math.ceil(config.k * interleaveUnits * mediaUnitMs);
1298
- if (sourceHorizonMs < config.timeoutMs) return sourceHorizonMs;
1299
- }
1300
- return halfFailBoundMs;
1301
- };
1302
- repairGraceMs_fn = function(config) {
1303
- return Math.max(1, config.timeoutMs - __privateMethod(this, _FECManager_instances, repairDeadlineMs_fn).call(this, config));
1304
- };
1305
- armBlockTimeout_fn = function(sbn, packetId, catalogTrackName, delayMs) {
1306
- const key = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
1307
- const current = __privateGet(this, _activeBlocks).get(key);
1308
- if (current) clearTimeout(current);
1309
- const boundedDelayMs = Math.max(1, Math.ceil(delayMs));
1310
- __privateGet(this, _activeBlockDeadlinesMs).set(key, performance.now() + boundedDelayMs);
1311
- const owner = {};
1312
- __privateGet(this, _activeBlockTimeoutOwners).set(key, owner);
1313
- const timer = setTimeout(() => {
1314
- if (__privateGet(this, _activeBlockTimeoutOwners).get(key) !== owner) return;
1315
- __privateGet(this, _activeBlocks).delete(key);
1316
- __privateGet(this, _activeBlockDeadlinesMs).delete(key);
1317
- __privateGet(this, _activeBlockTimeoutOwners).delete(key);
1318
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "timeout-queued", sbn, packetId, catalogTrackName);
1319
- const syncOwner = __privateGet(this, _syncDecoderBlockOwners).get(key);
1320
- if (syncOwner) {
1321
- __privateMethod(this, _FECManager_instances, routeSyncCleanup_fn).call(this, syncOwner, sbn, packetId);
1322
- __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, sbn, packetId, false, catalogTrackName);
1323
- return;
1324
- }
1325
- const workerClient = __privateMethod(this, _FECManager_instances, routableWorkerForPacket_fn).call(this, packetId, catalogTrackName);
1326
- if (workerClient) {
1327
- __privateGet(this, _pendingWorkerCleanups).add(key);
1328
- __privateGet(this, _pendingWorkerCleanupClients).set(key, workerClient);
1329
- workerClient.cleanup(sbn);
1330
- } else {
1331
- const decoder = __privateMethod(this, _FECManager_instances, decoderForPacket_fn).call(this, packetId, catalogTrackName)?.client;
1332
- if (decoder) {
1333
- __privateMethod(this, _FECManager_instances, routeSyncCleanup_fn).call(this, decoder, sbn, packetId);
1334
- __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, sbn, packetId, false, catalogTrackName);
1335
- } else {
1336
- __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, sbn, packetId, false, catalogTrackName);
1337
- }
1338
- }
1339
- }, boundedDelayMs);
1340
- __privateGet(this, _activeBlocks).set(key, timer);
1341
- };
1342
- upsertTrackConfig_fn = function(packetId, config) {
1343
- const previous = __privateGet(this, _trackConfigs).get(packetId) ?? __privateMethod(this, _FECManager_instances, defaultTrackConfig_fn).call(this);
1344
- const timingChanged = config.k !== void 0 || config.interleaveDepthMs !== void 0 || config.fps !== void 0;
1345
- const next = {
1346
- k: config.k ?? previous.k,
1347
- symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previous.symbolSize,
1348
- interleaveDepthMs: config.interleaveDepthMs ?? previous.interleaveDepthMs,
1349
- fps: config.fps ?? previous.fps,
1350
- timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs)
1351
- };
1352
- next.timeoutMs = __privateMethod(this, _FECManager_instances, computeTimeout_fn).call(this, next);
1353
- __privateGet(this, _trackConfigs).set(packetId, next);
1354
- return next;
1355
- };
1356
- normalizeSymbolData_fn = function(packetId, data) {
1357
- const symbolSize = this.symbolSizeForPacket(packetId);
1358
- if (symbolSize <= 0 || data.byteLength === symbolSize) return data;
1359
- const normalized = new Uint8Array(symbolSize);
1360
- normalized.set(data.subarray(0, symbolSize));
1361
- return normalized;
1362
- };
1363
- blockKeysFor_fn = function(sbn, packetId, catalogTrackName) {
1364
- if (packetId != null && catalogTrackName !== void 0) {
1365
- return [__privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName)];
1366
- }
1367
- const keys = /* @__PURE__ */ new Set();
1368
- for (const source of [
1369
- __privateGet(this, _activeBlocks),
1370
- __privateGet(this, _blockSourceCounts),
1371
- __privateGet(this, _blockCatalogTrackNames)
1372
- ]) {
1373
- for (const key of source.keys()) {
1374
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
1375
- if (block.sbn === sbn && (packetId === void 0 || block.packetId === packetId)) keys.add(key);
1767
+ for (const timer of this.#activeBlocks.values()) {
1768
+ if (timer.handle != null) clearTimeout(timer.handle);
1376
1769
  }
1377
- }
1378
- for (const source of [__privateGet(this, _completedBlocks), __privateGet(this, _cleanlyCompletedBlocks)]) {
1379
- for (const key of source) {
1380
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
1381
- if (block.sbn === sbn && (packetId === void 0 || block.packetId === packetId)) keys.add(key);
1770
+ this.#activeBlocks.clear();
1771
+ this.#activeBlockDeadlinesMs.clear();
1772
+ this.#pendingWorkerCleanups.clear();
1773
+ this.#pendingWorkerCleanupClients.clear();
1774
+ for (const timer of this.#repairDeadlines.values()) {
1775
+ if (timer?.handle != null) clearTimeout(timer.handle);
1382
1776
  }
1383
- }
1384
- if (packetId !== void 0) {
1385
- if (keys.size === 0) return [__privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId)];
1386
- return keys.size === 1 ? [...keys] : [];
1387
- }
1388
- return keys.size > 0 ? [...keys] : [__privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, 0, catalogTrackName)];
1389
- };
1390
- observeBlockCatalogTrackName_fn = function(blockKey, catalogTrackName) {
1391
- if (catalogTrackName === void 0) return;
1392
- if (!__privateGet(this, _blockCatalogTrackNames).has(blockKey)) {
1393
- __privateGet(this, _blockCatalogTrackNames).set(blockKey, catalogTrackName);
1394
- return;
1395
- }
1396
- if (__privateGet(this, _blockCatalogTrackNames).get(blockKey) !== catalogTrackName) {
1397
- __privateGet(this, _blockCatalogTrackNames).set(blockKey, null);
1398
- }
1399
- };
1400
- markStartupPartial_fn = function(blockKey) {
1401
- __privateGet(this, _startupPartialBlocks).add(blockKey);
1402
- if (__privateGet(this, _startupPartialBlocks).size > 128) {
1403
- __privateSet(this, _startupPartialBlocks, new Set(
1404
- Array.from(__privateGet(this, _startupPartialBlocks)).slice(-64)
1405
- ));
1406
- }
1407
- };
1408
- /**
1409
- * Take a Worker client out of routing under one stream key, fail the blocks
1410
- * whose completion it still owed, and report the stream's decoder
1411
- * unavailable together with whatever still decodes the stream.
1412
- */
1413
- retireWorker_fn = function(streamKey, client, reason) {
1414
- __privateGet(this, _workerClients).delete(streamKey);
1415
- __privateMethod(this, _FECManager_instances, releaseWorkerClient_fn).call(this, client);
1416
- __privateWrapper(this, _decoderUnavailableEvents)._++;
1417
- const stream = __privateMethod(this, _FECManager_instances, parseStreamKey_fn).call(this, streamKey);
1418
- const fallbackDecoder = __privateMethod(this, _FECManager_instances, decoderForPacket_fn).call(this, stream.packetId, stream.catalogTrackName) ? "sync" : "none";
1419
- this.onDecoderUnavailable?.({
1420
- packetId: stream.packetId,
1421
- ...stream.catalogTrackName === void 0 ? {} : { catalogTrackName: stream.catalogTrackName },
1422
- reason,
1423
- fallbackDecoder
1424
- });
1425
- };
1426
- /**
1427
- * Fail every block whose Worker cleanup acknowledgement is owed by `client`
1428
- * and drop its block ownership, so no block waits on a message the Worker
1429
- * will never post.
1430
- */
1431
- releaseWorkerClient_fn = function(client) {
1432
- const owed = [...__privateGet(this, _pendingWorkerCleanupClients)].filter(([, owner]) => owner === client).map(([key]) => key);
1433
- for (const key of owed) __privateMethod(this, _FECManager_instances, settleOwedCleanup_fn).call(this, key, "decoder-unavailable");
1434
- __privateGet(this, _decoderBlockOwners).delete(client);
1435
- };
1436
- /**
1437
- * Resolve one owed Worker cleanup: drop the pending entry and fail the block
1438
- * unless it already completed. Shared by the cleanup acknowledgement and by
1439
- * Worker retirement, so the two paths cannot drift in their bookkeeping.
1440
- */
1441
- settleOwedCleanup_fn = function(key, event) {
1442
- __privateGet(this, _pendingWorkerCleanups).delete(key);
1443
- __privateGet(this, _pendingWorkerCleanupClients).delete(key);
1444
- if (__privateGet(this, _completedBlocks).has(key)) return;
1445
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
1446
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, event, block.sbn, block.packetId, block.catalogTrackName);
1447
- __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, block.sbn, block.packetId, false, block.catalogTrackName);
1448
- };
1449
- /** Evict a disposed client under every stream key that still maps to it. */
1450
- evictDisposedWorker_fn = function(client) {
1451
- for (const [key, registered] of [...__privateGet(this, _workerClients)]) {
1452
- if (registered !== client) continue;
1453
- const stream = __privateMethod(this, _FECManager_instances, parseStreamKey_fn).call(this, key);
1454
- const track = stream.catalogTrackName === void 0 ? "" : ` track=${stream.catalogTrackName}`;
1455
- console.warn(
1456
- `[FECManager] packetId=${stream.packetId}${track} Worker decoder was disposed while still registered; evicting it`
1457
- );
1458
- __privateMethod(this, _FECManager_instances, retireWorker_fn).call(this, key, client, "disposed");
1459
- }
1460
- };
1461
- routeSyncCleanup_fn = function(decoder, sbn, packetId) {
1462
- let framed;
1463
- try {
1464
- framed = decoder.cleanup_blocks_detailed(Uint32Array.of(sbn));
1465
- } catch (error) {
1466
- console.warn(`[FECManager] Scoped cleanup failed for SBN ${sbn}:`, error);
1467
- return;
1468
- }
1469
- const view = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);
1470
- let offset = 0;
1471
- while (offset < framed.byteLength) {
1472
- if (framed.byteLength - offset < 8) {
1473
- console.warn(`[FECManager] Scoped cleanup returned a truncated record for SBN ${sbn}`);
1474
- return;
1475
- }
1476
- const fillSbn = view.getUint32(offset, false);
1477
- const length = view.getUint32(offset + 4, false);
1478
- offset += 8;
1479
- if (length > framed.byteLength - offset) {
1480
- console.warn(`[FECManager] Scoped cleanup returned a truncated payload for SBN ${sbn}`);
1481
- return;
1482
- }
1483
- const data = framed.slice(offset, offset + length).buffer;
1484
- offset += length;
1485
- __privateGet(this, _fecStats).greenFillFrames++;
1486
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).greenFillFrames++;
1487
- this.onGreenFill?.(fillSbn, packetId, data);
1488
- }
1489
- };
1490
- failBlock_fn = function(sbn, packetId, countGreenFill, catalogTrackName) {
1491
- const key = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
1492
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "failed", sbn, packetId, catalogTrackName);
1493
- __privateMethod(this, _FECManager_instances, clearRepairDeadline_fn).call(this, key);
1494
- const activeTimer = __privateGet(this, _activeBlocks).get(key);
1495
- if (activeTimer) {
1496
- clearTimeout(activeTimer);
1497
- __privateGet(this, _activeBlocks).delete(key);
1498
- }
1499
- __privateGet(this, _activeBlockDeadlinesMs).delete(key);
1500
- if (__privateGet(this, _repairRequestedBlocks).delete(key)) {
1501
- if (catalogTrackName === void 0) {
1502
- this.onRepairResolved?.(sbn, packetId, "failed");
1503
- } else {
1504
- this.onRepairResolved?.(sbn, packetId, "failed", catalogTrackName);
1505
- }
1506
- }
1507
- __privateGet(this, _blockSourceCounts).delete(key);
1508
- __privateGet(this, _blockSourceEsis).delete(key);
1509
- __privateGet(this, _blockRepairRsIds).delete(key);
1510
- __privateGet(this, _activeBlockTimeoutOwners).delete(key);
1511
- __privateGet(this, _syncDecoderBlockOwners).delete(key);
1512
- __privateGet(this, _completedBlocks).add(key);
1513
- __privateMethod(this, _FECManager_instances, markPathBlockComplete_fn).call(this, sbn, packetId, catalogTrackName);
1514
- __privateGet(this, _fecStats).blocksFailed++;
1515
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).blocksFailed++;
1516
- if (countGreenFill) {
1517
- __privateGet(this, _fecStats).greenFillFrames++;
1518
- __privateMethod(this, _FECManager_instances, statsForPacket_fn).call(this, packetId).greenFillFrames++;
1519
- }
1520
- if (catalogTrackName === void 0) {
1521
- this.onBlockFailed?.(sbn, packetId);
1522
- } else {
1523
- this.onBlockFailed?.(sbn, packetId, catalogTrackName);
1777
+ this.#repairDeadlines.clear();
1778
+ this.#repairDeadlineAtMs.clear();
1779
+ this.#terminalExpiryMs.clear();
1780
+ this.#terminalQueues.clear();
1781
+ this.#blockKeysBySbn.clear();
1782
+ this.#blockSourceCounts.clear();
1783
+ this.#blockSourceEsis.clear();
1784
+ this.#blockAuthoredLengths.clear();
1785
+ this.#blockRepairRsIds.clear();
1786
+ this.#completedBlocks.clear();
1787
+ this.#cleanlyCompletedBlocks.clear();
1788
+ this.#repairRequestedBlocks.clear();
1789
+ this.#workerRecoveredBlocks.clear();
1790
+ this.#syncDecoderBlockOwners.clear();
1791
+ this.#startupAlignedPackets.clear();
1792
+ this.#startupPartialBlocks.clear();
1793
+ this.#startupRequireRepairReady = false;
1794
+ this.#startupRepairReadyPackets.clear();
1795
+ this.#startupRepairBoundaryCounts.clear();
1796
+ this.#startupRepairFailOpenPackets.clear();
1797
+ this.#seenSymbols.clear();
1798
+ this.#blockPathCounts.clear();
1799
+ this.#blockCatalogTrackNames.clear();
1800
+ this.#trackConfigs.clear();
1801
+ this.#fecDecoders.clear();
1802
+ for (const client of new Set(this.#workerClients.values())) client.dispose();
1803
+ this.#workerClients.clear();
1524
1804
  }
1525
1805
  };
1526
1806
  export {