@blockcast/mmt-container 0.5.0-main.6f3380bce0c1 → 0.5.0-main.7e3db3eef00c

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 (45) hide show
  1. package/dist/browser-runtime.js +411 -37
  2. package/dist/browser-runtime.js.map +2 -2
  3. package/dist/fec-manager.d.ts +8 -0
  4. package/dist/fec-manager.d.ts.map +1 -1
  5. package/dist/fec-manager.js +60 -4
  6. package/dist/fec-manager.js.map +2 -2
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js.map +2 -2
  10. package/dist/mmtp-container-parser.d.ts +10 -0
  11. package/dist/mmtp-container-parser.d.ts.map +1 -1
  12. package/dist/mmtp-container-parser.js +31 -1
  13. package/dist/mmtp-container-parser.js.map +2 -2
  14. package/dist/mmtp-container-parser.no-modules.js +31 -1
  15. package/dist/mmtp-container-parser.no-modules.js.map +2 -2
  16. package/dist/mmtp-decode-pipeline.js +31 -1
  17. package/dist/mmtp-decode-pipeline.js.map +2 -2
  18. package/dist/mmtp-router.d.ts +32 -1
  19. package/dist/mmtp-router.d.ts.map +1 -1
  20. package/dist/mmtp-router.js +247 -13
  21. package/dist/mmtp-router.js.map +2 -2
  22. package/dist/multicast-manager.d.ts +30 -2
  23. package/dist/multicast-manager.d.ts.map +1 -1
  24. package/dist/multicast-manager.js +353 -18
  25. package/dist/multicast-manager.js.map +2 -2
  26. package/dist/no-modules.js +31 -1
  27. package/dist/no-modules.js.map +2 -2
  28. package/dist/repair-fetch.d.ts +41 -10
  29. package/dist/repair-fetch.d.ts.map +1 -1
  30. package/dist/repair-fetch.js +58 -19
  31. package/dist/repair-fetch.js.map +2 -2
  32. package/dist/wasm-mmtp-container-parser.js +31 -1
  33. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  34. package/package.json +7 -6
  35. package/src/fec-manager.ts +73 -4
  36. package/src/index.ts +1 -0
  37. package/src/mmtp-container-parser.ts +48 -0
  38. package/src/mmtp-router.ts +309 -15
  39. package/src/multicast-manager.ts +85 -1
  40. package/src/repair-fetch.ts +131 -31
  41. package/test-vectors/catalog/negative/multicast-auth-padded-key.json +0 -1
  42. package/test-vectors/catalog/negative/multicast-auth-reused-track-format.json +0 -1
  43. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +0 -1
  44. package/test-vectors/catalog/negative/multicast-auth-trailing-pad-bits.json +0 -1
  45. package/test-vectors/repair-policy-v1.json +113 -0
@@ -13502,6 +13502,9 @@ var FECManager = class _FECManager {
13502
13502
  // Receiver-local first-accepted-symbol time per block, bounded like
13503
13503
  // #blockPathCounts (see blockAnchorAtMs).
13504
13504
  this.#blockAnchorsMs = /* @__PURE__ */ new Map();
13505
+ // The receipt time of the packet being fed, when it is not now: a datagram
13506
+ // held on a miss and admitted later (withReceiptTime).
13507
+ this.#receiptAtMs = void 0;
13505
13508
  // Exact catalog identity observed on accepted symbols for each FEC block.
13506
13509
  // Conflicting identities collapse to null so recovery fails closed.
13507
13510
  this.#blockCatalogTrackNames = /* @__PURE__ */ new Map();
@@ -13552,6 +13555,11 @@ var FECManager = class _FECManager {
13552
13555
  // Worker-recovered blocks a recovered packet of which admission refused,
13553
13556
  // until the decode's final symbol (7.2.7: the block is unrecovered).
13554
13557
  this.#refusedRecoveries = /* @__PURE__ */ new Set();
13558
+ // Worker-recovered blocks: the next ESI the decode's ordered emit owes. The
13559
+ // Worker emits every ESI 0..SSB_length-1 in order and drops only a symbol it
13560
+ // refuses (a malformed ssbg_mode1 symbol), so a skipped ESI is a dropped
13561
+ // recovered packet and the decode recovered nothing.
13562
+ this.#workerRecoveredNextEsi = /* @__PURE__ */ new Map();
13555
13563
  // How the multicast leg delivers symbols (see MulticastSymbolDelivery). The
13556
13564
  // provider declares it per transport join; absence keeps datagram semantics.
13557
13565
  this.#multicastSymbolDelivery = "datagram";
@@ -13747,6 +13755,7 @@ var FECManager = class _FECManager {
13747
13755
  #seenSymbols;
13748
13756
  #blockPathCounts;
13749
13757
  #blockAnchorsMs;
13758
+ #receiptAtMs;
13750
13759
  #blockCatalogTrackNames;
13751
13760
  #startupAlignedPackets;
13752
13761
  #startupPartialBlocks;
@@ -13760,6 +13769,7 @@ var FECManager = class _FECManager {
13760
13769
  #repairDeadlineAtMs;
13761
13770
  #workerRecoveredBlocks;
13762
13771
  #refusedRecoveries;
13772
+ #workerRecoveredNextEsi;
13763
13773
  #multicastSymbolDelivery;
13764
13774
  #orderedFrontiers;
13765
13775
  #orderedPendingBlocks;
@@ -13900,6 +13910,7 @@ var FECManager = class _FECManager {
13900
13910
  this.#cleanlyCompletedBlocks.delete(record.key);
13901
13911
  this.#workerRecoveredBlocks.delete(record.key);
13902
13912
  this.#refusedRecoveries.delete(record.key);
13913
+ this.#workerRecoveredNextEsi.delete(record.key);
13903
13914
  this.#failedBlocks.delete(record.key);
13904
13915
  this.#resolvedBlockClasses.delete(record.key);
13905
13916
  this.#repairedBlocks.delete(record.key);
@@ -14238,7 +14249,7 @@ var FECManager = class _FECManager {
14238
14249
  * remainder, so repeated source progress costs no timer operation.
14239
14250
  */
14240
14251
  #armRepairDeadline(key, sbn, packetId, catalogTrackName, delayMs) {
14241
- const deadlineMs = performance.now() + delayMs;
14252
+ const deadlineMs = this.#notEarlierUnderReceipt(this.#receiptNow() + delayMs, this.#repairDeadlineAtMs.get(key));
14242
14253
  this.#repairDeadlineAtMs.set(key, deadlineMs);
14243
14254
  const armed = this.#repairDeadlines.get(key);
14244
14255
  if (armed?.handle != null) {
@@ -14258,7 +14269,7 @@ var FECManager = class _FECManager {
14258
14269
  timer.handle = null;
14259
14270
  this.#requestRepair(sbn, packetId, catalogTrackName);
14260
14271
  };
14261
- timer.handle = setTimeout(onFire, delayMs);
14272
+ timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
14262
14273
  this.#repairDeadlines.set(key, timer);
14263
14274
  }
14264
14275
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14662,7 +14673,10 @@ var FECManager = class _FECManager {
14662
14673
  }
14663
14674
  #armBlockTimeout(sbn, packetId, catalogTrackName, delayMs) {
14664
14675
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
14665
- const waitAtMs = performance.now() + Math.max(1, Math.ceil(delayMs));
14676
+ const waitAtMs = this.#notEarlierUnderReceipt(
14677
+ this.#receiptNow() + Math.max(1, Math.ceil(delayMs)),
14678
+ this.#blockWaitDeadlinesMs.get(key)
14679
+ );
14666
14680
  const holdAtMs = this.#repairHoldUntilMs.get(key);
14667
14681
  this.#blockWaitDeadlinesMs.set(key, holdAtMs === void 0 ? waitAtMs : Math.min(waitAtMs, holdAtMs));
14668
14682
  this.#applyBlockDeadline(key, sbn, packetId, catalogTrackName);
@@ -15052,6 +15066,7 @@ var FECManager = class _FECManager {
15052
15066
  resetSet(this.#repairRequestedBlocks);
15053
15067
  resetSet(this.#workerRecoveredBlocks);
15054
15068
  resetSet(this.#refusedRecoveries);
15069
+ resetMap(this.#workerRecoveredNextEsi);
15055
15070
  resetSet(this.#startupAlignedPackets);
15056
15071
  resetSet(this.#startupPartialBlocks);
15057
15072
  resetSet(this.#startupRepairReadyPackets);
@@ -15179,6 +15194,7 @@ var FECManager = class _FECManager {
15179
15194
  dropSet(this.#repairRequestedBlocks);
15180
15195
  dropSet(this.#workerRecoveredBlocks);
15181
15196
  dropSet(this.#refusedRecoveries);
15197
+ dropMap(this.#workerRecoveredNextEsi);
15182
15198
  dropSet(this.#startupAlignedPackets);
15183
15199
  dropSet(this.#startupPartialBlocks);
15184
15200
  dropSet(this.#startupRepairReadyPackets);
@@ -15292,7 +15308,9 @@ var FECManager = class _FECManager {
15292
15308
  moqSymbols: 0,
15293
15309
  complete: false
15294
15310
  };
15295
- if (!this.#blockAnchorsMs.has(blockKey)) this.#blockAnchorsMs.set(blockKey, performance.now());
15311
+ const receivedAtMs = this.#receiptNow();
15312
+ const anchorMs = this.#blockAnchorsMs.get(blockKey);
15313
+ if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
15296
15314
  if (source === "multicast") counts.multicastSymbols++;
15297
15315
  else counts.moqSymbols++;
15298
15316
  this.#blockPathCounts.set(blockKey, counts);
@@ -15964,6 +15982,16 @@ var FECManager = class _FECManager {
15964
15982
  if (!this.#claimDecoderBlock(client, meta.sbn, recoveredCatalogTrackName)) return;
15965
15983
  const blockKey = this.#blockKey(meta.sbn, packetId, recoveredCatalogTrackName);
15966
15984
  const cleanlyCompleted = this.#cleanlyCompletedBlocks.has(blockKey);
15985
+ if (esi !== (this.#workerRecoveredNextEsi.get(blockKey) ?? 0)) {
15986
+ this.#refusedRecoveries.add(blockKey);
15987
+ if (this.#refusedRecoveries.size > 1e3) dropOldest(this.#refusedRecoveries, 500);
15988
+ }
15989
+ if (esi >= meta.ssbLength - 1) {
15990
+ this.#workerRecoveredNextEsi.delete(blockKey);
15991
+ } else {
15992
+ this.#workerRecoveredNextEsi.set(blockKey, esi + 1);
15993
+ if (this.#workerRecoveredNextEsi.size > 1e3) dropOldest(this.#workerRecoveredNextEsi, 500);
15994
+ }
15967
15995
  if (!cleanlyCompleted) {
15968
15996
  const symbolKey = `${blockKey}:${esi}`;
15969
15997
  if (!this.#seenSymbols.has(symbolKey)) {
@@ -16567,6 +16595,33 @@ var FECManager = class _FECManager {
16567
16595
  }
16568
16596
  queueMicrotask(() => this.#syncDecoderBlockOwners.delete(key));
16569
16597
  }
16598
+ /**
16599
+ * Run `fn` with `receivedAtMs` (performance.now() clock) as the receipt
16600
+ * time of what it feeds. Within a consumer the bc-provenance profile
16601
+ * governs, a datagram held on a miss and admitted later keeps its receipt
16602
+ * time (fec-01 9): it anchors its block's ts and arms the block's
16603
+ * deadlines from then, never later than they are already armed.
16604
+ */
16605
+ withReceiptTime(receivedAtMs, fn) {
16606
+ const outer = this.#receiptAtMs;
16607
+ this.#receiptAtMs = receivedAtMs;
16608
+ try {
16609
+ fn();
16610
+ } finally {
16611
+ this.#receiptAtMs = outer;
16612
+ }
16613
+ }
16614
+ #receiptNow() {
16615
+ return this.#receiptAtMs ?? performance.now();
16616
+ }
16617
+ /**
16618
+ * A held packet admitted late arms from its (earlier) receipt time; that
16619
+ * never pulls in a deadline later activity already armed. Outside a
16620
+ * receipt scope a re-arm replaces the deadline, as a narrower bound may.
16621
+ */
16622
+ #notEarlierUnderReceipt(deadlineMs, armedMs) {
16623
+ return this.#receiptAtMs === void 0 || armedMs === void 0 ? deadlineMs : Math.max(deadlineMs, armedMs);
16624
+ }
16570
16625
  /** Refresh deadlines after accepted block activity. */
16571
16626
  noteBlockActivity(sbn, packetId, catalogTrackName, sourceProgress = false) {
16572
16627
  if (!this.#trackConfigs.has(packetId)) return;
@@ -16746,6 +16801,7 @@ var FECManager = class _FECManager {
16746
16801
  this.#repairRequestedBlocks.clear();
16747
16802
  this.#workerRecoveredBlocks.clear();
16748
16803
  this.#refusedRecoveries.clear();
16804
+ this.#workerRecoveredNextEsi.clear();
16749
16805
  this.#syncDecoderBlockOwners.clear();
16750
16806
  this.#startupAlignedPackets.clear();
16751
16807
  this.#startupPartialBlocks.clear();
@@ -17599,6 +17655,9 @@ function authoredGap(before, after) {
17599
17655
  if (!a || !b || a.mediaTimescale !== b.mediaTimescale) return false;
17600
17656
  return b.decodeTime > a.decodeTime + BigInt(a.durationTicks);
17601
17657
  }
17658
+ function ssIdAfter(a, b) {
17659
+ return (a - b | 0) > 0;
17660
+ }
17602
17661
  var FecReleaseSequencer = class {
17603
17662
  #streams = /* @__PURE__ */ new Map();
17604
17663
  #gate;
@@ -17660,11 +17719,17 @@ var FecReleaseSequencer = class {
17660
17719
  stream.last = null;
17661
17720
  stream.lastSbn = void 0;
17662
17721
  stream.discontinuity = false;
17722
+ stream.rapSsId = void 0;
17663
17723
  }
17664
17724
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
17665
17725
  this.#recordStat("droppedStale");
17666
17726
  return;
17667
17727
  }
17728
+ const ssId = meta.fecSbn;
17729
+ if (meta.trackType === "video" && ssId !== void 0 && this.#gate.isRap?.(data, meta) === true) {
17730
+ if (stream.rapSsId === void 0 || ssIdAfter(ssId, stream.rapSsId)) stream.rapSsId = ssId;
17731
+ this.#gate.onRap?.(stream.packetId, stream.catalogTrackName, ssId);
17732
+ }
17668
17733
  if (stream.last === null) {
17669
17734
  if (meta.trackType === "video" && !meta.keyframe) {
17670
17735
  this.#recordStat("droppedBeforeStartupKeyframe");
@@ -17700,6 +17765,22 @@ var FecReleaseSequencer = class {
17700
17765
  }
17701
17766
  return earliest;
17702
17767
  }
17768
+ /**
17769
+ * Whether a complete RAP above SS_ID `ssId` entered the gate of a stream of
17770
+ * `packetId` (draft-ramadan-moq-fec 11.4.2: repair of a block below it is
17771
+ * moot). Its SS_ID is the one its frame completed in; a frame's packets
17772
+ * hold consecutive SS_IDs in authored order, so a complete RAP with a
17773
+ * packet above `ssId` has every packet of it at or above the first SS_ID
17774
+ * any loss at or below `ssId` could have taken.
17775
+ */
17776
+ rapAbove(packetId, catalogTrackName, ssId) {
17777
+ for (const stream of this.#streams.values()) {
17778
+ if (stream.packetId !== packetId) continue;
17779
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
17780
+ if (stream.rapSsId !== void 0 && ssIdAfter(stream.rapSsId, ssId)) return true;
17781
+ }
17782
+ return false;
17783
+ }
17703
17784
  /** Re-evaluate held gaps after FEC state changed. */
17704
17785
  poke(streamKey) {
17705
17786
  if (streamKey !== void 0) {
@@ -17790,7 +17871,8 @@ var FecReleaseSequencer = class {
17790
17871
  buf: [],
17791
17872
  last: null,
17792
17873
  lastSbn: void 0,
17793
- discontinuity: false
17874
+ discontinuity: false,
17875
+ rapSsId: void 0
17794
17876
  };
17795
17877
  this.#streams.set(streamKey, stream);
17796
17878
  }
@@ -18153,6 +18235,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
18153
18235
  fecReleaseEarliestHeldAtMs(packetId, catalogTrackName) {
18154
18236
  return this.#fecSequencer?.earliestHeldArrivalMs(packetId, catalogTrackName);
18155
18237
  }
18238
+ /** See FecReleaseSequencer.rapAbove; false when no stream is FEC-gated. */
18239
+ fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18240
+ return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18241
+ }
18156
18242
  /** Re-evaluate held gaps after FEC block state changed. */
18157
18243
  pokeFecRelease(packetId, catalogTrackName) {
18158
18244
  if (!this.#fecSequencer) return;
@@ -19423,6 +19509,10 @@ var NO_BLOCK_SPAN_HORIZON = Object.freeze({
19423
19509
  reason: "no-block-span"
19424
19510
  });
19425
19511
  var DIRECT_RECOVERED_VIDEO_QUEUE_LIMIT = 512;
19512
+ var ASSIST_BLOCK_LIMIT = 64;
19513
+ var ASSIST_FAILURE_LEDGER_LIMIT = 4 * ASSIST_BLOCK_LIMIT;
19514
+ var ASSIST_FAILED_DECODES_MAX = 2;
19515
+ var assistKey = (ownerPacketId, catalogTrackName, blockStart) => `${ownerPacketId}/${catalogTrackName ?? ""}/${blockStart}`;
19426
19516
  var DIRECT_RECOVERED_AUDIO_QUEUE_LIMIT = 512;
19427
19517
  function sourceSymbolEvidence(packet, header, rapFlag, packetSequenceNumber) {
19428
19518
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
@@ -19447,11 +19537,19 @@ var MmtpRouter = class {
19447
19537
  #provenance = /* @__PURE__ */ new Map();
19448
19538
  #onFlowProtected = null;
19449
19539
  #unadmittedListedDrops = 0;
19540
+ #unlistedRepairSetAside = 0;
19541
+ #assistBlocks = /* @__PURE__ */ new Map();
19542
+ #assistFailures = /* @__PURE__ */ new Map();
19543
+ #scratchDecoderFactory = null;
19544
+ #unlistedAssistedRecoveries = 0;
19545
+ #unlistedAssistedRefusals = 0;
19450
19546
  /** The ingress a held datagram arrived with; the receiver returns the same bytes on release. */
19451
19547
  #heldIngress = /* @__PURE__ */ new WeakMap();
19452
19548
  #unicastRepair = false;
19453
19549
  /** How to route a held unicast (MoQ) datagram once a record admits it. */
19454
19550
  #heldReplay = /* @__PURE__ */ new WeakMap();
19551
+ /** When a held datagram was received: admitted later, it keeps that receipt time (fec-01 9). */
19552
+ #heldAt = /* @__PURE__ */ new WeakMap();
19455
19553
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
19456
19554
  #provenanceStreamFlow = /* @__PURE__ */ new Map();
19457
19555
  #unregisteredFlowDrops = 0;
@@ -19537,6 +19635,7 @@ var MmtpRouter = class {
19537
19635
  #onBlockFailed = null;
19538
19636
  /** Typed observer of every gap decision the release gate makes. */
19539
19637
  #onFrameGap;
19638
+ #fecRapObservers = /* @__PURE__ */ new Set();
19540
19639
  // Pokes requested while a packet is being processed are deferred to its
19541
19640
  // end: a synchronous recovery completes its block BEFORE routing the
19542
19641
  // recovered frames, and releasing a held gap in between would strand them.
@@ -20160,14 +20259,13 @@ var MmtpRouter = class {
20160
20259
  updateProvenanceFlowIngress(ingress) {
20161
20260
  const entry = this.#provenance.get(ingress.flow);
20162
20261
  if (!entry) return;
20262
+ const added = entry.protected ? ingress.tracks.filter(({ name, packetId }) => name && !entry.ingress.tracks.some((t) => t.name === name && t.packetId === packetId)) : [];
20263
+ const governed = added.map(({ packetId }) => [...this.#repairOwnersByPacketId.get(packetId) ?? [packetId]].some((owner) => this.#governs(owner)));
20163
20264
  this.#provenance.set(ingress.flow, { ...entry, ingress });
20164
- if (entry.protected) {
20165
- for (const { name, packetId } of ingress.tracks) {
20166
- if (name && !entry.ingress.tracks.some((t) => t.name === name && t.packetId === packetId)) {
20167
- this.#fecManager?.resetTrack?.(packetId, name);
20168
- }
20169
- }
20170
- }
20265
+ added.forEach(({ name, packetId }, i) => {
20266
+ if (governed[i]) for (const block of this.#assistBlocks.values()) block.pooled.clear();
20267
+ else this.#fecManager?.resetTrack?.(packetId, name);
20268
+ });
20171
20269
  }
20172
20270
  /**
20173
20271
  * Called once per protection of a flow: at the admission that makes this
@@ -20188,11 +20286,154 @@ var MmtpRouter = class {
20188
20286
  if (!entry) return;
20189
20287
  entry.receiver.release();
20190
20288
  entry.protected = false;
20289
+ this.#assistBlocks.clear();
20290
+ this.#assistFailures.clear();
20191
20291
  }
20192
20292
  /** MoQ packets of a track a protected flow lists, dropped on its unicast path: duplicate, overflow, or listed by more than one flow. */
20193
20293
  get unadmittedListedDropCount() {
20194
20294
  return this.#unadmittedListedDrops;
20195
20295
  }
20296
+ /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
20297
+ get unlistedRepairSetAsideCount() {
20298
+ return this.#unlistedRepairSetAside;
20299
+ }
20300
+ /** Governed blocks recovered with the help of unlisted repair (7.2.7 step 2). */
20301
+ get unlistedAssistedRecoveryCount() {
20302
+ return this.#unlistedAssistedRecoveries;
20303
+ }
20304
+ /** Unlisted-assisted decodes refused because two already failed for the block (7.2.7 step 2). */
20305
+ get unlistedAssistedRefusalCount() {
20306
+ return this.#unlistedAssistedRefusals;
20307
+ }
20308
+ /** Unlisted repair symbols pooled now, across every governed block (7.2.7 step 2). */
20309
+ get unlistedPoolSymbolCount() {
20310
+ let n = 0;
20311
+ for (const block of this.#assistBlocks.values()) n += block.pooled.size;
20312
+ return n;
20313
+ }
20314
+ /**
20315
+ * Wire the decoder an unlisted-assisted decode runs in: a fresh, configured
20316
+ * decoder of the owner's track, used once and discarded, never the live one.
20317
+ * Without it unlisted repair on a governed instance is set aside and dropped.
20318
+ */
20319
+ setScratchFecDecoderFactory(factory) {
20320
+ this.#scratchDecoderFactory = factory;
20321
+ if (!factory) {
20322
+ this.#assistBlocks.clear();
20323
+ this.#assistFailures.clear();
20324
+ }
20325
+ }
20326
+ /** Whether a protected flow lists `ownerPacketId`: its FEC instance is governed (7.2.7). */
20327
+ #governs(ownerPacketId) {
20328
+ for (const entry of this.#provenance.values()) {
20329
+ if (entry.protected && ingressHasPacketId(entry.ingress, ownerPacketId)) return true;
20330
+ }
20331
+ return false;
20332
+ }
20333
+ /**
20334
+ * A MoQ repair symbol no protected flow lists, owned by a source track one
20335
+ * does: its FEC instance is governed (7.2.7 step 2) and takes only admitted
20336
+ * symbols, so the symbol is set aside: pooled for an unlisted-assisted
20337
+ * decode of a block admitted repair already delimits, else dropped. It
20338
+ * never states a block, so the live locator and decoder are unchanged.
20339
+ * Un-listing needs no hook: an unprotected or released flow lists nothing.
20340
+ */
20341
+ #setAsideUnlistedRepair(ownerPacketId, catalogTrackName, repair) {
20342
+ if (!this.#governs(ownerPacketId)) return false;
20343
+ this.#unlistedRepairSetAside++;
20344
+ const key = assistKey(ownerPacketId, catalogTrackName, repair.ssStart);
20345
+ const block = this.#assistBlocks.get(key);
20346
+ if (block !== void 0 && block.ssbLength === repair.ssbLength && !block.repairs.has(repair.rsId) && block.pooled.size < block.ssbLength && repair.symbolData.byteLength === this.#symbolSizeForPacket(ownerPacketId) && this.#fecManager?.admitRepairBlockLength?.(ownerPacketId, repair.ssbLength, repair.rsbLength, repair.rsId) !== false) {
20347
+ block.pooled.set(repair.rsId, repair.symbolData);
20348
+ this.#tryAssistedDecode(key, block, ownerPacketId, catalogTrackName, repair.ssStart);
20349
+ }
20350
+ return true;
20351
+ }
20352
+ /**
20353
+ * An admitted repair placed a governed block (its SSB_length delimits it):
20354
+ * open the block's record, which the symbols its live decoder takes join.
20355
+ */
20356
+ #openAssistBlock(ownerPacketId, catalogTrackName, blockStart, ssbLength) {
20357
+ const key = assistKey(ownerPacketId, catalogTrackName, blockStart);
20358
+ if (!this.#scratchDecoderFactory || this.#assistBlocks.has(key) || !this.#governs(ownerPacketId)) return;
20359
+ this.#assistBlocks.set(key, { ssbLength, sources: /* @__PURE__ */ new Map(), repairs: /* @__PURE__ */ new Map(), pooled: /* @__PURE__ */ new Map() });
20360
+ for (const oldest of this.#assistBlocks.keys()) {
20361
+ if (this.#assistBlocks.size <= ASSIST_BLOCK_LIMIT) break;
20362
+ this.#assistBlocks.delete(oldest);
20363
+ }
20364
+ }
20365
+ /** A symbol fed to an open governed block's live decoder that did not recover it. */
20366
+ #noteAssistAdmitted(ownerPacketId, catalogTrackName, blockStart, symbol, data) {
20367
+ const key = assistKey(ownerPacketId, catalogTrackName, blockStart);
20368
+ const block = this.#assistBlocks.get(key);
20369
+ if (block === void 0) return;
20370
+ if ("rsId" in symbol) {
20371
+ block.repairs.set(symbol.rsId, data);
20372
+ block.pooled.delete(symbol.rsId);
20373
+ } else {
20374
+ block.sources.set(symbol.esi, data);
20375
+ }
20376
+ this.#tryAssistedDecode(key, block, ownerPacketId, catalogTrackName, blockStart);
20377
+ }
20378
+ /**
20379
+ * 7.2.7 step 2, phase two: a governed block its admitted symbols cannot
20380
+ * decode (the live decoder already had them all) is decoded in a scratch
20381
+ * decoder from its admitted symbols plus pooled unlisted repair, only as
20382
+ * many as close the shortfall. What it recovers is released only through
20383
+ * admission (#routeRecoveredBlock), so the live decoder is never touched and
20384
+ * a refused recovery leaves the block to fail at its FEC deadline. At most
20385
+ * two such decodes may fail per block; a third is refused.
20386
+ */
20387
+ #tryAssistedDecode(key, block, ownerPacketId, catalogTrackName, blockStart) {
20388
+ const fec = this.#fecManager;
20389
+ const admitted = block.sources.size + block.repairs.size;
20390
+ if (!fec || block.pooled.size === 0) return;
20391
+ if (admitted >= block.ssbLength || admitted + block.pooled.size < block.ssbLength) return;
20392
+ if (fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName)) {
20393
+ this.#assistBlocks.delete(key);
20394
+ return;
20395
+ }
20396
+ if ((this.#assistFailures.get(key) ?? 0) >= ASSIST_FAILED_DECODES_MAX) {
20397
+ this.#unlistedAssistedRefusals++;
20398
+ return;
20399
+ }
20400
+ const decoder = this.#scratchDecoderFactory?.(ownerPacketId, catalogTrackName);
20401
+ if (!decoder) return;
20402
+ let recovered = null;
20403
+ const fed = [];
20404
+ try {
20405
+ for (const [esi, data] of block.sources) decoder.add_source(serial32Add(blockStart, esi), data, 0);
20406
+ for (const [rsId, data] of block.repairs) {
20407
+ recovered ??= decoder.add_repair(blockStart, block.ssbLength, rsId, data, 0);
20408
+ }
20409
+ for (const [rsId, data] of block.pooled) {
20410
+ if (recovered || fed.length >= block.ssbLength - admitted) break;
20411
+ fed.push(rsId);
20412
+ recovered = decoder.add_repair(blockStart, block.ssbLength, rsId, data, 0);
20413
+ }
20414
+ } catch {
20415
+ recovered = null;
20416
+ } finally {
20417
+ decoder.free?.();
20418
+ }
20419
+ if (recovered && this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName, () => {
20420
+ fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
20421
+ fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
20422
+ fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
20423
+ })) {
20424
+ this.#unlistedAssistedRecoveries++;
20425
+ this.#assistBlocks.delete(key);
20426
+ return;
20427
+ }
20428
+ for (const rsId of fed) block.pooled.delete(rsId);
20429
+ const failed = (this.#assistFailures.get(key) ?? 0) + 1;
20430
+ this.#assistFailures.delete(key);
20431
+ this.#assistFailures.set(key, failed);
20432
+ for (const oldest of this.#assistFailures.keys()) {
20433
+ if (this.#assistFailures.size <= ASSIST_FAILURE_LEDGER_LIMIT) break;
20434
+ this.#assistFailures.delete(oldest);
20435
+ }
20436
+ }
20196
20437
  /**
20197
20438
  * The admission that makes this router protected under `flow` (7.2.7):
20198
20439
  * its FEC instances discard what they hold of the flow's listed tracks so
@@ -20237,6 +20478,7 @@ var MmtpRouter = class {
20237
20478
  if (verdict === "admitted") return "admitted";
20238
20479
  if (verdict === "held") {
20239
20480
  this.#heldReplay.set(packet, replay);
20481
+ this.#heldAt.set(packet, performance.now());
20240
20482
  return "held";
20241
20483
  }
20242
20484
  this.#unadmittedListedDrops++;
@@ -20255,9 +20497,14 @@ var MmtpRouter = class {
20255
20497
  this.#noteFlowAdmitted(flow);
20256
20498
  this.#withDeferredFecPokes(() => {
20257
20499
  for (const datagram of result.admitted) {
20258
- const replay = this.#heldReplay.get(datagram);
20259
- if (replay) replay();
20260
- else this.#processMMTP(datagram, "multicast", true, this.#heldIngress.get(datagram) ?? entry.ingress, false, true);
20500
+ const route = () => {
20501
+ const replay = this.#heldReplay.get(datagram);
20502
+ if (replay) replay();
20503
+ else this.#processMMTP(datagram, "multicast", true, this.#heldIngress.get(datagram) ?? entry.ingress, false, true);
20504
+ };
20505
+ const heldAt = this.#heldAt.get(datagram);
20506
+ if (heldAt !== void 0 && this.#fecManager?.withReceiptTime) this.#fecManager.withReceiptTime(heldAt, route);
20507
+ else route();
20261
20508
  }
20262
20509
  });
20263
20510
  }
@@ -20362,8 +20609,9 @@ var MmtpRouter = class {
20362
20609
  );
20363
20610
  }
20364
20611
  if (ownerPacketId != null && !admitted) {
20365
- const admit = this.#admitUnicast(ownerPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
20612
+ const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
20366
20613
  if (admit === "held" || admit === "dropped") return;
20614
+ if (admit === "unlisted" && this.#fecManager && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackName, parsed)) return;
20367
20615
  }
20368
20616
  if (ownerPacketId != null && this.#fecManager) {
20369
20617
  this.#moqRepairPidCounts[repairPacketId] = (this.#moqRepairPidCounts[repairPacketId] || 0) + 1;
@@ -20483,6 +20731,7 @@ var MmtpRouter = class {
20483
20731
  const placement = fec.placeIsoRepair(ownerPacketId, catalogTrackName, repair.ssStart, repair.ssbLength);
20484
20732
  if (placement.status !== "placed") return;
20485
20733
  const blockStart = placement.block.start;
20734
+ this.#openAssistBlock(ownerPacketId, catalogTrackName, blockStart, repair.ssbLength);
20486
20735
  if (placement.span !== void 0) {
20487
20736
  this.#replayIsoSources(ownerPacketId, catalogTrackName, placement.span.block.start, placement.span.placed);
20488
20737
  }
@@ -20513,6 +20762,8 @@ var MmtpRouter = class {
20513
20762
  fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
20514
20763
  fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
20515
20764
  });
20765
+ } else if (!recovered) {
20766
+ this.#noteAssistAdmitted(ownerPacketId, catalogTrackName, blockStart, { rsId: repair.rsId }, repair.symbolData);
20516
20767
  }
20517
20768
  }
20518
20769
  /**
@@ -20552,6 +20803,7 @@ var MmtpRouter = class {
20552
20803
  if (payload.oversized) continue;
20553
20804
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
20554
20805
  const recovered = fec.feedSourceSymbol(ownerPacketId, ssId, payload.symbolData, catalogTrackName);
20806
+ if (!recovered) this.#noteAssistAdmitted(ownerPacketId, catalogTrackName, blockStart, { esi }, payload.symbolData);
20555
20807
  if (!recovered || alreadyCompleted) continue;
20556
20808
  this.#routeRecoveredBlock(blockStart, recovered, ownerPacketId, catalogTrackName, () => {
20557
20809
  fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
@@ -20622,6 +20874,9 @@ var MmtpRouter = class {
20622
20874
  }
20623
20875
  }
20624
20876
  this.#parser.resetTrack(packetId, catalogTrackName);
20877
+ const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
20878
+ for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
20879
+ for (const key of this.#assistFailures.keys()) if (key.startsWith(assistPrefix)) this.#assistFailures.delete(key);
20625
20880
  const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
20626
20881
  this.#trackSynced.delete(streamKey);
20627
20882
  this.#droppedPreSyncVideo.delete(streamKey);
@@ -21039,6 +21294,24 @@ var MmtpRouter = class {
21039
21294
  fecReleaseEarliestHeldAtMs(packetId, catalogTrackName) {
21040
21295
  return this.#parser.fecReleaseEarliestHeldAtMs(packetId, catalogTrackName);
21041
21296
  }
21297
+ /**
21298
+ * Whether a complete RAP above SS_ID `ssId` entered this stream's FEC
21299
+ * release gate (see FecReleaseSequencer.rapAbove).
21300
+ */
21301
+ fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
21302
+ return this.#parser.fecReleaseRapAbove(packetId, catalogTrackName, ssId);
21303
+ }
21304
+ /**
21305
+ * Observe each complete RAP entering an FEC release gate, with the SS_ID
21306
+ * its frame completed in. Called synchronously from the frame push: an
21307
+ * observer that drives FEC state must defer that work.
21308
+ */
21309
+ addFecRapObserver(observer) {
21310
+ this.#fecRapObservers.add(observer);
21311
+ return () => {
21312
+ this.#fecRapObservers.delete(observer);
21313
+ };
21314
+ }
21042
21315
  #requestFecPoke(packetId, catalogTrackName) {
21043
21316
  if (this.#disposed) return;
21044
21317
  if (this.#fecPokeDepth > 0) {
@@ -21084,6 +21357,10 @@ var MmtpRouter = class {
21084
21357
  this.#onFrameGap?.(decision);
21085
21358
  return decision;
21086
21359
  },
21360
+ isRap: (data, meta) => this.#isRapForGap(data, meta),
21361
+ onRap: (packetId, catalogTrackName, ssId) => {
21362
+ for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
21363
+ },
21087
21364
  onReleased: (data, meta) => {
21088
21365
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
21089
21366
  const timing = meta.authoredTiming;
@@ -21263,7 +21540,10 @@ var MmtpRouter = class {
21263
21540
  if (verdict === "admitted") {
21264
21541
  this.#noteFlowAdmitted(ingress.flow);
21265
21542
  this.#processMMTP(packet, source, true, ingress, overlapCopy);
21266
- } else if (verdict === "held") this.#heldIngress.set(packet, ingress);
21543
+ } else if (verdict === "held") {
21544
+ this.#heldIngress.set(packet, ingress);
21545
+ this.#heldAt.set(packet, performance.now());
21546
+ }
21267
21547
  return;
21268
21548
  }
21269
21549
  if (source === "moq" && !manifestAdmitted) {
@@ -21279,6 +21559,7 @@ var MmtpRouter = class {
21279
21559
  const ownerPacketId = this.#resolveRepairOwnerPacketId(info.packetId, ingress);
21280
21560
  if (ownerPacketId != null && this.#fecManager) {
21281
21561
  if (hasAmbiguousCatalogTrackName(ingress, ownerPacketId)) return;
21562
+ if (source === "moq" && !manifestAdmitted && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
21282
21563
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
21283
21564
  const count = this.#repairPidCounts[info.packetId];
21284
21565
  if (count <= 2 || count % 500 === 0) {
@@ -21446,6 +21727,15 @@ var MmtpRouter = class {
21446
21727
  sourceFec.symbolData,
21447
21728
  catalogTrackName
21448
21729
  );
21730
+ if (!recovered) {
21731
+ this.#noteAssistAdmitted(
21732
+ info.packetId,
21733
+ catalogTrackName,
21734
+ sourceFec.sbn,
21735
+ { esi: serial32Distance(sourceFec.sbn, sourceFec.ssId) },
21736
+ sourceFec.symbolData
21737
+ );
21738
+ }
21449
21739
  if (recovered && !alreadyCompleted) {
21450
21740
  const fec = this.#fecManager;
21451
21741
  const sbn = sourceFec.sbn;
@@ -26519,6 +26809,8 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
26519
26809
  repairsSkippedPresentationDelayUnavailable: 0,
26520
26810
  repairsSkippedRangeNoAnchor: 0,
26521
26811
  repairsSkippedGroupCannotComplete: 0,
26812
+ repairsSkippedMootRap: 0,
26813
+ repairStops: { preempted: 0, reprioritized: 0, expired: 0, resolved: 0, reset: 0, disposed: 0, moot: 0 },
26522
26814
  lastRepairSkip: null,
26523
26815
  keyframeRepairFetchesSent: 0,
26524
26816
  rangeRepairFetchesSent: 0,
@@ -26605,7 +26897,17 @@ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
26605
26897
  "rtt-exceeds-budget",
26606
26898
  "presentation-delay-unavailable",
26607
26899
  "range-no-anchor",
26608
- "group-cannot-complete"
26900
+ "group-cannot-complete",
26901
+ "moot-rap"
26902
+ ]);
26903
+ var REPAIR_STOP_REASONS = /* @__PURE__ */ new Set([
26904
+ "preempted",
26905
+ "reprioritized",
26906
+ "expired",
26907
+ "resolved",
26908
+ "reset",
26909
+ "disposed",
26910
+ "moot"
26609
26911
  ]);
26610
26912
  var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
26611
26913
  var GAP_REASONS = {
@@ -26664,6 +26966,8 @@ function isRepairLifecycleEvent(value) {
26664
26966
  ]) && isRepairBlockIdentity(block) && (value["priority"] === 0 || value["priority"] === 1 || value["priority"] === 2) && isFiniteNumber(value["rttMs"]) && value["rttMs"] > 0 && isFiniteNumber(value["budgetMs"]) && value["budgetMs"] > value["rttMs"] && isNullableNonNegative(value["delayMs"]) && isNullableNonNegative(value["blockAgeMs"]) && value["delayMs"] === null === (value["blockAgeMs"] === null) && REPAIR_DEADLINE_BOUNDS.has(value["bound"]);
26665
26967
  case "repair-skipped":
26666
26968
  return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
26969
+ case "repair-stopped":
26970
+ return hasExactKeys(value, ["version", "type", "block", "reason"]) && isRepairBlockIdentity(block) && REPAIR_STOP_REASONS.has(value["reason"]);
26667
26971
  case "repair-priority": {
26668
26972
  const blockClass = value["blockClass"];
26669
26973
  const action = value["action"];
@@ -28073,6 +28377,14 @@ var MulticastManager = class {
28073
28377
  }
28074
28378
  }
28075
28379
  }
28380
+ const factory = typeof wasmDecoderSource === "function" ? wasmDecoderSource : null;
28381
+ const fecTracks = fecTrackIndexes.map((i) => catalog.tracks[i]);
28382
+ this.#router.setScratchFecDecoderFactory(factory && ((ownerPacketId, catalogTrackName) => {
28383
+ const track = fecTracks.find((t) => t.packetId === ownerPacketId && t.name === catalogTrackName);
28384
+ if (!track) return null;
28385
+ const decoder = factory(track);
28386
+ return [...fecDecoders.values()].includes(decoder) ? null : decoder;
28387
+ }));
28076
28388
  this.#switchingSets.clear();
28077
28389
  this.#repairPacketIds.clear();
28078
28390
  this.#router.clearRepairPacketIdOwners();
@@ -28246,6 +28558,7 @@ var MulticastManager = class {
28246
28558
  else if (reason === "rtt-exceeds-budget") stats.repairsSkippedRttExceedsBudget++;
28247
28559
  else if (reason === "range-no-anchor") stats.repairsSkippedRangeNoAnchor++;
28248
28560
  else if (reason === "group-cannot-complete") stats.repairsSkippedGroupCannotComplete++;
28561
+ else if (reason === "moot-rap") stats.repairsSkippedMootRap++;
28249
28562
  else stats.repairsSkippedPresentationDelayUnavailable++;
28250
28563
  stats.lastRepairSkip = {
28251
28564
  reason,
@@ -28306,6 +28619,27 @@ var MulticastManager = class {
28306
28619
  block: repairBlockIdentity(packetId, sbn, catalogTrackName)
28307
28620
  });
28308
28621
  }
28622
+ /** Record a running repair FETCH the scheduler stopped, and why. */
28623
+ noteRepairStopped(reason, sbn, packetId, catalogTrackName) {
28624
+ this.#statsFor(packetId, catalogTrackName).repairStops[reason]++;
28625
+ this.#emitRepairLifecycle({
28626
+ version: 2,
28627
+ type: "repair-stopped",
28628
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
28629
+ reason
28630
+ });
28631
+ }
28632
+ /**
28633
+ * Whether a complete RAP above SS_ID `ssId` reached the stream's in-order
28634
+ * release gate (draft-ramadan-moq-fec 11.4.2: repair below it is moot).
28635
+ */
28636
+ rapCompleteAbove(packetId, catalogTrackName, ssId) {
28637
+ return this.#router.fecReleaseRapAbove(packetId, catalogTrackName, ssId);
28638
+ }
28639
+ /** Observe each complete RAP reaching a release gate (synchronous: defer FEC work). */
28640
+ addRapCompleteObserver(observer) {
28641
+ return this.#router.addFecRapObserver(observer);
28642
+ }
28309
28643
  /** Catalog/reset epoch of a packet's streams; gap decisions carry it. */
28310
28644
  epochFor(packetId) {
28311
28645
  return this.#fec.epochFor(packetId);
@@ -28321,6 +28655,7 @@ var MulticastManager = class {
28321
28655
  if (stats.epoch !== this.#fec.epochFor(stats.packetId)) continue;
28322
28656
  out[key] = {
28323
28657
  ...stats,
28658
+ repairStops: { ...stats.repairStops },
28324
28659
  lastRepairSkip: stats.lastRepairSkip === null ? null : { ...stats.lastRepairSkip }
28325
28660
  };
28326
28661
  }
@@ -30684,6 +31019,34 @@ function wireRepairFetch(mc, opts) {
30684
31019
  run.stopped = reason;
30685
31020
  run.controller.abort();
30686
31021
  if (reason === "preempted") releaseHold(entry);
31022
+ mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
31023
+ };
31024
+ const lastSsId = (entry) => {
31025
+ if (entry.range) return entry.sbn + entry.range.holeLength - 1;
31026
+ const length = symbolCounts(entry.sbn, entry.packetId, entry.catalogTrackName)?.authoredLength;
31027
+ return length === void 0 ? void 0 : entry.sbn + length - 1;
31028
+ };
31029
+ const moot = (entry) => {
31030
+ if (entry.priority !== 0) return false;
31031
+ const last = lastSsId(entry);
31032
+ if (last === void 0) return false;
31033
+ try {
31034
+ return mc.rapCompleteAbove?.(entry.packetId, entry.catalogTrackName, last) === true;
31035
+ } catch {
31036
+ return false;
31037
+ }
31038
+ };
31039
+ const skip = (entry, reason, rttMs, budgetMs) => {
31040
+ retire(entry);
31041
+ releaseHold(entry);
31042
+ clearEntry(entry);
31043
+ mc.noteRepairSkipped(
31044
+ reason,
31045
+ { rttMs, budgetMs, priority: entry.priority },
31046
+ entry.sbn,
31047
+ entry.packetId,
31048
+ entry.catalogTrackName
31049
+ );
30687
31050
  };
30688
31051
  const readKeyframeBudget = (packetId, catalogTrackName) => {
30689
31052
  const reader = opts.keyframeRepairBudgetMs;
@@ -30708,31 +31071,22 @@ function wireRepairFetch(mc, opts) {
30708
31071
  const rttMs = readRtt();
30709
31072
  const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
30710
31073
  if (reason === null) return rttMs;
30711
- retire(entry);
30712
- releaseHold(entry);
30713
- clearEntry(entry);
30714
- mc.noteRepairSkipped(
30715
- reason,
30716
- { rttMs, budgetMs, priority: entry.priority },
30717
- entry.sbn,
30718
- entry.packetId,
30719
- entry.catalogTrackName
30720
- );
31074
+ skip(entry, reason, rttMs, budgetMs);
30721
31075
  return null;
30722
31076
  };
30723
31077
  const retire = (entry) => {
30724
31078
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
30725
31079
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
30726
31080
  };
30727
- const urgentOutstanding = () => {
31081
+ const outstandingBelow = (priority) => {
30728
31082
  for (const entry of entries.values()) {
30729
- if (entry.priority < 2) return true;
31083
+ if (entry.priority < priority) return true;
30730
31084
  }
30731
31085
  return false;
30732
31086
  };
30733
- const preemptDeltas = () => {
31087
+ const preemptBestEffort = () => {
30734
31088
  for (const entry of entries.values()) {
30735
- if (entry.priority !== 2 || !entry.running) continue;
31089
+ if (entry.priority === 0 || !entry.running) continue;
30736
31090
  stop(entry, "preempted");
30737
31091
  note("repair-preempted", entry);
30738
31092
  }
@@ -30752,8 +31106,13 @@ function wireRepairFetch(mc, opts) {
30752
31106
  };
30753
31107
  const start = (entry, counted = true) => {
30754
31108
  const now = performance.now();
31109
+ if (moot(entry)) {
31110
+ skip(entry, "moot-rap", readRtt(), entry.deadlineAt - now);
31111
+ return;
31112
+ }
30755
31113
  const rttMs = admit(entry, now);
30756
31114
  if (rttMs === null) return;
31115
+ if (entry.priority === 0) preemptBestEffort();
30757
31116
  if (counted) entry.attempts++;
30758
31117
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
30759
31118
  rttMs,
@@ -30797,9 +31156,13 @@ function wireRepairFetch(mc, opts) {
30797
31156
  queued.push(entry);
30798
31157
  }
30799
31158
  for (const entry of queued) {
30800
- if (entry.priority < 2) start(entry);
31159
+ if (entry.priority === 0) start(entry);
31160
+ }
31161
+ if (outstandingBelow(1)) return;
31162
+ for (const entry of queued) {
31163
+ if (entry.priority === 1) start(entry);
30801
31164
  }
30802
- if (urgentOutstanding()) return;
31165
+ if (outstandingBelow(2)) return;
30803
31166
  queued.filter((entry) => entry.priority === 2).sort((a, b) => a.deadlineAt - b.deadlineAt || a.order - b.order).forEach((entry) => start(entry));
30804
31167
  };
30805
31168
  const symbolCounts = (sbn, packetId, catalogTrackName) => {
@@ -30927,7 +31290,6 @@ function wireRepairFetch(mc, opts) {
30927
31290
  stop(entry2, "reprioritized");
30928
31291
  start(entry2, false);
30929
31292
  }
30930
- preemptDeltas();
30931
31293
  dispatch();
30932
31294
  return;
30933
31295
  }
@@ -31059,7 +31421,6 @@ function wireRepairFetch(mc, opts) {
31059
31421
  };
31060
31422
  entries.set(key, entry);
31061
31423
  noteBudget(entry, deadline.extensionMs);
31062
- if (entry.priority < 2) preemptDeltas();
31063
31424
  dispatch();
31064
31425
  });
31065
31426
  const rangeFor = (loss, repairTrack) => {
@@ -31135,15 +31496,28 @@ function wireRepairFetch(mc, opts) {
31135
31496
  }
31136
31497
  entries.set(entry.key, entry);
31137
31498
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
31138
- preemptDeltas();
31139
31499
  dispatch();
31140
31500
  });
31141
31501
  }
31502
+ const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
31503
+ queueMicrotask(() => {
31504
+ if (disposed) return;
31505
+ for (const entry of [...entries.values()]) {
31506
+ if (entry.packetId !== packetId || !entry.running || !moot(entry)) continue;
31507
+ stop(entry, "moot");
31508
+ retire(entry);
31509
+ releaseHold(entry);
31510
+ clearEntry(entry);
31511
+ }
31512
+ dispatch();
31513
+ });
31514
+ });
31142
31515
  return () => {
31143
31516
  disposed = true;
31144
31517
  mc.setUnicastRepair?.(false);
31145
31518
  removeResetObserver();
31146
31519
  removeLifecycleObserver();
31520
+ removeRapObserver?.();
31147
31521
  for (const entry of [...entries.values()]) {
31148
31522
  clearEntry(entry);
31149
31523
  if (entry.running) releaseHold(entry);