@blockcast/mmt-container 0.4.0-main.bbd83cb48eff → 0.4.0-main.c73a82eb3ed8

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 (77) hide show
  1. package/README.md +1 -1
  2. package/dist/browser-runtime.js +428 -14
  3. package/dist/browser-runtime.js.map +3 -3
  4. package/dist/carp-catalog.d.ts.map +1 -1
  5. package/dist/carp-catalog.js +4 -0
  6. package/dist/carp-catalog.js.map +2 -2
  7. package/dist/catalog-fec-params.d.ts.map +1 -1
  8. package/dist/catalog-fec-params.js +6 -3
  9. package/dist/catalog-fec-params.js.map +2 -2
  10. package/dist/catalog-network-source.js.map +1 -1
  11. package/dist/delivery-catalog.js +2 -2
  12. package/dist/delivery-catalog.js.map +3 -3
  13. package/dist/fec-manager.js.map +1 -1
  14. package/dist/fec-state.d.ts.map +1 -1
  15. package/dist/fec-state.js +14 -2
  16. package/dist/fec-state.js.map +3 -3
  17. package/dist/fec-worker-setup.js.map +1 -1
  18. package/dist/index.d.ts +2 -1
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +4 -0
  21. package/dist/index.js.map +2 -2
  22. package/dist/iso-block-locator.js.map +1 -1
  23. package/dist/mfu-reassembler.js.map +2 -2
  24. package/dist/mmtp-container-parser.js.map +2 -2
  25. package/dist/mmtp-container-parser.no-modules.js +521 -13
  26. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  27. package/dist/mmtp-decode-pipeline.js.map +2 -2
  28. package/dist/mmtp-fec-session.d.ts +156 -0
  29. package/dist/mmtp-fec-session.d.ts.map +1 -0
  30. package/dist/mmtp-fec-session.js +522 -0
  31. package/dist/mmtp-fec-session.js.map +7 -0
  32. package/dist/mmtp-router.d.ts.map +1 -1
  33. package/dist/mmtp-router.js +17 -0
  34. package/dist/mmtp-router.js.map +2 -2
  35. package/dist/multicast-input.js.map +1 -1
  36. package/dist/multicast-manager.d.ts +21 -2
  37. package/dist/multicast-manager.d.ts.map +1 -1
  38. package/dist/multicast-manager.js +52 -1
  39. package/dist/multicast-manager.js.map +2 -2
  40. package/dist/multicast-transport.js.map +2 -2
  41. package/dist/multicast-unwrap.js.map +2 -2
  42. package/dist/no-modules.d.ts +2 -0
  43. package/dist/no-modules.d.ts.map +1 -1
  44. package/dist/no-modules.js +473 -2
  45. package/dist/no-modules.js.map +4 -4
  46. package/dist/repair-fetch.d.ts +23 -1
  47. package/dist/repair-fetch.d.ts.map +1 -1
  48. package/dist/repair-fetch.js +35 -10
  49. package/dist/repair-fetch.js.map +2 -2
  50. package/dist/repair-layers.js.map +1 -1
  51. package/dist/signaling.d.ts +2 -2
  52. package/dist/signaling.d.ts.map +1 -1
  53. package/dist/signaling.js +3 -3
  54. package/dist/signaling.js.map +2 -2
  55. package/dist/timestamp-codec.js.map +2 -2
  56. package/dist/wasm-mfu-reassembler.js.map +1 -1
  57. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  58. package/package.json +5 -5
  59. package/schemas/catalog.schema.json +5 -0
  60. package/src/carp-catalog.ts +6 -0
  61. package/src/catalog-fec-params.ts +4 -1
  62. package/src/fec-state.ts +3 -2
  63. package/src/index.ts +16 -0
  64. package/src/mmtp-fec-session.ts +514 -0
  65. package/src/mmtp-router.ts +25 -0
  66. package/src/multicast-manager.ts +80 -2
  67. package/src/no-modules.ts +2 -0
  68. package/src/repair-fetch.ts +79 -14
  69. package/src/signaling.ts +2 -2
  70. package/test-vectors/catalog/README.md +8 -0
  71. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  72. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  73. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  74. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  75. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  76. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  77. package/test-vectors/catalog/section-codes.json +6 -0
package/README.md CHANGED
@@ -121,7 +121,7 @@ function parseAlFecMessage(buf: Uint8Array): AlFecMessage | null // every FEC
121
121
  function parseMoqRepairFrame(buf: Uint8Array): MoqRepairFrame
122
122
  ```
123
123
 
124
- Constants worth knowing: `MMTP_HEADER_SIZE = 12`, `MPU_HEADER_SIZE = 8`, `MFU_DU_HEADER_SIZE_TIMED = 14`, `PACKET_TYPE_MPU = 0x00`, `PACKET_TYPE_REPAIR = 0x03`, `ALFEC_MESSAGE_ID = 0x0203`, `FEC_CODE_RAPTORQ = 2`.
124
+ Constants worth knowing: `MMTP_HEADER_SIZE = 12`, `MPU_HEADER_SIZE = 8`, `MFU_DU_HEADER_SIZE_TIMED = 14`, `PACKET_TYPE_MPU = 0x00`, `PACKET_TYPE_REPAIR = 0x03`, `ALFEC_MESSAGE_ID = 0x0203`, `FEC_CODE_RAPTORQ = 3`, `FEC_CODE_REED_SOLOMON = 1`.
125
125
 
126
126
  ```ts
127
127
  import { parseMMTPHeader, extractMFUPayload } from "@blockcast/mmt-base"
@@ -1015,11 +1015,14 @@ function catalogFecAvailable(fec) {
1015
1015
  function isPositiveSafeInteger(value) {
1016
1016
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
1017
1017
  }
1018
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
1018
1019
  function catalogFecDeclaresUnconfigurableInstance(fec) {
1019
1020
  const block = recordOf(fec);
1020
1021
  if (block === void 0 || block["algorithm"] === "none")
1021
1022
  return false;
1022
- return !(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]));
1023
+ if (!(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"])))
1024
+ return true;
1025
+ return block["blockProfile"] === "iso-ssbg1-v1" && block["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE;
1023
1026
  }
1024
1027
 
1025
1028
  // src/mfu-reassembler.ts
@@ -6811,6 +6814,9 @@ function validateCmsfMmtpCatalog(value) {
6811
6814
  }
6812
6815
  }
6813
6816
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
6817
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
6818
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
6819
+ }
6814
6820
  }
6815
6821
  }
6816
6822
  const repairDescriptors = trackRecords.flatMap(
@@ -12544,7 +12550,7 @@ function isPositiveSafeInteger2(value) {
12544
12550
  function catalogDeclaresFec(fec) {
12545
12551
  const block = recordOf2(fec);
12546
12552
  if (block === void 0 || block["algorithm"] === "none") return false;
12547
- return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
12553
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
12548
12554
  }
12549
12555
  function requireBoolean(value, field) {
12550
12556
  if (typeof value !== "boolean") {
@@ -18977,6 +18983,12 @@ var MmtpRouter = class {
18977
18983
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
18978
18984
  */
18979
18985
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
18986
+ /**
18987
+ * Streams whose multicast leg delivered a RAP-flagged source packet that was
18988
+ * not parsed, typically because its overlap copy was parsed first
18989
+ * (BLO-49179). The next video keyframe emitted on the stream consumes it.
18990
+ */
18991
+ #multicastRapTwinByStream = /* @__PURE__ */ new Set();
18980
18992
  #lastDirectSourceVideoTsByStream = /* @__PURE__ */ new Map();
18981
18993
  #lastDirectEmittedVideoTsByStream = /* @__PURE__ */ new Map();
18982
18994
  #pendingDirectRecoveredVideoByStream = /* @__PURE__ */ new Map();
@@ -19110,6 +19122,12 @@ var MmtpRouter = class {
19110
19122
  ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName }
19111
19123
  };
19112
19124
  if (meta.source) frameMeta.source = meta.source;
19125
+ if (isVideo && frameMeta.keyframe) {
19126
+ const twinSeen = this.#multicastRapTwinByStream.delete(
19127
+ this.#mediaStreamKey(packetId, frameMeta.catalogTrackName)
19128
+ );
19129
+ if (twinSeen && frameMeta.source === "moq") frameMeta.source = "multicast";
19130
+ }
19113
19131
  if (meta.deliveryProvenance !== void 0)
19114
19132
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
19115
19133
  if (meta.recovered) frameMeta.recovered = true;
@@ -19932,6 +19950,7 @@ var MmtpRouter = class {
19932
19950
  this.#droppedPreSyncVideo.delete(streamKey);
19933
19951
  this.#latestVideoSeqByStream.delete(streamKey);
19934
19952
  this.#ssIdSeqOffsetByStream.delete(streamKey);
19953
+ this.#multicastRapTwinByStream.delete(streamKey);
19935
19954
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
19936
19955
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
19937
19956
  this.#pendingDirectRecoveredVideoByStream.delete(streamKey);
@@ -20730,6 +20749,10 @@ var MmtpRouter = class {
20730
20749
  // An FEC source frame is anchored by its own SS_ID (C.5.2).
20731
20750
  ...fecSource && fecPayloadId ? { fecSbn: fecPayloadId.ssId } : {}
20732
20751
  }, parsed);
20752
+ } else if (source === "multicast" && info.rapFlag) {
20753
+ this.#multicastRapTwinByStream.add(
20754
+ this.#mediaStreamKey(info.packetId, catalogTrackName)
20755
+ );
20733
20756
  }
20734
20757
  if (this.#classifyPacketId(info.packetId) === null) return;
20735
20758
  if (this.#fecManager && fecPayloadId && coords && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -23068,7 +23091,7 @@ function fecParams(catalog, track, rendition, fps, sampleRate) {
23068
23091
  throwRepairContractError(
23069
23092
  "track_fec",
23070
23093
  `${fecPath}.${kValid ? "symbolSize" : "sourceSymbols"}`,
23071
- "must be a positive integer"
23094
+ kValid && Number.isSafeInteger(fec.symbolSize) && (fec.symbolSize ?? 0) > 0 ? `iso-ssbg1-v1 symbolSize must be at least ${ISO_SSBG1_MIN_SYMBOL_SIZE}` : "must be a positive integer"
23072
23095
  );
23073
23096
  }
23074
23097
  const fecUnavailable = catalogFecUnavailable(fec, fecPath);
@@ -23253,6 +23276,12 @@ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
23253
23276
  "repair-priority-absent",
23254
23277
  "repair-priority-invalid"
23255
23278
  ]);
23279
+ var REPAIR_SKIP_REASONS = /* @__PURE__ */ new Set([
23280
+ "rtt-unmeasured",
23281
+ "rtt-exceeds-budget",
23282
+ "presentation-delay-unavailable"
23283
+ ]);
23284
+ var REPAIR_DEADLINE_BOUNDS = /* @__PURE__ */ new Set(["wait", "presentation", "keyframe", "retention"]);
23256
23285
  var GAP_REASONS = {
23257
23286
  "rap-lost": "stall",
23258
23287
  "rap-unknown": "stall",
@@ -23275,6 +23304,9 @@ function isSymbolCounts(value) {
23275
23304
  function isNullableNonNegative(value) {
23276
23305
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
23277
23306
  }
23307
+ function isFiniteNumber(value) {
23308
+ return typeof value === "number" && Number.isFinite(value);
23309
+ }
23278
23310
  function isRepairLifecycleEvent(value) {
23279
23311
  if (!isRecord(value) || value["version"] !== 2) return false;
23280
23312
  const block = value["block"];
@@ -23292,6 +23324,20 @@ function isRepairLifecycleEvent(value) {
23292
23324
  case "repair-preempted":
23293
23325
  case "repair-deferred":
23294
23326
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
23327
+ case "repair-sent":
23328
+ return hasExactKeys(value, [
23329
+ "version",
23330
+ "type",
23331
+ "block",
23332
+ "priority",
23333
+ "rttMs",
23334
+ "budgetMs",
23335
+ "delayMs",
23336
+ "blockAgeMs",
23337
+ "bound"
23338
+ ]) && 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"]);
23339
+ case "repair-skipped":
23340
+ return hasExactKeys(value, ["version", "type", "block", "reason", "rttMs", "budgetMs"]) && isRepairBlockIdentity(block) && REPAIR_SKIP_REASONS.has(value["reason"]) && isNullableNonNegative(value["rttMs"]) && isFiniteNumber(value["budgetMs"]);
23295
23341
  case "repair-priority": {
23296
23342
  const blockClass = value["blockClass"];
23297
23343
  const action = value["action"];
@@ -24794,8 +24840,19 @@ var MulticastManager = class {
24794
24840
  stats.keyframeBudgetHoldMs += extensionMs;
24795
24841
  }
24796
24842
  /** Record a repair FETCH the scheduler admitted and sent. */
24797
- noteRepairFetchSent(priority, _sbn, packetId, catalogTrackName) {
24843
+ noteRepairFetchSent(priority, sbn, packetId, catalogTrackName, measurement) {
24798
24844
  if (priority === 0) this.#statsFor(packetId, catalogTrackName).keyframeRepairFetchesSent++;
24845
+ this.#emitRepairLifecycle({
24846
+ version: 2,
24847
+ type: "repair-sent",
24848
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
24849
+ priority,
24850
+ rttMs: measurement.rttMs,
24851
+ budgetMs: measurement.budgetMs,
24852
+ delayMs: measurement.delayMs,
24853
+ blockAgeMs: measurement.blockAgeMs,
24854
+ bound: measurement.bound
24855
+ });
24799
24856
  }
24800
24857
  /**
24801
24858
  * Record a repair-scheduler decision about a delta block: preempted for
@@ -26708,6 +26765,337 @@ var CmcdProducer = class {
26708
26765
  }
26709
26766
  };
26710
26767
 
26768
+ // src/mmtp-fec-session.ts
26769
+ var PATH_BITS = { moq: 1, multicast: 2 };
26770
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
26771
+ var MmtpFecSession = class {
26772
+ #decoder;
26773
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
26774
+ #blocks = /* @__PURE__ */ new Map();
26775
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
26776
+ #settled = /* @__PURE__ */ new Set();
26777
+ /**
26778
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
26779
+ * received on, or 0 for one the session recovered.
26780
+ */
26781
+ #have = /* @__PURE__ */ new Map();
26782
+ #newest;
26783
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
26784
+ #prunedAt;
26785
+ #repairPacketId;
26786
+ #stats = {
26787
+ sourceSymbols: 0,
26788
+ repairSymbols: 0,
26789
+ blocksClean: 0,
26790
+ blocksRecovered: 0,
26791
+ blocksFailed: 0,
26792
+ blocksReleased: 0,
26793
+ packetsRecovered: 0,
26794
+ packetsLost: 0,
26795
+ dropped: {},
26796
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
26797
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
26798
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
26799
+ };
26800
+ /**
26801
+ * @throws when the catalog block lacks or misstates a field the session
26802
+ * needs: the block profile, K, T, `interleaveDepthMs` or
26803
+ * `reorderToleranceMs`. None is defaulted.
26804
+ */
26805
+ constructor(config) {
26806
+ const fec = config?.fec;
26807
+ if (!fec || typeof fec !== "object") {
26808
+ throw new Error("MmtpFecSession: the catalog fec block is required");
26809
+ }
26810
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
26811
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
26812
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
26813
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
26814
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
26815
+ this.retentionBlocks = deriveFecRetentionBlocks(
26816
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
26817
+ interleaveDepthMs
26818
+ );
26819
+ if (typeof config.Decoder !== "function") {
26820
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
26821
+ }
26822
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile);
26823
+ try {
26824
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
26825
+ } catch (error) {
26826
+ decoder.free();
26827
+ throw error;
26828
+ }
26829
+ this.#decoder = decoder;
26830
+ }
26831
+ /** True once release() ran. */
26832
+ get released() {
26833
+ return this.#decoder === null;
26834
+ }
26835
+ get stats() {
26836
+ return {
26837
+ ...this.#stats,
26838
+ dropped: { ...this.#stats.dropped },
26839
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
26840
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
26841
+ mixedPath: { ...this.#stats.mixedPath }
26842
+ };
26843
+ }
26844
+ /**
26845
+ * Feeds one received source packet: the MMTP packet without its four-byte
26846
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
26847
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
26848
+ * was received; a caller that only subscribes over MoQT can leave it out.
26849
+ *
26850
+ * @returns the protected packets of this packet's block that it recovered,
26851
+ * in SS_ID order, for the caller to feed to its parser with
26852
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
26853
+ */
26854
+ addSource(ssId, packet, path = "moq") {
26855
+ const decoder = this.#decoder;
26856
+ if (!decoder) return this.#drop("source:released");
26857
+ const pathBit = PATH_BITS[path];
26858
+ if (!pathBit) return this.#drop("source:unknown-path");
26859
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
26860
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
26861
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
26862
+ this.#have.set(ssId, pathBit);
26863
+ this.#stats.sourceSymbols++;
26864
+ this.#stats.sourceSymbolsByPath[path]++;
26865
+ this.#noteNewest(ssId);
26866
+ const start = this.#blockStartOf(ssId);
26867
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
26868
+ if (block) {
26869
+ block.received++;
26870
+ block.paths |= pathBit;
26871
+ }
26872
+ let output;
26873
+ try {
26874
+ output = decoder.add_source(ssId, packet, 0);
26875
+ } catch {
26876
+ this.#drop("source:decoder-refused");
26877
+ output = void 0;
26878
+ }
26879
+ const recovered = [];
26880
+ if (start !== void 0 && block) {
26881
+ if (output) {
26882
+ recovered.push(...this.#settleDecoded(start, block, output));
26883
+ } else if (block.received >= block.ssbLength) {
26884
+ this.#settleClean(start);
26885
+ }
26886
+ }
26887
+ this.#retireBehindHorizon();
26888
+ return recovered;
26889
+ }
26890
+ /**
26891
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
26892
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
26893
+ * repair packet fixes its packet ID and a packet of any other is refused.
26894
+ * `path` is where it was received, as for addSource().
26895
+ *
26896
+ * @returns the protected packets this repair symbol recovered, as for
26897
+ * addSource().
26898
+ */
26899
+ addRepair(packet, path = "moq") {
26900
+ const decoder = this.#decoder;
26901
+ if (!decoder) return this.#drop("repair:released");
26902
+ const pathBit = PATH_BITS[path];
26903
+ if (!pathBit) return this.#drop("repair:unknown-path");
26904
+ let header;
26905
+ try {
26906
+ header = parseMMTPHeader(packet);
26907
+ } catch {
26908
+ return this.#drop("repair:malformed");
26909
+ }
26910
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
26911
+ if (!frame) return this.#drop("repair:malformed");
26912
+ if (this.#repairPacketId === void 0) {
26913
+ this.#repairPacketId = frame.packetId;
26914
+ } else if (frame.packetId !== this.#repairPacketId) {
26915
+ return this.#drop("repair:foreign-packet-id");
26916
+ }
26917
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
26918
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
26919
+ const start = frame.ssStart;
26920
+ let block = this.#blocks.get(start);
26921
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
26922
+ if (!block) {
26923
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
26924
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
26925
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0 };
26926
+ this.#countHeld(start, block);
26927
+ this.#blocks.set(start, block);
26928
+ }
26929
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
26930
+ if (block.received >= block.ssbLength) {
26931
+ this.#settleClean(start);
26932
+ this.#retireBehindHorizon();
26933
+ return [];
26934
+ }
26935
+ let output;
26936
+ try {
26937
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
26938
+ } catch {
26939
+ return this.#drop("repair:decoder-refused");
26940
+ }
26941
+ this.#stats.repairSymbols++;
26942
+ this.#stats.repairSymbolsByPath[path]++;
26943
+ block.paths |= pathBit;
26944
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
26945
+ this.#retireBehindHorizon();
26946
+ return recovered;
26947
+ }
26948
+ /**
26949
+ * Frees the decoder and every block. Blocks still unsettled are counted as
26950
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
26951
+ * returns whether this call released anything.
26952
+ */
26953
+ release() {
26954
+ const decoder = this.#decoder;
26955
+ if (!decoder) return false;
26956
+ this.#decoder = null;
26957
+ this.#stats.blocksReleased += this.#blocks.size;
26958
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
26959
+ this.#blocks.clear();
26960
+ this.#settled.clear();
26961
+ this.#have.clear();
26962
+ decoder.free();
26963
+ return true;
26964
+ }
26965
+ #drop(reason) {
26966
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
26967
+ return [];
26968
+ }
26969
+ #noteNewest(ssId) {
26970
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
26971
+ }
26972
+ #blockStartOf(ssId) {
26973
+ for (const [start, block] of this.#blocks) {
26974
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
26975
+ }
26976
+ return void 0;
26977
+ }
26978
+ /** Counts the sources of a new block the parser already has, and their paths. */
26979
+ #countHeld(start, block) {
26980
+ for (let i = 0; i < block.ssbLength; i++) {
26981
+ const pathBit = this.#have.get(serial32Add(start, i));
26982
+ if (pathBit === void 0) continue;
26983
+ block.received++;
26984
+ block.paths |= pathBit;
26985
+ }
26986
+ }
26987
+ #noteMixed(block, outcome) {
26988
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
26989
+ }
26990
+ /** The decoder's own rule: more than its retention behind, counted from below. */
26991
+ #behindHorizon(start) {
26992
+ const newest = this.#newest;
26993
+ if (newest === void 0) return false;
26994
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
26995
+ }
26996
+ #settle(start) {
26997
+ this.#blocks.delete(start);
26998
+ this.#settled.add(start);
26999
+ }
27000
+ #settleClean(start) {
27001
+ const block = this.#blocks.get(start);
27002
+ if (!block) return;
27003
+ this.#settle(start);
27004
+ this.#stats.blocksClean++;
27005
+ this.#noteMixed(block, "clean");
27006
+ try {
27007
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
27008
+ } catch {
27009
+ }
27010
+ }
27011
+ /**
27012
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
27013
+ * concatenated: split by T, trim by each symbol's length field, and hand
27014
+ * back the packets the parser does not have yet.
27015
+ */
27016
+ #settleDecoded(start, block, output) {
27017
+ this.#settle(start);
27018
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
27019
+ this.#stats.blocksFailed++;
27020
+ this.#stats.packetsLost += block.ssbLength - block.received;
27021
+ this.#noteMixed(block, "failed");
27022
+ this.#drop("block:decoded-length");
27023
+ return [];
27024
+ }
27025
+ const recovered = [];
27026
+ let refused = 0;
27027
+ for (let i = 0; i < block.ssbLength; i++) {
27028
+ const ssId = serial32Add(start, i);
27029
+ if (this.#have.has(ssId)) continue;
27030
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
27031
+ const packet = trimSsbg1SourceSymbol(symbol);
27032
+ if (!packet) {
27033
+ refused++;
27034
+ continue;
27035
+ }
27036
+ this.#have.set(ssId, 0);
27037
+ recovered.push(packet.slice());
27038
+ }
27039
+ if (refused > 0) {
27040
+ this.#stats.blocksFailed++;
27041
+ this.#stats.packetsLost += refused;
27042
+ this.#noteMixed(block, "failed");
27043
+ this.#drop("block:bad-ssbg1-symbol");
27044
+ } else if (recovered.length === 0) {
27045
+ this.#stats.blocksClean++;
27046
+ this.#noteMixed(block, "clean");
27047
+ } else {
27048
+ this.#stats.blocksRecovered++;
27049
+ this.#noteMixed(block, "recovered");
27050
+ }
27051
+ this.#stats.packetsRecovered += recovered.length;
27052
+ return recovered;
27053
+ }
27054
+ /**
27055
+ * Retires every block, and every SS_ID the session remembers, that the
27056
+ * newest SS_ID has moved past the retention. An unsettled block retired
27057
+ * here is a failure: more of its sources were lost than its repair could
27058
+ * restore, or its repair never arrived.
27059
+ */
27060
+ #retireBehindHorizon() {
27061
+ const decoder = this.#decoder;
27062
+ const newest = this.#newest;
27063
+ if (!decoder || newest === void 0) return;
27064
+ try {
27065
+ decoder.cleanup_by_ss_start(newest);
27066
+ } catch {
27067
+ }
27068
+ for (const [start, block] of this.#blocks) {
27069
+ if (!this.#behindHorizon(start)) continue;
27070
+ this.#settle(start);
27071
+ this.#stats.blocksFailed++;
27072
+ this.#stats.packetsLost += block.ssbLength - block.received;
27073
+ this.#noteMixed(block, "failed");
27074
+ }
27075
+ const prunedAt = this.#prunedAt;
27076
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
27077
+ this.#prunedAt = newest;
27078
+ for (const ssId of this.#have.keys()) {
27079
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
27080
+ }
27081
+ for (const start of this.#settled) {
27082
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
27083
+ }
27084
+ }
27085
+ };
27086
+ function requirePositiveInteger(value, path) {
27087
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
27088
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
27089
+ }
27090
+ return value;
27091
+ }
27092
+ function requireNumber(value, path) {
27093
+ if (typeof value !== "number") {
27094
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
27095
+ }
27096
+ return value;
27097
+ }
27098
+
26711
27099
  // src/repair-fetch.ts
26712
27100
  var MOQT_PRIORITY_MAX = 255;
26713
27101
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
@@ -26788,7 +27176,7 @@ function wireRepairFetch(mc, opts) {
26788
27176
  const admit = (entry, now) => {
26789
27177
  const budgetMs = entry.deadlineAt - now;
26790
27178
  const rttMs = readRtt();
26791
- if (rttMs !== null && rttMs < budgetMs) return true;
27179
+ if (rttMs !== null && rttMs < budgetMs) return rttMs;
26792
27180
  retire(entry);
26793
27181
  releaseHold(entry);
26794
27182
  clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
@@ -26799,7 +27187,7 @@ function wireRepairFetch(mc, opts) {
26799
27187
  entry.packetId,
26800
27188
  entry.catalogTrackName
26801
27189
  );
26802
- return false;
27190
+ return null;
26803
27191
  };
26804
27192
  const retire = (entry) => {
26805
27193
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
@@ -26831,9 +27219,17 @@ function wireRepairFetch(mc, opts) {
26831
27219
  return derived.kind === "omit" ? { subscriberPriority: void 0 } : null;
26832
27220
  };
26833
27221
  const start = (entry, counted = true) => {
26834
- if (!admit(entry, performance.now())) return;
27222
+ const now = performance.now();
27223
+ const rttMs = admit(entry, now);
27224
+ if (rttMs === null) return;
26835
27225
  if (counted) entry.attempts++;
26836
- mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName);
27226
+ mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
27227
+ rttMs,
27228
+ budgetMs: entry.deadlineAt - now,
27229
+ delayMs: entry.delayMs,
27230
+ blockAgeMs: entry.anchorAt === null ? null : Math.max(0, now - entry.anchorAt),
27231
+ bound: entry.bound
27232
+ });
26837
27233
  const run = { controller: new AbortController(), stopped: null };
26838
27234
  entry.running = run;
26839
27235
  mc.fecManager.holdBlockForRepair(
@@ -26980,6 +27376,9 @@ function wireRepairFetch(mc, opts) {
26980
27376
  );
26981
27377
  if (promotedDeadline !== null && promotedDeadline.deadlineAt > entry2.deadlineAt) {
26982
27378
  entry2.deadlineAt = promotedDeadline.deadlineAt;
27379
+ entry2.anchorAt = promotedDeadline.anchorAt;
27380
+ entry2.delayMs = promotedDeadline.delayMs;
27381
+ entry2.bound = promotedDeadline.bound;
26983
27382
  noteBudget(entry2, promotedDeadline.extensionMs);
26984
27383
  }
26985
27384
  if (entry2.running) {
@@ -27005,7 +27404,9 @@ function wireRepairFetch(mc, opts) {
27005
27404
  if (waitMs === void 0) return null;
27006
27405
  const waitDeadlineAt = now + waitMs;
27007
27406
  const anchor = mc.fecManager.blockAnchorAtMs(sbn, packetId, catalogTrackName);
27008
- if (anchor === void 0) return { deadlineAt: waitDeadlineAt, extensionMs: 0 };
27407
+ if (anchor === void 0) {
27408
+ return { deadlineAt: waitDeadlineAt, extensionMs: 0, anchorAt: null, delayMs: null, bound: "wait" };
27409
+ }
27009
27410
  let delayMs;
27010
27411
  try {
27011
27412
  delayMs = opts.presentationDelayMs(packetId, catalogTrackName);
@@ -27016,12 +27417,21 @@ function wireRepairFetch(mc, opts) {
27016
27417
  const retentionMs = mc.fecManager.terminalRetentionMsForPacket(packetId);
27017
27418
  if (retentionMs === void 0) return null;
27018
27419
  const ceilingAt = Math.min(anchor, earliestGatedFrameAt(packetId, catalogTrackName) ?? anchor) + retentionMs;
27019
- const deadlineAt = (delay) => Math.max(waitDeadlineAt, Math.min(anchor + delay, ceilingAt));
27020
- const base = deadlineAt(delayMs);
27420
+ const at = (delay, delayBound) => {
27421
+ const presentAt = Math.min(anchor + delay, ceilingAt);
27422
+ if (waitDeadlineAt >= presentAt) return { deadlineAt: waitDeadlineAt, bound: "wait" };
27423
+ return { deadlineAt: presentAt, bound: anchor + delay <= ceilingAt ? delayBound : "retention" };
27424
+ };
27425
+ const base = at(delayMs, "presentation");
27021
27426
  const budgetMs = keyframeBudgetEligible(blockClass, classifierMode(packetId, catalogTrackName)) && groupCanComplete(sbn, packetId, catalogTrackName) ? readKeyframeBudget(packetId, catalogTrackName) : null;
27022
- if (budgetMs === null || budgetMs <= delayMs) return { deadlineAt: base, extensionMs: 0 };
27023
- const extended = deadlineAt(budgetMs);
27024
- return { deadlineAt: extended, extensionMs: extended - base };
27427
+ if (budgetMs === null || budgetMs <= delayMs) return { ...base, extensionMs: 0, anchorAt: anchor, delayMs };
27428
+ const extended = at(budgetMs, "keyframe");
27429
+ return {
27430
+ ...extended,
27431
+ extensionMs: extended.deadlineAt - base.deadlineAt,
27432
+ anchorAt: anchor,
27433
+ delayMs: budgetMs
27434
+ };
27025
27435
  };
27026
27436
  const earliestGatedFrameAt = (packetId, catalogTrackName) => {
27027
27437
  try {
@@ -27098,6 +27508,9 @@ function wireRepairFetch(mc, opts) {
27098
27508
  priority,
27099
27509
  subscriberPriority: wire.subscriberPriority,
27100
27510
  deadlineAt: deadline.deadlineAt,
27511
+ anchorAt: deadline.anchorAt,
27512
+ delayMs: deadline.delayMs,
27513
+ bound: deadline.bound,
27101
27514
  order: enqueueOrder++,
27102
27515
  attempts: 0,
27103
27516
  running: null
@@ -27153,6 +27566,7 @@ export {
27153
27566
  MfuReassemblyError,
27154
27567
  MmtpContainerParser,
27155
27568
  MmtpDecodePipeline,
27569
+ MmtpFecSession,
27156
27570
  MmtpRouter,
27157
27571
  MmtpToCmaf,
27158
27572
  MulticastContainerContractError,