@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
@@ -185,6 +185,69 @@ function newFecCounters(): MutableFecCounters {
185
185
  }
186
186
  }
187
187
 
188
+ /**
189
+ * The one timer armed for a block deadline (BLO-36599).
190
+ *
191
+ * Symbols move a block's deadline later many times per block. Re-arming a
192
+ * browser timer for each of them cost ~41 us per clear+set pair on a Kirin 659,
193
+ * so the deadline itself is stored as a performance.now() timestamp and this
194
+ * timer only guarantees a wake-up no later than it. When the timer fires it
195
+ * re-checks the stored deadline and re-arms for the remainder if activity
196
+ * moved it. `fireAtMs` is what the armed timer was scheduled for; `handle` is
197
+ * null once it fired without re-arming.
198
+ */
199
+ interface DeadlineTimer {
200
+ handle: ReturnType<typeof setTimeout> | null
201
+ fireAtMs: number
202
+ }
203
+
204
+ /**
205
+ * Delete the `count` oldest (first-inserted) keys of `collection` in place
206
+ * and return them.
207
+ */
208
+ function dropOldest(
209
+ collection: Set<string> | Map<string, unknown>,
210
+ count: number,
211
+ ): string[] {
212
+ const dropped: string[] = []
213
+ for (const key of collection.keys()) {
214
+ if (dropped.length >= count) break
215
+ dropped.push(key)
216
+ }
217
+ for (const key of dropped) collection.delete(key)
218
+ return dropped
219
+ }
220
+
221
+ /** A block key whose terminal state expires at `expiresAtMs`. */
222
+ interface TerminalRecord {
223
+ readonly key: string
224
+ readonly expiresAtMs: number
225
+ }
226
+
227
+ /** FIFO of terminal records in the order blocks became terminal. */
228
+ class TerminalQueue {
229
+ #records: TerminalRecord[] = []
230
+ #head = 0
231
+
232
+ push(record: TerminalRecord): void {
233
+ this.#records.push(record)
234
+ }
235
+
236
+ peek(): TerminalRecord | undefined {
237
+ return this.#records[this.#head]
238
+ }
239
+
240
+ shift(): void {
241
+ this.#head++
242
+ // Compact once the consumed prefix outweighs the live tail, so the array
243
+ // never holds more than twice the records still in the window.
244
+ if (this.#head * 2 >= this.#records.length) {
245
+ this.#records = this.#records.slice(this.#head)
246
+ this.#head = 0
247
+ }
248
+ }
249
+ }
250
+
188
251
  // ---------------------------------------------------------------------------
189
252
  // FECManager
190
253
  // ---------------------------------------------------------------------------
@@ -239,12 +302,12 @@ export class FECManager {
239
302
  #fecWorkerStats = new Map<number, FecTrackStats>()
240
303
  #fecStatsObservers = new Set<(packetId: number, stats: FecTrackStats) => void>()
241
304
 
242
- // Block inactivity tracking: (packetId, SBN) -> timer. The deadline is
243
- // derived from catalog geometry and refreshed on progress; only an idle
244
- // block fails.
245
- #activeBlocks = new Map<string, ReturnType<typeof setTimeout>>()
305
+ // Block inactivity tracking: (packetId, SBN) -> the one armed timer. The
306
+ // deadline is derived from catalog geometry and refreshed on progress; only
307
+ // an idle block fails. #activeBlockDeadlinesMs is the authoritative
308
+ // deadline; the timer re-checks it when it fires (see DeadlineTimer).
309
+ #activeBlocks = new Map<string, DeadlineTimer>()
246
310
  #activeBlockDeadlinesMs = new Map<string, number>()
247
- #activeBlockTimeoutOwners = new Map<string, object>()
248
311
  #lifecycleTrace: FecLifecycleTrace[] = []
249
312
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
250
313
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -253,11 +316,46 @@ export class FECManager {
253
316
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
254
317
  #blockSourceCounts = new Map<string, number>()
255
318
  #blockSourceEsis = new Map<string, Set<number>>()
319
+ // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
320
+ // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
321
+ // media units, usually before it holds K symbols, and fec-raptorq
322
+ // force_complete() encodes it as a K-symbol RaptorQ block whose ESIs
323
+ // SSB_length..K-1 are zero padding that is never sent. Such a block is clean
324
+ // at SSB_length source arrivals and recoverable from SSB_length received
325
+ // symbols; waiting for K fails every one of them.
326
+ #blockAuthoredLengths = new Map<string, number>()
327
+ #ssbLengthConflictCount = 0
256
328
  #blockRepairRsIds = new Map<string, Set<number>>()
257
329
  // Blocks already recovered — prevents late source symbols from restarting timeouts.
258
330
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
259
331
  // which would falsely start new timeouts without this guard.
332
+ //
333
+ // Every insertion goes through #markTerminal, which retires the key one
334
+ // catalog-derived block lifetime later (terminalRetentionMsForPacket). The
335
+ // previous bound (trim to 500 at 1000) lived in cancelBlockTimeout alone, so
336
+ // a stream whose blocks only failed grew this set without limit (BLO-36599).
260
337
  #completedBlocks = new Set<string>()
338
+ #terminalExpiryMs = new Map<string, number>()
339
+ #terminalQueues = new Map<number, TerminalQueue>()
340
+ // sbn -> (block key -> packetId) for every key held by #activeBlocks,
341
+ // #blockSourceCounts, #blockCatalogTrackNames or #completedBlocks. A lookup
342
+ // without a catalog name used to string-parse every key of all of those on
343
+ // each source packet, which is O(retained blocks) per packet (BLO-36599).
344
+ #blockKeysBySbn = new Map<number, Map<string, number>>()
345
+ // Stable per-name encodings for stream and block keys, bounded by the
346
+ // catalog's track names; #blockKey is built several times per packet.
347
+ #encodedTrackNames = new Map<string, string>()
348
+ // The last block and stream key built. One packet asks for the same block's
349
+ // key from every FECManager entry point it passes through (~6 per source
350
+ // symbol), so each key is built once per packet rather than once per call
351
+ // (BLO-36599). Both keys are pure functions of their arguments.
352
+ #lastBlockKeySbn = -1
353
+ #lastBlockKeyPacketId = -1
354
+ #lastBlockKeyTrackName: string | undefined = undefined
355
+ #lastBlockKey = ''
356
+ #lastStreamKeyPacketId = -1
357
+ #lastStreamKeyTrackName: string | undefined = undefined
358
+ #lastStreamKey = ''
261
359
  #seenSymbols = new Set<string>()
262
360
  #blockPathCounts = new Map<string, FecBlockPathCount>()
263
361
  // Exact catalog identity observed on accepted symbols for each FEC block.
@@ -295,12 +393,15 @@ export class FECManager {
295
393
  // one repair request per block; entries are removed when the block
296
394
  // completes, recovers, or fails.
297
395
  #repairRequestedBlocks = new Set<string>()
298
- // D-28: repair-deadline timers refreshed by accepted source progress until
299
- // the first repair request. A `null` value marks a deadline that already
300
- // fired (never re-armed). At most K accepted source symbols can refresh the
301
- // horizon, so browser scheduling delay cannot create an early loss signal
302
- // and repair traffic cannot keep a block alive indefinitely.
303
- #repairDeadlines = new Map<string, ReturnType<typeof setTimeout> | null>()
396
+ // D-28: repair deadlines refreshed by accepted source progress until the
397
+ // first repair request. A `null` value marks a deadline that already fired
398
+ // and requested repair (never re-armed). At most K accepted source symbols
399
+ // can refresh the horizon, so browser scheduling delay cannot create an
400
+ // early loss signal and repair traffic cannot keep a block alive
401
+ // indefinitely. #repairDeadlineAtMs is the authoritative deadline; the one
402
+ // armed timer re-checks it when it fires (see DeadlineTimer).
403
+ #repairDeadlines = new Map<string, DeadlineTimer | null>()
404
+ #repairDeadlineAtMs = new Map<string, number>()
304
405
  // Worker recovery emits all K source symbols. Track recovery once per block
305
406
  // while routing only ESI slots that were absent from the direct source path.
306
407
  #workerRecoveredBlocks = new Set<string>()
@@ -374,10 +475,29 @@ export class FECManager {
374
475
  onFecStatsUpdate: ((packetId: number, stats: FecTrackStats) => void) | null = null
375
476
  onGreenFill: ((sbn: number, packetId: number, data: ArrayBuffer) => void) | null = null
376
477
 
478
+ #encodeTrackName(catalogTrackName: string): string {
479
+ let encoded = this.#encodedTrackNames.get(catalogTrackName)
480
+ if (encoded === undefined) {
481
+ encoded = encodeURIComponent(catalogTrackName)
482
+ this.#encodedTrackNames.set(catalogTrackName, encoded)
483
+ }
484
+ return encoded
485
+ }
486
+
377
487
  #streamKey(packetId: number, catalogTrackName?: string): string {
378
- return catalogTrackName === undefined
488
+ if (
489
+ packetId === this.#lastStreamKeyPacketId &&
490
+ catalogTrackName === this.#lastStreamKeyTrackName
491
+ ) {
492
+ return this.#lastStreamKey
493
+ }
494
+ const key = catalogTrackName === undefined
379
495
  ? `${packetId}`
380
- : `${packetId}:${encodeURIComponent(catalogTrackName)}`
496
+ : `${packetId}:${this.#encodeTrackName(catalogTrackName)}`
497
+ this.#lastStreamKeyPacketId = packetId
498
+ this.#lastStreamKeyTrackName = catalogTrackName
499
+ this.#lastStreamKey = key
500
+ return key
381
501
  }
382
502
 
383
503
  #belongsToPacket(key: string, packetId: number): boolean {
@@ -387,7 +507,7 @@ export class FECManager {
387
507
  #belongsToStream(key: string, packetId: number, catalogTrackName: string): boolean {
388
508
  if (!this.#belongsToPacket(key, packetId)) return false
389
509
  const parts = key.split(':')
390
- const encodedTrackName = encodeURIComponent(catalogTrackName)
510
+ const encodedTrackName = this.#encodeTrackName(catalogTrackName)
391
511
  if (parts.length === 2) return parts[1] === encodedTrackName
392
512
  if (parts.length >= 3) return parts[2] === encodedTrackName
393
513
  return false
@@ -407,10 +527,98 @@ export class FECManager {
407
527
  }
408
528
 
409
529
  #blockKey(sbn: number, packetId: number, catalogTrackName?: string): string {
530
+ if (
531
+ sbn === this.#lastBlockKeySbn &&
532
+ packetId === this.#lastBlockKeyPacketId &&
533
+ catalogTrackName === this.#lastBlockKeyTrackName
534
+ ) {
535
+ return this.#lastBlockKey
536
+ }
410
537
  const base = `${packetId}:${sbn}`
411
- return catalogTrackName === undefined
538
+ const key = catalogTrackName === undefined
412
539
  ? base
413
- : `${base}:${encodeURIComponent(catalogTrackName)}`
540
+ : `${base}:${this.#encodeTrackName(catalogTrackName)}`
541
+ this.#lastBlockKeySbn = sbn
542
+ this.#lastBlockKeyPacketId = packetId
543
+ this.#lastBlockKeyTrackName = catalogTrackName
544
+ this.#lastBlockKey = key
545
+ return key
546
+ }
547
+
548
+ /** Record that `key` (block `sbn` on `packetId`) is held by a lookup set. */
549
+ #indexBlockKey(key: string, sbn: number, packetId: number): void {
550
+ let keys = this.#blockKeysBySbn.get(sbn)
551
+ if (!keys) {
552
+ keys = new Map()
553
+ this.#blockKeysBySbn.set(sbn, keys)
554
+ }
555
+ keys.set(key, packetId)
556
+ }
557
+
558
+ /** True while any set a catalog-name-less lookup consults still holds `key`. */
559
+ #isBlockKeyHeld(key: string): boolean {
560
+ return this.#activeBlocks.has(key) ||
561
+ this.#blockSourceCounts.has(key) ||
562
+ this.#blockCatalogTrackNames.has(key) ||
563
+ this.#completedBlocks.has(key)
564
+ }
565
+
566
+ /** Drop `key` from the SBN index once no lookup set holds it any more. */
567
+ #unindexBlockKey(key: string): void {
568
+ if (this.#isBlockKeyHeld(key)) return
569
+ const sbn = this.#parseBlockKey(key).sbn
570
+ const keys = this.#blockKeysBySbn.get(sbn)
571
+ if (!keys) return
572
+ keys.delete(key)
573
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn)
574
+ }
575
+
576
+ /**
577
+ * Make `key` terminal: late symbols for it are duplicates from now on. The
578
+ * key is retired one block lifetime later, when no copy of any of its
579
+ * symbols can still be in flight on either transport (see
580
+ * terminalRetentionMsForPacket). Retirement is swept lazily here, on the
581
+ * stream's own terminal events, so it needs no timer.
582
+ */
583
+ #markTerminal(key: string, sbn: number, packetId: number, clean: boolean): void {
584
+ const nowMs = performance.now()
585
+ this.#retireTerminalBlocks(packetId, nowMs)
586
+ this.#completedBlocks.add(key)
587
+ if (clean) this.#cleanlyCompletedBlocks.add(key)
588
+ this.#indexBlockKey(key, sbn, packetId)
589
+ const expiresAtMs = nowMs + this.terminalRetentionMsForPacket(packetId)
590
+ this.#terminalExpiryMs.set(key, expiresAtMs)
591
+ let queue = this.#terminalQueues.get(packetId)
592
+ if (!queue) {
593
+ queue = new TerminalQueue()
594
+ this.#terminalQueues.set(packetId, queue)
595
+ }
596
+ queue.push({ key, expiresAtMs })
597
+ }
598
+
599
+ #retireTerminalBlocks(packetId: number, nowMs: number): void {
600
+ const queue = this.#terminalQueues.get(packetId)
601
+ if (!queue) return
602
+ for (let record = queue.peek(); record !== undefined; record = queue.peek()) {
603
+ if (record.expiresAtMs > nowMs) return
604
+ queue.shift()
605
+ // A key made terminal again later (or reset and reused) owns a newer
606
+ // record; this one no longer describes it.
607
+ if (this.#terminalExpiryMs.get(record.key) !== record.expiresAtMs) continue
608
+ this.#terminalExpiryMs.delete(record.key)
609
+ this.#completedBlocks.delete(record.key)
610
+ this.#cleanlyCompletedBlocks.delete(record.key)
611
+ this.#workerRecoveredBlocks.delete(record.key)
612
+ this.#unindexBlockKey(record.key)
613
+ }
614
+ }
615
+
616
+ /** Cancel and forget a block's inactivity timer and deadline. */
617
+ #clearBlockTimer(key: string): void {
618
+ const timer = this.#activeBlocks.get(key)
619
+ if (timer?.handle != null) clearTimeout(timer.handle)
620
+ this.#activeBlocks.delete(key)
621
+ this.#activeBlockDeadlinesMs.delete(key)
414
622
  }
415
623
 
416
624
  #parseBlockKey(key: string): { packetId: number; sbn: number; catalogTrackName?: string } {
@@ -528,8 +736,45 @@ export class FECManager {
528
736
  /** Cancel and forget a block's D-28 repair-deadline timer. */
529
737
  #clearRepairDeadline(key: string): void {
530
738
  const timer = this.#repairDeadlines.get(key)
531
- if (timer != null) clearTimeout(timer)
739
+ if (timer?.handle != null) clearTimeout(timer.handle)
532
740
  this.#repairDeadlines.delete(key)
741
+ this.#repairDeadlineAtMs.delete(key)
742
+ }
743
+
744
+ /**
745
+ * Move a block's D-28 repair deadline to `delayMs` from now. The timer
746
+ * already armed for an earlier moment fires first and re-arms for the
747
+ * remainder, so repeated source progress costs no timer operation.
748
+ */
749
+ #armRepairDeadline(
750
+ key: string,
751
+ sbn: number,
752
+ packetId: number,
753
+ catalogTrackName: string | undefined,
754
+ delayMs: number,
755
+ ): void {
756
+ const deadlineMs = performance.now() + delayMs
757
+ this.#repairDeadlineAtMs.set(key, deadlineMs)
758
+ const armed = this.#repairDeadlines.get(key)
759
+ if (armed?.handle != null) {
760
+ if (armed.fireAtMs <= deadlineMs) return
761
+ clearTimeout(armed.handle)
762
+ }
763
+ const timer: DeadlineTimer = { handle: null, fireAtMs: deadlineMs }
764
+ const onFire = (): void => {
765
+ if (this.#repairDeadlines.get(key) !== timer) return
766
+ const currentDeadlineMs = this.#repairDeadlineAtMs.get(key)
767
+ const nowMs = performance.now()
768
+ if (currentDeadlineMs !== undefined && currentDeadlineMs > nowMs) {
769
+ timer.fireAtMs = currentDeadlineMs
770
+ timer.handle = setTimeout(onFire, Math.ceil(currentDeadlineMs - nowMs))
771
+ return
772
+ }
773
+ timer.handle = null
774
+ this.#requestRepair(sbn, packetId, catalogTrackName)
775
+ }
776
+ timer.handle = setTimeout(onFire, delayMs)
777
+ this.#repairDeadlines.set(key, timer)
533
778
  }
534
779
 
535
780
  #requestRepair(
@@ -545,8 +790,9 @@ export class FECManager {
545
790
  ) return
546
791
 
547
792
  const deadline = this.#repairDeadlines.get(key)
548
- if (deadline) clearTimeout(deadline)
793
+ if (deadline?.handle != null) clearTimeout(deadline.handle)
549
794
  this.#repairDeadlines.set(key, null)
795
+ this.#repairDeadlineAtMs.delete(key)
550
796
  this.#repairRequestedBlocks.add(key)
551
797
 
552
798
  // Preserve the source-progress inactivity deadline and append exactly one
@@ -673,20 +919,31 @@ export class FECManager {
673
919
  delayMs: number,
674
920
  ): void {
675
921
  const key = this.#blockKey(sbn, packetId, catalogTrackName)
676
- const current = this.#activeBlocks.get(key)
677
- if (current) clearTimeout(current)
678
922
  const boundedDelayMs = Math.max(1, Math.ceil(delayMs))
679
- this.#activeBlockDeadlinesMs.set(key, performance.now() + boundedDelayMs)
680
- const owner = {}
681
- this.#activeBlockTimeoutOwners.set(key, owner)
682
- const timer = setTimeout(() => {
923
+ const deadlineMs = performance.now() + boundedDelayMs
924
+ this.#activeBlockDeadlinesMs.set(key, deadlineMs)
925
+ const armed = this.#activeBlocks.get(key)
926
+ if (armed?.handle != null) {
927
+ // The armed timer wakes no later than the new deadline and re-arms for
928
+ // the remainder, so moving a deadline later costs no timer operation.
929
+ if (armed.fireAtMs <= deadlineMs) return
930
+ clearTimeout(armed.handle)
931
+ }
932
+ const timer: DeadlineTimer = { handle: null, fireAtMs: deadlineMs }
933
+ const onFire = (): void => {
683
934
  // clearTimeout() cannot retract a callback that the browser already
684
935
  // moved onto its task queue. Only the timer that still owns this
685
936
  // block's deadline may fail it or enqueue Worker cleanup.
686
- if (this.#activeBlockTimeoutOwners.get(key) !== owner) return
937
+ if (this.#activeBlocks.get(key) !== timer) return
938
+ const currentDeadlineMs = this.#activeBlockDeadlinesMs.get(key)
939
+ const nowMs = performance.now()
940
+ if (currentDeadlineMs !== undefined && currentDeadlineMs > nowMs) {
941
+ timer.fireAtMs = currentDeadlineMs
942
+ timer.handle = setTimeout(onFire, Math.ceil(currentDeadlineMs - nowMs))
943
+ return
944
+ }
687
945
  this.#activeBlocks.delete(key)
688
946
  this.#activeBlockDeadlinesMs.delete(key)
689
- this.#activeBlockTimeoutOwners.delete(key)
690
947
  this.#traceLifecycle('timeout-queued', sbn, packetId, catalogTrackName)
691
948
 
692
949
  // A block that began on the synchronous decoder remains owned by that
@@ -713,8 +970,10 @@ export class FECManager {
713
970
  this.#failBlock(sbn, packetId, false, catalogTrackName)
714
971
  }
715
972
  }
716
- }, boundedDelayMs)
973
+ }
974
+ timer.handle = setTimeout(onFire, boundedDelayMs)
717
975
  this.#activeBlocks.set(key, timer)
976
+ this.#indexBlockKey(key, sbn, packetId)
718
977
  }
719
978
 
720
979
  #upsertTrackConfig(packetId: number, config: FECManagerConfig): ResolvedFECTrackConfig {
@@ -751,35 +1010,29 @@ export class FECManager {
751
1010
  return [this.#blockKey(sbn, packetId, catalogTrackName)]
752
1011
  }
753
1012
 
754
- const keys = new Set<string>()
755
- for (const source of [
756
- this.#activeBlocks,
757
- this.#blockSourceCounts,
758
- this.#blockCatalogTrackNames,
759
- ]) {
760
- for (const key of source.keys()) {
761
- const block = this.#parseBlockKey(key)
762
- if (
763
- block.sbn === sbn &&
764
- (packetId === undefined || block.packetId === packetId)
765
- ) keys.add(key)
766
- }
767
- }
768
- for (const source of [this.#completedBlocks, this.#cleanlyCompletedBlocks]) {
769
- for (const key of source) {
770
- const block = this.#parseBlockKey(key)
771
- if (
772
- block.sbn === sbn &&
773
- (packetId === undefined || block.packetId === packetId)
774
- ) keys.add(key)
1013
+ // Every key held by a block-keyed lookup set is indexed under its SBN
1014
+ // (#indexBlockKey), so this visits only the handful of streams sharing the
1015
+ // SBN instead of every retained block. #cleanlyCompletedBlocks is a subset
1016
+ // of #completedBlocks and needs no separate check.
1017
+ const keys: string[] = []
1018
+ const candidates = this.#blockKeysBySbn.get(sbn)
1019
+ if (candidates) {
1020
+ for (const [key, keyPacketId] of candidates) {
1021
+ if (packetId !== undefined && keyPacketId !== packetId) continue
1022
+ if (!this.#isBlockKeyHeld(key)) {
1023
+ candidates.delete(key)
1024
+ continue
1025
+ }
1026
+ keys.push(key)
775
1027
  }
1028
+ if (candidates.size === 0) this.#blockKeysBySbn.delete(sbn)
776
1029
  }
777
1030
 
778
1031
  if (packetId !== undefined) {
779
- if (keys.size === 0) return [this.#blockKey(sbn, packetId)]
780
- return keys.size === 1 ? [...keys] : []
1032
+ if (keys.length === 0) return [this.#blockKey(sbn, packetId)]
1033
+ return keys.length === 1 ? keys : []
781
1034
  }
782
- return keys.size > 0 ? [...keys] : [this.#blockKey(sbn, 0, catalogTrackName)]
1035
+ return keys.length > 0 ? keys : [this.#blockKey(sbn, 0, catalogTrackName)]
783
1036
  }
784
1037
 
785
1038
  // -----------------------------------------------------------------------
@@ -792,6 +1045,7 @@ export class FECManager {
792
1045
  timeoutMs: this.#fecTimeoutMs,
793
1046
  activeBlocks: this.#activeBlocks.size,
794
1047
  completedBlocks: this.#completedBlocks.size,
1048
+ cleanlyCompletedBlocks: this.#cleanlyCompletedBlocks.size,
795
1049
  pendingCounts: Object.fromEntries(this.#blockSourceCounts),
796
1050
  fpsDetected: this.#fpsDetected,
797
1051
  interleaveDepthMs: this.#fecInterleaveDepthMs,
@@ -893,12 +1147,10 @@ export class FECManager {
893
1147
  map.delete(key)
894
1148
  }
895
1149
  }
896
- const resetTimerMap = (
897
- map: Map<string, ReturnType<typeof setTimeout> | null>,
898
- ): void => {
1150
+ const resetTimerMap = (map: Map<string, DeadlineTimer | null>): void => {
899
1151
  for (const [key, timer] of map) {
900
1152
  if (!this.#belongsToStream(key, packetId, catalogTrackName)) continue
901
- if (timer != null) clearTimeout(timer)
1153
+ if (timer?.handle != null) clearTimeout(timer.handle)
902
1154
  map.delete(key)
903
1155
  }
904
1156
  }
@@ -911,10 +1163,14 @@ export class FECManager {
911
1163
  resetTimerMap(this.#activeBlocks)
912
1164
  resetTimerMap(this.#repairDeadlines)
913
1165
  resetMap(this.#activeBlockDeadlinesMs)
914
- resetMap(this.#activeBlockTimeoutOwners)
1166
+ resetMap(this.#repairDeadlineAtMs)
1167
+ // Queued terminal records of this stream no longer match an expiry entry,
1168
+ // so the retirement sweep skips them and cannot retire a reused key early.
1169
+ resetMap(this.#terminalExpiryMs)
915
1170
  resetMap(this.#pendingWorkerCleanupClients)
916
1171
  resetMap(this.#blockSourceCounts)
917
1172
  resetMap(this.#blockSourceEsis)
1173
+ resetMap(this.#blockAuthoredLengths)
918
1174
  resetMap(this.#blockRepairRsIds)
919
1175
  resetMap(this.#blockPathCounts)
920
1176
  resetMap(this.#blockCatalogTrackNames)
@@ -930,6 +1186,12 @@ export class FECManager {
930
1186
  resetSet(this.#startupRepairReadyPackets)
931
1187
  resetSet(this.#startupRepairFailOpenPackets)
932
1188
  resetSet(this.#seenSymbols)
1189
+ for (const [sbn, keys] of this.#blockKeysBySbn) {
1190
+ for (const key of keys.keys()) {
1191
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) keys.delete(key)
1192
+ }
1193
+ if (keys.size === 0) this.#blockKeysBySbn.delete(sbn)
1194
+ }
933
1195
 
934
1196
  const decoderClients = new Set<WasmFecDecoder>()
935
1197
  for (const [key, entry] of this.#fecDecoders) {
@@ -1058,27 +1320,39 @@ export class FECManager {
1058
1320
  if (source === 'multicast') counts.multicastSymbols++
1059
1321
  else counts.moqSymbols++
1060
1322
  this.#blockPathCounts.set(blockKey, counts)
1061
- this.#observeBlockCatalogTrackName(blockKey, catalogTrackName)
1323
+ this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName)
1062
1324
 
1325
+ // Keep the newest entries of each bounded cache. Deleting the oldest in
1326
+ // place keeps exactly the entries a slice(-n) rebuild would, without
1327
+ // copying the whole collection into an array on the page thread.
1063
1328
  if (this.#seenSymbols.size > 4096) {
1064
- this.#seenSymbols = new Set(Array.from(this.#seenSymbols).slice(-2048))
1329
+ dropOldest(this.#seenSymbols, this.#seenSymbols.size - 2048)
1065
1330
  }
1066
1331
  if (this.#blockPathCounts.size > 512) {
1067
- this.#blockPathCounts = new Map(Array.from(this.#blockPathCounts).slice(-256))
1332
+ dropOldest(this.#blockPathCounts, this.#blockPathCounts.size - 256)
1068
1333
  }
1069
1334
  if (this.#blockCatalogTrackNames.size > 512) {
1070
- this.#blockCatalogTrackNames = new Map(
1071
- Array.from(this.#blockCatalogTrackNames).slice(-256),
1072
- )
1335
+ for (const key of dropOldest(
1336
+ this.#blockCatalogTrackNames,
1337
+ this.#blockCatalogTrackNames.size - 256,
1338
+ )) {
1339
+ this.#unindexBlockKey(key)
1340
+ }
1073
1341
  }
1074
1342
 
1075
1343
  return true
1076
1344
  }
1077
1345
 
1078
- #observeBlockCatalogTrackName(blockKey: string, catalogTrackName?: string): void {
1346
+ #observeBlockCatalogTrackName(
1347
+ blockKey: string,
1348
+ sbn: number,
1349
+ packetId: number,
1350
+ catalogTrackName?: string,
1351
+ ): void {
1079
1352
  if (catalogTrackName === undefined) return
1080
1353
  if (!this.#blockCatalogTrackNames.has(blockKey)) {
1081
1354
  this.#blockCatalogTrackNames.set(blockKey, catalogTrackName)
1355
+ this.#indexBlockKey(blockKey, sbn, packetId)
1082
1356
  return
1083
1357
  }
1084
1358
  if (this.#blockCatalogTrackNames.get(blockKey) !== catalogTrackName) {
@@ -1129,7 +1403,7 @@ export class FECManager {
1129
1403
  for (const [key] of this.#activeBlocks) {
1130
1404
  const { packetId, sbn } = this.#parseBlockKey(key);
1131
1405
  const count = this.#blockSourceCounts.get(key) ?? 0;
1132
- const k = this.kForPacket(packetId);
1406
+ const k = this.#blockAuthoredLengths.get(key) ?? this.kForPacket(packetId);
1133
1407
  blocks.push({ sbn, packetId, state: 'collecting', sourceCount: count, k, progress: k > 0 ? Math.min(count / k, 1) : 0 });
1134
1408
  }
1135
1409
  // Recently completed blocks (last 16)
@@ -1164,6 +1438,19 @@ export class FECManager {
1164
1438
  repairDeadlineMsForPacket(packetId: number): number {
1165
1439
  return this.#repairDeadlineMs(this.#resolveTrackConfig(packetId))
1166
1440
  }
1441
+ /**
1442
+ * How long a terminal (clean, recovered or failed) block stays authoritative
1443
+ * for late symbols: one full block lifetime, i.e. the inactivity fail bound
1444
+ * plus the D-28 repair grace a repair-requested block may be granted. No
1445
+ * copy of a block's symbols is useful, or awaited, beyond the moment the
1446
+ * block itself would have been failed, so a copy arriving later is dropped
1447
+ * by the other bounded ledgers rather than by this one. Both terms come from
1448
+ * the track's catalog geometry; there is no separate cap.
1449
+ */
1450
+ terminalRetentionMsForPacket(packetId: number): number {
1451
+ const config = this.#resolveTrackConfig(packetId)
1452
+ return config.timeoutMs + this.#repairGraceMs(config)
1453
+ }
1167
1454
  /** Remaining fetch budget for a specific repair-requested block. */
1168
1455
  repairFetchTimeoutMsForBlock(
1169
1456
  sbn: number,
@@ -1297,13 +1584,34 @@ export class FECManager {
1297
1584
  // Block-completion accounting needs that exact ESI, and counting an
1298
1585
  // ESI-less event as recovered would report healthy FEC while dropping
1299
1586
  // the media. Enforce the Worker contract before any recovery metric.
1300
- if (!Number.isInteger(meta.esi) || meta.esi! < 0 || meta.esi! >= workerK) {
1587
+ // The Worker names the recovered block's authored SSB_length; ESIs
1588
+ // SSB_length..K-1 are encoder padding and are never emitted.
1589
+ if (
1590
+ !Number.isInteger(meta.ssbLength) ||
1591
+ meta.ssbLength! <= 0 ||
1592
+ meta.ssbLength! > workerK
1593
+ ) {
1594
+ const kind: FecWorkerErrorCode = 'recovered-symbol-ssb-length-invalid'
1595
+ const seen = this.#workerErrorCounts.get(kind) ?? 0
1596
+ this.#workerErrorCounts.set(kind, seen + 1)
1597
+ if (seen < WORKER_ERROR_LOG_CAP) {
1598
+ console.warn(
1599
+ `[FECManager] Dropping recovered symbol with invalid SSB_length: pid=${packetId} sbn=${meta.sbn} ssbLength=${String(meta.ssbLength)}`,
1600
+ )
1601
+ }
1602
+ return
1603
+ }
1604
+ if (
1605
+ !Number.isInteger(meta.esi) ||
1606
+ meta.esi! < 0 ||
1607
+ meta.esi! >= meta.ssbLength!
1608
+ ) {
1301
1609
  const kind = 'recovered-symbol-missing-esi'
1302
1610
  const seen = this.#workerErrorCounts.get(kind) ?? 0
1303
1611
  this.#workerErrorCounts.set(kind, seen + 1)
1304
1612
  if (seen < WORKER_ERROR_LOG_CAP) {
1305
1613
  console.warn(
1306
- `[FECManager] Dropping recovered symbol without valid ESI: pid=${packetId} sbn=${meta.sbn} esi=${String(meta.esi)}`,
1614
+ `[FECManager] Dropping recovered symbol without valid ESI: pid=${packetId} sbn=${meta.sbn} esi=${String(meta.esi)} ssbLength=${String(meta.ssbLength)}`,
1307
1615
  )
1308
1616
  }
1309
1617
  return
@@ -1341,8 +1649,7 @@ export class FECManager {
1341
1649
  this.#fecStats.blocksRecovered++
1342
1650
  this.#statsForPacket(packetId).blocksRecovered++
1343
1651
  if (this.#workerRecoveredBlocks.size > 1000) {
1344
- const stale = Array.from(this.#workerRecoveredBlocks).slice(0, 500)
1345
- for (const key of stale) this.#workerRecoveredBlocks.delete(key)
1652
+ dropOldest(this.#workerRecoveredBlocks, 500)
1346
1653
  }
1347
1654
  }
1348
1655
 
@@ -1364,10 +1671,10 @@ export class FECManager {
1364
1671
  }
1365
1672
 
1366
1673
  // The worker emits recovered source symbols in ESI order. Complete the
1367
- // block only after the final slot so assemblers receive every missing
1368
- // symbol before their completion callback flushes buffered media.
1674
+ // block only after its final authored slot so assemblers receive every
1675
+ // missing symbol before their completion callback flushes buffered media.
1369
1676
  if (
1370
- esi >= workerK - 1 &&
1677
+ esi >= meta.ssbLength! - 1 &&
1371
1678
  !this.#completedBlocks.has(blockKey)
1372
1679
  ) {
1373
1680
  this.cancelBlockTimeout(meta.sbn, packetId, recoveredCatalogTrackName)
@@ -1584,12 +1891,16 @@ export class FECManager {
1584
1891
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName)
1585
1892
  if (workerClient && !syncBlockOwner) {
1586
1893
  if (!this.#claimDecoderBlock(workerClient, sbn, catalogTrackName)) return null
1587
- // Create clean ArrayBuffer copy — prevents transferring a shared underlying buffer
1588
- // when symbolData is a view into a larger packet (T-03-06)
1589
- const buf = fecData.buffer.slice(
1590
- fecData.byteOffset,
1591
- fecData.byteOffset + fecData.byteLength,
1592
- ) as ArrayBuffer
1894
+ // Transfer an ArrayBuffer nothing else references. A symbol this manager
1895
+ // just zero-padded to T already is one; copying it again cost a second
1896
+ // T-byte allocation per short packet (BLO-36599). A caller's buffer may
1897
+ // be a view into a larger packet, so it is copied first (T-03-06).
1898
+ const buf = fecData !== symbolData
1899
+ ? fecData.buffer as ArrayBuffer
1900
+ : fecData.buffer.slice(
1901
+ fecData.byteOffset,
1902
+ fecData.byteOffset + fecData.byteLength,
1903
+ ) as ArrayBuffer
1593
1904
  // Pass the flat SS_ID through to the worker. The WASM decoder derives
1594
1905
  // SBN/ESI internally per ISO 23008-1 §C.5.2; the WASM add_source
1595
1906
  // signature is (ss_id, data, timestamp) — pre-computing sbn/esi on this
@@ -1677,7 +1988,9 @@ export class FECManager {
1677
1988
  this.noteBlockActivity(sbn, packetId, catalogTrackName)
1678
1989
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName)
1679
1990
  if (this.#completedBlocks.has(blockKey)) return null
1680
- const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey)
1991
+ if (!this.#noteAuthoredLength(blockKey, sbn, packetId, ssbLength, catalogTrackName)) {
1992
+ return null
1993
+ }
1681
1994
  let repairIds = this.#blockRepairRsIds.get(blockKey)
1682
1995
  if (!repairIds) {
1683
1996
  repairIds = new Set()
@@ -1688,6 +2001,74 @@ export class FECManager {
1688
2001
  this.#traceLifecycle('repair-arrived', sbn, packetId, catalogTrackName, rsId)
1689
2002
  }
1690
2003
 
2004
+ // Every authored source symbol already arrived: the block is clean now
2005
+ // that its SSB_length is known. The decoder still receives the repair so
2006
+ // it retires its own copy of the block, but whatever it returns is the
2007
+ // source the direct path already routed, not a recovery.
2008
+ const cleanOnArrival =
2009
+ (this.#blockSourceCounts.get(blockKey) ?? 0) >= ssbLength
2010
+ const recovered = this.#dispatchRepairSymbol(
2011
+ blockKey,
2012
+ sbn,
2013
+ packetId,
2014
+ ssStart,
2015
+ ssbLength,
2016
+ rsId,
2017
+ fecData,
2018
+ catalogTrackName,
2019
+ )
2020
+ if (cleanOnArrival) {
2021
+ this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName)
2022
+ return null
2023
+ }
2024
+ return recovered
2025
+ }
2026
+
2027
+ /**
2028
+ * Record a block's authored SSB_length from a repair symbol. Returns false,
2029
+ * leaving the block unchanged, when the symbol contradicts the block: a
2030
+ * different SSB_length than an earlier repair symbol declared is dropped,
2031
+ * and an SSB_length that places an already-received source ESI inside the
2032
+ * zero padding fails the block, since its geometry can no longer be trusted.
2033
+ */
2034
+ #noteAuthoredLength(
2035
+ blockKey: string,
2036
+ sbn: number,
2037
+ packetId: number,
2038
+ ssbLength: number,
2039
+ catalogTrackName?: string,
2040
+ ): boolean {
2041
+ const known = this.#blockAuthoredLengths.get(blockKey)
2042
+ if (known === ssbLength) return true
2043
+ if (known !== undefined) {
2044
+ this.#ssbLengthConflictCount++
2045
+ if (this.#ssbLengthConflictCount <= 5 || this.#ssbLengthConflictCount % 100 === 0) {
2046
+ console.warn(
2047
+ `[FECManager] Dropping repair symbol whose SSB_length ${ssbLength} conflicts with ${known} for packetId=${packetId} sbn=${sbn}`,
2048
+ )
2049
+ }
2050
+ return false
2051
+ }
2052
+ const sourceEsis = this.#blockSourceEsis.get(blockKey)
2053
+ if (sourceEsis && [...sourceEsis].some((esi) => esi >= ssbLength)) {
2054
+ this.#failBlock(sbn, packetId, false, catalogTrackName)
2055
+ return false
2056
+ }
2057
+ this.#blockAuthoredLengths.set(blockKey, ssbLength)
2058
+ return true
2059
+ }
2060
+
2061
+ #dispatchRepairSymbol(
2062
+ blockKey: string,
2063
+ sbn: number,
2064
+ packetId: number,
2065
+ ssStart: number,
2066
+ ssbLength: number,
2067
+ rsId: number,
2068
+ fecData: Uint8Array,
2069
+ catalogTrackName?: string,
2070
+ ): Uint8Array | null {
2071
+ const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey)
1691
2072
  // Worker-backed track: dispatch async, return null (recovery via onFrame callback)
1692
2073
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName)
1693
2074
  if (workerClient && !syncBlockOwner) {
@@ -1764,7 +2145,8 @@ export class FECManager {
1764
2145
 
1765
2146
  /**
1766
2147
  * Track a source symbol for an FEC block. Refreshes the inactivity deadline
1767
- * on each symbol and marks the block clean when K source symbols arrive.
2148
+ * on each symbol and marks the block clean when all of its authored source
2149
+ * symbols arrived: the SSB_length a repair symbol declared, otherwise K.
1768
2150
  */
1769
2151
  trackBlock(
1770
2152
  sbn: number,
@@ -1779,9 +2161,18 @@ export class FECManager {
1779
2161
  // Skip blocks already recovered — late source symbols must not restart timeouts
1780
2162
  if (this.#completedBlocks.has(key)) return
1781
2163
 
2164
+ // A source ESI inside the zero padding contradicts the block's authored
2165
+ // SSB_length; its geometry can no longer be trusted, so fail it closed.
2166
+ const authoredLength = this.#blockAuthoredLengths.get(key) ?? k
2167
+ if (Number.isInteger(esi) && esi! >= authoredLength) {
2168
+ this.#failBlock(sbn, packetId, false, catalogTrackName)
2169
+ return
2170
+ }
2171
+
1782
2172
  // Count source symbols per block
1783
2173
  const count = (this.#blockSourceCounts.get(key) ?? 0) + 1
1784
2174
  this.#blockSourceCounts.set(key, count)
2175
+ if (count === 1) this.#indexBlockKey(key, sbn, packetId)
1785
2176
  if (Number.isInteger(esi) && esi! >= 0 && esi! < k) {
1786
2177
  let sourceEsis = this.#blockSourceEsis.get(key)
1787
2178
  if (!sourceEsis) {
@@ -1798,30 +2189,10 @@ export class FECManager {
1798
2189
  }
1799
2190
  }
1800
2191
 
1801
- // When K source symbols received, block is clean (no loss, no FEC needed).
1802
- if (k > 0 && count >= k) {
1803
- this.#fecStats.blocksClean++
1804
- this.#statsForPacket(packetId).blocksClean++
1805
- this.cancelBlockTimeout(sbn, packetId, catalogTrackName)
1806
- this.#blockSourceCounts.delete(key)
1807
- this.#blockSourceEsis.delete(key)
1808
- this.#blockRepairRsIds.delete(key)
1809
- this.#completedBlocks.add(key)
1810
- // BLO-3323 L15: track which SBNs reached K source-symbol arrivals so the
1811
- // worker recovery suppression can distinguish "block completed by source"
1812
- // (legitimately suppress duplicate recovery) from "block touched by any
1813
- // prior emit / timeout / external mark" (do NOT suppress recovery).
1814
- this.#cleanlyCompletedBlocks.add(key)
1815
- this.#markPathBlockComplete(sbn, packetId, catalogTrackName)
1816
- if (catalogTrackName === undefined) {
1817
- this.onBlockComplete?.(sbn, packetId)
1818
- } else {
1819
- this.onBlockComplete?.(sbn, packetId, catalogTrackName)
1820
- }
1821
- // MmtpRouter feeds the K-th source immediately after this callback.
1822
- // Defer cleanup so that synchronous feed selects the same decoder; this
1823
- // also clears blocks whose K-th packet was too large for decoder input.
1824
- queueMicrotask(() => this.#syncDecoderBlockOwners.delete(key))
2192
+ // When every authored source symbol arrived (SSB_length once a repair
2193
+ // symbol declared it, otherwise K), the block is clean: no loss, no FEC.
2194
+ if (k > 0 && count >= authoredLength) {
2195
+ this.#completeCleanBlock(key, sbn, packetId, catalogTrackName)
1825
2196
  return
1826
2197
  }
1827
2198
 
@@ -1832,6 +2203,37 @@ export class FECManager {
1832
2203
  // progress-refreshed source horizon above is the earliest loss signal.
1833
2204
  }
1834
2205
 
2206
+ #completeCleanBlock(
2207
+ key: string,
2208
+ sbn: number,
2209
+ packetId: number,
2210
+ catalogTrackName?: string,
2211
+ ): void {
2212
+ this.#fecStats.blocksClean++
2213
+ this.#statsForPacket(packetId).blocksClean++
2214
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName)
2215
+ this.#blockSourceCounts.delete(key)
2216
+ this.#blockSourceEsis.delete(key)
2217
+ this.#blockAuthoredLengths.delete(key)
2218
+ this.#blockRepairRsIds.delete(key)
2219
+ // BLO-3323 L15: track which SBNs reached K source-symbol arrivals so the
2220
+ // worker recovery suppression can distinguish "block completed by source"
2221
+ // (legitimately suppress duplicate recovery) from "block touched by any
2222
+ // prior emit / timeout / external mark" (do NOT suppress recovery).
2223
+ // #markTerminal retires both memberships together (BLO-36599).
2224
+ this.#markTerminal(key, sbn, packetId, true)
2225
+ this.#markPathBlockComplete(sbn, packetId, catalogTrackName)
2226
+ if (catalogTrackName === undefined) {
2227
+ this.onBlockComplete?.(sbn, packetId)
2228
+ } else {
2229
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName)
2230
+ }
2231
+ // MmtpRouter feeds the K-th source immediately after this callback.
2232
+ // Defer cleanup so that synchronous feed selects the same decoder; this
2233
+ // also clears blocks whose K-th packet was too large for decoder input.
2234
+ queueMicrotask(() => this.#syncDecoderBlockOwners.delete(key))
2235
+ }
2236
+
1835
2237
  /** Refresh deadlines after accepted block activity. */
1836
2238
  noteBlockActivity(
1837
2239
  sbn: number,
@@ -1863,12 +2265,12 @@ export class FECManager {
1863
2265
  this.onRepairNeeded &&
1864
2266
  (repairDeadline === undefined || sourceProgress)
1865
2267
  ) {
1866
- if (repairDeadline != null) clearTimeout(repairDeadline)
1867
- this.#repairDeadlines.set(
2268
+ this.#armRepairDeadline(
1868
2269
  key,
1869
- setTimeout(() => {
1870
- this.#requestRepair(sbn, packetId, catalogTrackName)
1871
- }, this.#repairDeadlineMs(trackConfig)),
2270
+ sbn,
2271
+ packetId,
2272
+ catalogTrackName,
2273
+ this.#repairDeadlineMs(trackConfig),
1872
2274
  )
1873
2275
  }
1874
2276
 
@@ -1884,12 +2286,7 @@ export class FECManager {
1884
2286
  const key = this.#blockKey(sbn, packetId, catalogTrackName)
1885
2287
  this.#traceLifecycle('failed', sbn, packetId, catalogTrackName)
1886
2288
  this.#clearRepairDeadline(key)
1887
- const activeTimer = this.#activeBlocks.get(key)
1888
- if (activeTimer) {
1889
- clearTimeout(activeTimer)
1890
- this.#activeBlocks.delete(key)
1891
- }
1892
- this.#activeBlockDeadlinesMs.delete(key)
2289
+ this.#clearBlockTimer(key)
1893
2290
  if (this.#repairRequestedBlocks.delete(key)) {
1894
2291
  if (catalogTrackName === undefined) {
1895
2292
  this.onRepairResolved?.(sbn, packetId, 'failed')
@@ -1899,10 +2296,10 @@ export class FECManager {
1899
2296
  }
1900
2297
  this.#blockSourceCounts.delete(key)
1901
2298
  this.#blockSourceEsis.delete(key)
2299
+ this.#blockAuthoredLengths.delete(key)
1902
2300
  this.#blockRepairRsIds.delete(key)
1903
- this.#activeBlockTimeoutOwners.delete(key)
1904
2301
  this.#syncDecoderBlockOwners.delete(key)
1905
- this.#completedBlocks.add(key)
2302
+ this.#markTerminal(key, sbn, packetId, false)
1906
2303
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName)
1907
2304
  this.#fecStats.blocksFailed++
1908
2305
  this.#statsForPacket(packetId).blocksFailed++
@@ -1925,10 +2322,10 @@ export class FECManager {
1925
2322
  /** Mark a block as completed externally (e.g., after routing recovered data). */
1926
2323
  markBlockCompleted(sbn: number, packetId?: number, catalogTrackName?: string): void {
1927
2324
  for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
1928
- this.#completedBlocks.add(key)
2325
+ const block = this.#parseBlockKey(key)
2326
+ this.#markTerminal(key, block.sbn, block.packetId, false)
1929
2327
  this.#pendingWorkerCleanups.delete(key)
1930
2328
  this.#pendingWorkerCleanupClients.delete(key)
1931
- const block = this.#parseBlockKey(key)
1932
2329
  this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName)
1933
2330
  this.#clearRepairDeadline(key)
1934
2331
  if (this.#repairRequestedBlocks.delete(key)) {
@@ -1945,14 +2342,9 @@ export class FECManager {
1945
2342
  }
1946
2343
  this.#blockSourceCounts.delete(key)
1947
2344
  this.#blockSourceEsis.delete(key)
2345
+ this.#blockAuthoredLengths.delete(key)
1948
2346
  this.#blockRepairRsIds.delete(key)
1949
- const timer = this.#activeBlocks.get(key)
1950
- if (timer) {
1951
- clearTimeout(timer)
1952
- this.#activeBlocks.delete(key)
1953
- }
1954
- this.#activeBlockDeadlinesMs.delete(key)
1955
- this.#activeBlockTimeoutOwners.delete(key)
2347
+ this.#clearBlockTimer(key)
1956
2348
  }
1957
2349
  }
1958
2350
 
@@ -2000,10 +2392,10 @@ export class FECManager {
2000
2392
  /** Cancel block timeout (block completed via clean reception or FEC recovery). */
2001
2393
  cancelBlockTimeout(sbn: number, packetId?: number, catalogTrackName?: string): void {
2002
2394
  for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
2003
- this.#completedBlocks.add(key)
2395
+ const block = this.#parseBlockKey(key)
2396
+ this.#markTerminal(key, block.sbn, block.packetId, false)
2004
2397
  this.#pendingWorkerCleanups.delete(key)
2005
2398
  this.#pendingWorkerCleanupClients.delete(key)
2006
- const block = this.#parseBlockKey(key)
2007
2399
  this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName)
2008
2400
  this.#clearRepairDeadline(key)
2009
2401
  if (this.#repairRequestedBlocks.delete(key)) {
@@ -2020,23 +2412,9 @@ export class FECManager {
2020
2412
  }
2021
2413
  this.#blockSourceCounts.delete(key)
2022
2414
  this.#blockSourceEsis.delete(key)
2415
+ this.#blockAuthoredLengths.delete(key)
2023
2416
  this.#blockRepairRsIds.delete(key)
2024
- const timer = this.#activeBlocks.get(key)
2025
- if (timer) {
2026
- clearTimeout(timer)
2027
- this.#activeBlocks.delete(key)
2028
- }
2029
- this.#activeBlockDeadlinesMs.delete(key)
2030
- this.#activeBlockTimeoutOwners.delete(key)
2031
- }
2032
- // Trim old entries to prevent unbounded growth (keep last ~500 blocks)
2033
- if (this.#completedBlocks.size > 1000) {
2034
- const iter = this.#completedBlocks.values()
2035
- for (let i = 0; i < 500; i++) iter.next()
2036
- // Sets iterate in insertion order — first 500 are oldest
2037
- const keep = new Set<string>()
2038
- for (const v of iter) keep.add(v)
2039
- this.#completedBlocks = keep
2417
+ this.#clearBlockTimer(key)
2040
2418
  }
2041
2419
  }
2042
2420
 
@@ -2045,18 +2423,24 @@ export class FECManager {
2045
2423
  // -----------------------------------------------------------------------
2046
2424
 
2047
2425
  dispose(): void {
2048
- for (const timer of this.#activeBlocks.values()) clearTimeout(timer)
2426
+ for (const timer of this.#activeBlocks.values()) {
2427
+ if (timer.handle != null) clearTimeout(timer.handle)
2428
+ }
2049
2429
  this.#activeBlocks.clear()
2050
2430
  this.#activeBlockDeadlinesMs.clear()
2051
- this.#activeBlockTimeoutOwners.clear()
2052
2431
  this.#pendingWorkerCleanups.clear()
2053
2432
  this.#pendingWorkerCleanupClients.clear()
2054
2433
  for (const timer of this.#repairDeadlines.values()) {
2055
- if (timer != null) clearTimeout(timer)
2434
+ if (timer?.handle != null) clearTimeout(timer.handle)
2056
2435
  }
2057
2436
  this.#repairDeadlines.clear()
2437
+ this.#repairDeadlineAtMs.clear()
2438
+ this.#terminalExpiryMs.clear()
2439
+ this.#terminalQueues.clear()
2440
+ this.#blockKeysBySbn.clear()
2058
2441
  this.#blockSourceCounts.clear()
2059
2442
  this.#blockSourceEsis.clear()
2443
+ this.#blockAuthoredLengths.clear()
2060
2444
  this.#blockRepairRsIds.clear()
2061
2445
  this.#completedBlocks.clear()
2062
2446
  this.#cleanlyCompletedBlocks.clear()