@blockcast/mmt-container 2.2.0-main.e1bebe787bc9 → 2.2.0-main.ea9223dc11de

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 (124) hide show
  1. package/dist/block-policy.d.ts +33 -3
  2. package/dist/block-policy.d.ts.map +1 -1
  3. package/dist/block-policy.js +60 -24
  4. package/dist/block-policy.js.map +3 -3
  5. package/dist/browser-runtime.js +1034 -126
  6. package/dist/browser-runtime.js.map +4 -4
  7. package/dist/carp-catalog.d.ts +40 -1
  8. package/dist/carp-catalog.d.ts.map +1 -1
  9. package/dist/carp-catalog.js +163 -10
  10. package/dist/carp-catalog.js.map +4 -4
  11. package/dist/catalog-fec-params.js +34 -0
  12. package/dist/catalog-fec-params.js.map +3 -3
  13. package/dist/catalog-network-source.js +34 -0
  14. package/dist/catalog-network-source.js.map +3 -3
  15. package/dist/datagram-leg-deadline.d.ts +138 -0
  16. package/dist/datagram-leg-deadline.d.ts.map +1 -0
  17. package/dist/datagram-leg-deadline.js +229 -0
  18. package/dist/datagram-leg-deadline.js.map +7 -0
  19. package/dist/delivery-catalog.js +68 -0
  20. package/dist/delivery-catalog.js.map +4 -4
  21. package/dist/delta-fallback-config.js +34 -0
  22. package/dist/delta-fallback-config.js.map +3 -3
  23. package/dist/fec-manager.d.ts +117 -13
  24. package/dist/fec-manager.d.ts.map +1 -1
  25. package/dist/fec-manager.js +358 -42
  26. package/dist/fec-manager.js.map +4 -4
  27. package/dist/fec-state.d.ts +17 -5
  28. package/dist/fec-state.d.ts.map +1 -1
  29. package/dist/fec-state.js +36 -0
  30. package/dist/fec-state.js.map +3 -3
  31. package/dist/fec-worker-setup.js +34 -0
  32. package/dist/fec-worker-setup.js.map +3 -3
  33. package/dist/held-layer-admission.js +34 -0
  34. package/dist/held-layer-admission.js.map +3 -3
  35. package/dist/index.d.ts +6 -4
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +14 -0
  38. package/dist/index.js.map +2 -2
  39. package/dist/iso-block-locator.d.ts +16 -0
  40. package/dist/iso-block-locator.d.ts.map +1 -1
  41. package/dist/iso-block-locator.js +62 -0
  42. package/dist/iso-block-locator.js.map +3 -3
  43. package/dist/mfu-reassembler.js +34 -0
  44. package/dist/mfu-reassembler.js.map +3 -3
  45. package/dist/mmtp-container-parser.d.ts +6 -3
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +34 -0
  48. package/dist/mmtp-container-parser.js.map +3 -3
  49. package/dist/mmtp-container-parser.no-modules.js +167 -13
  50. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  51. package/dist/mmtp-decode-pipeline.js +34 -0
  52. package/dist/mmtp-decode-pipeline.js.map +3 -3
  53. package/dist/mmtp-fec-session.js +34 -0
  54. package/dist/mmtp-fec-session.js.map +3 -3
  55. package/dist/mmtp-mode-selection.d.ts +48 -0
  56. package/dist/mmtp-mode-selection.d.ts.map +1 -0
  57. package/dist/mmtp-mode-selection.js +79 -0
  58. package/dist/mmtp-mode-selection.js.map +7 -0
  59. package/dist/mmtp-router.d.ts +66 -10
  60. package/dist/mmtp-router.d.ts.map +1 -1
  61. package/dist/mmtp-router.js +204 -30
  62. package/dist/mmtp-router.js.map +4 -4
  63. package/dist/multicast-auth-catalog.js +42 -2
  64. package/dist/multicast-auth-catalog.js.map +3 -3
  65. package/dist/multicast-input.js +42 -2
  66. package/dist/multicast-input.js.map +3 -3
  67. package/dist/multicast-manager.d.ts +95 -1
  68. package/dist/multicast-manager.d.ts.map +1 -1
  69. package/dist/multicast-manager.js +613 -92
  70. package/dist/multicast-manager.js.map +4 -4
  71. package/dist/multicast-transport.js +68 -0
  72. package/dist/multicast-transport.js.map +4 -4
  73. package/dist/multicast-unwrap.js +34 -0
  74. package/dist/multicast-unwrap.js.map +3 -3
  75. package/dist/no-modules.js +167 -13
  76. package/dist/no-modules.js.map +4 -4
  77. package/dist/phase14-catalog-override.d.ts +2 -1
  78. package/dist/phase14-catalog-override.d.ts.map +1 -1
  79. package/dist/phase14-catalog-override.js +69 -2
  80. package/dist/phase14-catalog-override.js.map +3 -3
  81. package/dist/repair-fetch.d.ts.map +1 -1
  82. package/dist/repair-fetch.js +50 -0
  83. package/dist/repair-fetch.js.map +3 -3
  84. package/dist/repair-layer-subscriptions.js +34 -0
  85. package/dist/repair-layer-subscriptions.js.map +3 -3
  86. package/dist/signaling.js +34 -0
  87. package/dist/signaling.js.map +3 -3
  88. package/dist/timestamp-codec.js +34 -0
  89. package/dist/timestamp-codec.js.map +3 -3
  90. package/dist/wasm-mfu-reassembler.js +34 -0
  91. package/dist/wasm-mfu-reassembler.js.map +3 -3
  92. package/dist/wasm-mmtp-container-parser.js +34 -0
  93. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  94. package/package.json +5 -5
  95. package/schemas/catalog.schema.json +2 -2
  96. package/src/block-policy.ts +108 -31
  97. package/src/carp-catalog.ts +165 -5
  98. package/src/datagram-leg-deadline.ts +370 -0
  99. package/src/fec-manager.ts +345 -33
  100. package/src/fec-state.ts +21 -5
  101. package/src/index.ts +37 -0
  102. package/src/iso-block-locator.ts +34 -0
  103. package/src/mmtp-container-parser.ts +6 -4
  104. package/src/mmtp-mode-selection.ts +80 -0
  105. package/src/mmtp-router.ts +226 -45
  106. package/src/multicast-manager.ts +126 -0
  107. package/src/phase14-catalog-override.ts +14 -3
  108. package/src/repair-fetch.ts +23 -0
  109. package/test-vectors/catalog/README.md +36 -2
  110. package/test-vectors/catalog/mmtp-siblings/ambiguous-sibling.json +158 -0
  111. package/test-vectors/catalog/mmtp-siblings/ladder-bitrate-only.json +231 -0
  112. package/test-vectors/catalog/mmtp-siblings/ladder-four-rungs.json +405 -0
  113. package/test-vectors/catalog/mmtp-siblings/ladder-other-names.json +231 -0
  114. package/test-vectors/catalog/mmtp-siblings/mmtp-mode-unknown.json +143 -0
  115. package/test-vectors/catalog/mmtp-siblings/multicast-endpoint-lists-datagram-track.json +143 -0
  116. package/test-vectors/catalog/mmtp-siblings/no-sibling.json +79 -0
  117. package/test-vectors/catalog/mmtp-siblings/rendition-mismatch.json +143 -0
  118. package/test-vectors/catalog/mmtp-siblings/stream-delivery-mode.json +143 -0
  119. package/test-vectors/catalog/mmtp-siblings/timescale-mismatch.json +143 -0
  120. package/test-vectors/catalog/mmtp-siblings/valid-pair.json +142 -0
  121. package/test-vectors/catalog/section-codes.json +3 -3
  122. package/test-vectors/catalog-timing.json +742 -1
  123. package/test-vectors/catalog-validation.json +266 -7
  124. package/test-vectors/moq/mmtp-mode-selection.json +259 -0
@@ -852,14 +852,14 @@ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
852
852
  };
853
853
  }
854
854
  function extractRepairFecPayloadId(mmtpPacket) {
855
- const fields = readRepairFecPayloadIdFields(mmtpPacket);
856
- if (!fields)
855
+ const fields2 = readRepairFecPayloadIdFields(mmtpPacket);
856
+ if (!fields2)
857
857
  return null;
858
858
  return {
859
- ssStart: fields.ssStart,
860
- rsbLength: fields.rsbLength,
861
- rsId: fields.rsId,
862
- ssbLength: fields.ssbLength
859
+ ssStart: fields2.ssStart,
860
+ rsbLength: fields2.rsbLength,
861
+ rsId: fields2.rsId,
862
+ ssbLength: fields2.ssbLength
863
863
  };
864
864
  }
865
865
  function parseMoqRepairFrame(frame) {
@@ -1028,11 +1028,11 @@ function isoBlocksBehindLowerBound(a, b, kMax) {
1028
1028
  var DEC_OCTET = /^(?:0|[1-9]\d{0,2})$/;
1029
1029
  var H16 = /^[0-9A-Fa-f]{1,4}$/;
1030
1030
  function parseIpv4(text2) {
1031
- const fields = text2.split(".");
1032
- if (fields.length !== 4)
1031
+ const fields2 = text2.split(".");
1032
+ if (fields2.length !== 4)
1033
1033
  return void 0;
1034
1034
  const octets = [];
1035
- for (const field of fields) {
1035
+ for (const field of fields2) {
1036
1036
  if (!DEC_OCTET.test(field))
1037
1037
  return void 0;
1038
1038
  const value = Number(field);
@@ -1266,9 +1266,12 @@ function multicastCatalogIssues(catalog, options = {}) {
1266
1266
  return issues;
1267
1267
  const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
1268
1268
  const namespaceOf = /* @__PURE__ */ new Map();
1269
+ const modeOf = /* @__PURE__ */ new Map();
1269
1270
  for (const track of tracks) {
1270
- if (isObject(track) && typeof track["name"] === "string")
1271
- namespaceOf.set(track["name"], track["namespace"]);
1271
+ if (!isObject(track) || typeof track["name"] !== "string")
1272
+ continue;
1273
+ namespaceOf.set(track["name"], track["namespace"]);
1274
+ modeOf.set(track["name"], track["mmtpMode"]);
1272
1275
  }
1273
1276
  const tagged = catalog[CATALOG_NAMESPACE];
1274
1277
  let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
@@ -1338,6 +1341,9 @@ function multicastCatalogIssues(catalog, options = {}) {
1338
1341
  const name = isObject(ref) ? ref["name"] : ref;
1339
1342
  if (typeof name !== "string")
1340
1343
  continue;
1344
+ if (modeOf.get(name) === "mfu-datagram") {
1345
+ fail("multicast_track", `${at2}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} is an "mfu-datagram" track, which rides no multicast endpoint; list its "mfu" sibling (draft-ramadan-moq-mmt-02 4.3.1)`);
1346
+ }
1341
1347
  const namespace = namespaceOf.get(name);
1342
1348
  if (typeof namespace !== "string")
1343
1349
  continue;
@@ -1913,6 +1919,70 @@ function geometry(o, instanceId, symbolTrack) {
1913
1919
  });
1914
1920
  }
1915
1921
 
1922
+ // ../mmt-base/dist/mmtp-siblings.js
1923
+ var MMTP_MODES = Object.freeze(["mfu", "mfu-datagram"]);
1924
+ function isMmtpMode(value) {
1925
+ return typeof value === "string" && MMTP_MODES.includes(value);
1926
+ }
1927
+ var MMTP_SIBLING_HARD_FIELDS = Object.freeze([
1928
+ "namespace",
1929
+ "timescale",
1930
+ "presentationAnchorTicks",
1931
+ "groupDuration"
1932
+ ]);
1933
+ var MMTP_SIBLING_RENDITION_FIELDS = Object.freeze([
1934
+ "codec",
1935
+ "width",
1936
+ "height",
1937
+ "framerate",
1938
+ "bitrate",
1939
+ "samplerate",
1940
+ "channelConfig",
1941
+ "lang"
1942
+ ]);
1943
+ var MMTP_SIBLING_SOFT_FIELDS = Object.freeze([
1944
+ "initRef",
1945
+ "keyframeIntervalMs",
1946
+ "keyframeIntervalTicks",
1947
+ "isLive",
1948
+ "altGroup"
1949
+ ]);
1950
+ function fields(track) {
1951
+ return track;
1952
+ }
1953
+ function groupDurationTicks(track) {
1954
+ const ticks = track["groupDurationTicks"];
1955
+ if (Number.isSafeInteger(ticks))
1956
+ return BigInt(ticks);
1957
+ const ms = track["groupDurationMs"];
1958
+ const timescale = track["timescale"];
1959
+ if (!Number.isSafeInteger(ms) || !Number.isSafeInteger(timescale))
1960
+ return void 0;
1961
+ return BigInt(ms) * BigInt(timescale) / 1000n;
1962
+ }
1963
+ function identityEqual(a, b) {
1964
+ return a["namespace"] === b["namespace"] && a["timescale"] === b["timescale"] && a["presentationAnchorTicks"] === b["presentationAnchorTicks"] && groupDurationTicks(a) === groupDurationTicks(b) && MMTP_SIBLING_RENDITION_FIELDS.every((field) => a[field] === b[field]);
1965
+ }
1966
+ function isMmtpTrack(track, mode) {
1967
+ return typeof track === "object" && track !== null && !Array.isArray(track) && fields(track)["packaging"] === "mmtp" && fields(track)["mmtpMode"] === mode;
1968
+ }
1969
+ function mmtpSiblingCandidates(tracks, datagram) {
1970
+ const own = fields(datagram);
1971
+ return tracks.filter((track) => isMmtpTrack(track, "mfu") && identityEqual(fields(track), own));
1972
+ }
1973
+
1974
+ // ../mmt-base/dist/datagram-leg-size.js
1975
+ var DATAGRAM_LEG_UDP_FLOOR = 1200;
1976
+ var DATAGRAM_LEG_QUIC_WT_FRAMING = 48;
1977
+ var DATAGRAM_LEG_OBJECT_HEADER = 13;
1978
+ var DATAGRAM_LEG_RELAY_ROOM = 16;
1979
+ var DATAGRAM_LEG_REPAIR_OVERHEAD = 25;
1980
+ var DATAGRAM_LEG_DATAGRAM_MAX = DATAGRAM_LEG_UDP_FLOOR - DATAGRAM_LEG_QUIC_WT_FRAMING;
1981
+ var DATAGRAM_LEG_BODY_MAX = DATAGRAM_LEG_DATAGRAM_MAX - DATAGRAM_LEG_OBJECT_HEADER - DATAGRAM_LEG_RELAY_ROOM;
1982
+ function datagramLegObjectMax(symbolSize) {
1983
+ return DATAGRAM_LEG_OBJECT_HEADER + DATAGRAM_LEG_REPAIR_OVERHEAD + symbolSize;
1984
+ }
1985
+
1916
1986
  // src/mfu-reassembler.ts
1917
1987
  function fragmentProvenance(fragment) {
1918
1988
  if (fragment.deliveryProvenance !== void 0) return fragment.deliveryProvenance;
@@ -7241,13 +7311,13 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7241
7311
  }
7242
7312
  const timescale = track["timescale"];
7243
7313
  const groupDurationMs = track["groupDurationMs"];
7244
- const groupDurationTicks = track["groupDurationTicks"];
7314
+ const groupDurationTicks2 = track["groupDurationTicks"];
7245
7315
  const keyframeIntervalMs = track["keyframeIntervalMs"];
7246
7316
  const keyframeIntervalTicks = track["keyframeIntervalTicks"];
7247
7317
  if (groupDurationMs !== void 0 && !positiveInteger2(groupDurationMs)) {
7248
7318
  catalogError("track_group_duration_ms", `${path}.groupDurationMs`, "must be a positive integer");
7249
7319
  }
7250
- if (groupDurationTicks !== void 0 && !positiveInteger2(groupDurationTicks)) {
7320
+ if (groupDurationTicks2 !== void 0 && !positiveInteger2(groupDurationTicks2)) {
7251
7321
  catalogError("track_group_duration_ticks", `${path}.groupDurationTicks`, "must be a positive integer");
7252
7322
  }
7253
7323
  if (keyframeIntervalMs !== void 0 && !positiveNumber2(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
@@ -7262,20 +7332,17 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7262
7332
  catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7263
7333
  }
7264
7334
  if (packaging === "mmtp") {
7265
- if (track["mmtpMode"] !== "mfu") {
7266
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7267
- }
7268
7335
  if (!positiveInteger2(timescale)) {
7269
7336
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
7270
7337
  }
7271
- if (groupDurationMs === void 0 && groupDurationTicks === void 0) {
7338
+ if (groupDurationMs === void 0 && groupDurationTicks2 === void 0) {
7272
7339
  catalogError(
7273
7340
  "track_group_duration_ms",
7274
7341
  path,
7275
7342
  "groupDurationMs or groupDurationTicks must be a positive integer"
7276
7343
  );
7277
7344
  }
7278
- if (groupDurationTicks === void 0 && BigInt(groupDurationMs) * BigInt(timescale) % 1000n !== 0n) {
7345
+ if (groupDurationTicks2 === void 0 && BigInt(groupDurationMs) * BigInt(timescale) % 1000n !== 0n) {
7279
7346
  catalogError("track_group_duration_exact", `${path}.groupDurationMs`, "does not resolve to an exact integer tick count");
7280
7347
  }
7281
7348
  }
@@ -7357,8 +7424,103 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7357
7424
  }
7358
7425
  }
7359
7426
  validateArchive(catalog);
7427
+ dropRejectedMmtpTracks(catalog);
7360
7428
  return catalog;
7361
7429
  }
7430
+ function dropRejectedMmtpTracks(catalog) {
7431
+ const rejected = mmtpTrackIssues(catalog);
7432
+ if (rejected.length === 0) return;
7433
+ const tracks = catalog["tracks"];
7434
+ const rejectedIndexes = new Set(rejected.map((issue) => issue.index));
7435
+ const nameOf = (track) => track?.["name"];
7436
+ const mediaNames = new Set(tracks.filter((_, index) => !rejectedIndexes.has(index)).map(nameOf));
7437
+ const kept = tracks.filter((track, index) => {
7438
+ if (rejectedIndexes.has(index)) return false;
7439
+ const t = track;
7440
+ return !(t?.["packaging"] === "fec-repair" && typeof t["source"] === "string" && !mediaNames.has(t["source"]) && rejected.some((issue) => issue.name === t["source"]));
7441
+ });
7442
+ catalog["tracks"] = kept;
7443
+ const keptNames = new Set(kept.map(nameOf));
7444
+ const endpoints = catalog["multicast"]?.["endpoints"];
7445
+ if (Array.isArray(endpoints)) {
7446
+ for (const endpoint of endpoints) {
7447
+ const refs = endpoint?.["tracks"];
7448
+ if (!endpoint || !Array.isArray(refs)) continue;
7449
+ endpoint["tracks"] = refs.filter((ref) => keptNames.has(typeof ref === "object" ? nameOf(ref) : ref));
7450
+ }
7451
+ }
7452
+ Object.defineProperty(catalog, "rejectedTracks", { value: rejected, enumerable: false, configurable: true, writable: true });
7453
+ }
7454
+ function mmtpTrackIssues(catalog) {
7455
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) return [];
7456
+ const tracks = catalog["tracks"];
7457
+ if (!Array.isArray(tracks)) return [];
7458
+ const records = tracks.filter(
7459
+ (track) => typeof track === "object" && track !== null && !Array.isArray(track)
7460
+ );
7461
+ const issues = [];
7462
+ const streamPaths = (track) => {
7463
+ const name = typeof track["name"] === "string" ? track["name"] : "";
7464
+ return [track, ...records.filter((repair) => repair["packaging"] === "fec-repair" && repair["source"] === name)].filter((declaring) => declaring["deliveryMode"] === "stream").map((declaring) => `$.tracks[${tracks.indexOf(declaring)}]`);
7465
+ };
7466
+ const candidatesOf = /* @__PURE__ */ new Map();
7467
+ const mirrorsOf = /* @__PURE__ */ new Map();
7468
+ for (const track of records) {
7469
+ if (track["packaging"] !== "mmtp" || track["mmtpMode"] !== "mfu-datagram") continue;
7470
+ const candidates = mmtpSiblingCandidates(records, track);
7471
+ candidatesOf.set(track, candidates);
7472
+ if (candidates.length === 1 && streamPaths(track).length === 0) {
7473
+ mirrorsOf.set(candidates[0], [...mirrorsOf.get(candidates[0]) ?? [], track]);
7474
+ }
7475
+ }
7476
+ for (const track of records) {
7477
+ const index = tracks.indexOf(track);
7478
+ const path = `$.tracks[${index}]`;
7479
+ const name = typeof track["name"] === "string" ? track["name"] : "";
7480
+ if (track["packaging"] !== "mmtp") continue;
7481
+ const mode = track["mmtpMode"];
7482
+ if (!isMmtpMode(mode)) {
7483
+ issues.push({
7484
+ code: "track_mmtp_mode",
7485
+ path: `${path}.mmtpMode`,
7486
+ message: `mmtpMode must be "mfu" or "mfu-datagram", got ${JSON.stringify(mode)}; a subscriber rejects the track (draft-ramadan-moq-mmt-02 13.1)`,
7487
+ name,
7488
+ index
7489
+ });
7490
+ continue;
7491
+ }
7492
+ if (mode !== "mfu-datagram") continue;
7493
+ const conflict = (at2) => issues.push({
7494
+ code: "track_delivery_mode_conflict",
7495
+ path: `${at2}.deliveryMode`,
7496
+ message: `"mfu-datagram" track ${JSON.stringify(name)} and its repair tracks are sent as datagrams; deliveryMode "stream" would subscribe no repair (draft-ramadan-moq-mmt-02 4.3.1)`,
7497
+ name,
7498
+ index
7499
+ });
7500
+ const streams = streamPaths(track);
7501
+ for (const at2 of streams) conflict(at2);
7502
+ const candidates = candidatesOf.get(track) ?? [];
7503
+ const rivals = candidates.length === 1 && streams.length === 0 ? (mirrorsOf.get(candidates[0]) ?? []).filter((other) => other !== track) : [];
7504
+ if (rivals.length > 0) {
7505
+ issues.push({
7506
+ code: "track_mmtp_sibling",
7507
+ path,
7508
+ message: `"mfu-datagram" track ${JSON.stringify(name)} mirrors "mfu" track ${JSON.stringify(candidates[0]["name"])}, and so ${rivals.length === 1 ? "does" : "do"} ${rivals.map((rival) => JSON.stringify(rival["name"])).join(", ")}; the catalog does not say which one mirrors it, so a subscriber pairs none (draft-ramadan-moq-mmt-02 4.3.1)`,
7509
+ name,
7510
+ index
7511
+ });
7512
+ } else if (candidates.length !== 1) {
7513
+ issues.push({
7514
+ code: "track_mmtp_sibling",
7515
+ path,
7516
+ message: candidates.length === 0 ? `"mfu-datagram" track ${JSON.stringify(name)} mirrors no "mfu" track of its namespace with the same timescale, presentationAnchorTicks, group duration and rendition fields (${MMTP_SIBLING_RENDITION_FIELDS.join(", ")}), each equal or absent on both (draft-ramadan-moq-mmt-02 4.3.1, 13.1)` : `"mfu-datagram" track ${JSON.stringify(name)} could mirror ${candidates.length} "mfu" tracks (${candidates.map((c) => JSON.stringify(c["name"])).join(", ")}) that carry one description; the pair is ambiguous`,
7517
+ name,
7518
+ index
7519
+ });
7520
+ }
7521
+ }
7522
+ return issues;
7523
+ }
7362
7524
  function resolveGroupDurationTicks(timing, timescale) {
7363
7525
  if (!Number.isFinite(timescale) || !Number.isInteger(timescale) || timescale <= 0) {
7364
7526
  throw new Error(
@@ -7674,6 +7836,40 @@ var RUNTIME_FEC_RECEIVER2 = Object.freeze({
7674
7836
  overlays: true
7675
7837
  });
7676
7838
 
7839
+ // node_modules/@blockcast/mmt-base/dist/mmtp-siblings.js
7840
+ var MMTP_MODES2 = Object.freeze(["mfu", "mfu-datagram"]);
7841
+ var MMTP_SIBLING_HARD_FIELDS2 = Object.freeze([
7842
+ "namespace",
7843
+ "timescale",
7844
+ "presentationAnchorTicks",
7845
+ "groupDuration"
7846
+ ]);
7847
+ var MMTP_SIBLING_RENDITION_FIELDS2 = Object.freeze([
7848
+ "codec",
7849
+ "width",
7850
+ "height",
7851
+ "framerate",
7852
+ "bitrate",
7853
+ "samplerate",
7854
+ "channelConfig",
7855
+ "lang"
7856
+ ]);
7857
+ var MMTP_SIBLING_SOFT_FIELDS2 = Object.freeze([
7858
+ "initRef",
7859
+ "keyframeIntervalMs",
7860
+ "keyframeIntervalTicks",
7861
+ "isLive",
7862
+ "altGroup"
7863
+ ]);
7864
+
7865
+ // node_modules/@blockcast/mmt-base/dist/datagram-leg-size.js
7866
+ var DATAGRAM_LEG_UDP_FLOOR2 = 1200;
7867
+ var DATAGRAM_LEG_QUIC_WT_FRAMING2 = 48;
7868
+ var DATAGRAM_LEG_OBJECT_HEADER2 = 13;
7869
+ var DATAGRAM_LEG_RELAY_ROOM2 = 16;
7870
+ var DATAGRAM_LEG_DATAGRAM_MAX2 = DATAGRAM_LEG_UDP_FLOOR2 - DATAGRAM_LEG_QUIC_WT_FRAMING2;
7871
+ var DATAGRAM_LEG_BODY_MAX2 = DATAGRAM_LEG_DATAGRAM_MAX2 - DATAGRAM_LEG_OBJECT_HEADER2 - DATAGRAM_LEG_RELAY_ROOM2;
7872
+
7677
7873
  // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
7678
7874
  var DEFAULT_DWELL_MS = 3e3;
7679
7875
  var DEFAULT_JOIN_DEADLINE_MS = 5e3;
@@ -9843,11 +10039,15 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9843
10039
  if (ot.role !== void 0 && existing.role === void 0) existing.role = ot.role;
9844
10040
  if (existing.packaging === "mmtp") {
9845
10041
  const mode = existing.mmtpMode ?? ot.mmtpMode;
9846
- if (mode !== "mfu") {
10042
+ if (mode === void 0) {
9847
10043
  throw new Error(
9848
10044
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9849
10045
  );
9850
10046
  }
10047
+ if (!isMmtpMode(mode)) {
10048
+ console.warn(`[phase14-catalog-override] track "${ot.name}" has unknown mmtpMode ${JSON.stringify(mode)}; skipping the override`);
10049
+ continue;
10050
+ }
9851
10051
  existing.mmtpMode = mode;
9852
10052
  if (existing.timescale === void 0 && ot.timescale !== void 0) existing.timescale = ot.timescale;
9853
10053
  if (existing.groupDurationMs === void 0 && ot.groupDurationMs !== void 0) {
@@ -9884,11 +10084,15 @@ function mergeOverrideIntoCmsfTracks(tracks, override) {
9884
10084
  );
9885
10085
  }
9886
10086
  const mmtpMode = ot.mmtpMode;
9887
- if (packaging === "mmtp" && mmtpMode !== "mfu") {
10087
+ if (packaging === "mmtp" && mmtpMode === void 0) {
9888
10088
  throw new Error(
9889
10089
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid mmtpMode`
9890
10090
  );
9891
10091
  }
10092
+ if (packaging === "mmtp" && !isMmtpMode(mmtpMode)) {
10093
+ console.warn(`[phase14-catalog-override] track "${ot.name}" has unknown mmtpMode ${JSON.stringify(mmtpMode)}; skipping the track`);
10094
+ continue;
10095
+ }
9892
10096
  if (packaging === "mmtp" && !isPositiveInteger(ot.timescale)) {
9893
10097
  throw new Error(
9894
10098
  `[phase14-catalog-override] track "${ot.name}" has packaging='mmtp' but no valid timescale`
@@ -13222,6 +13426,34 @@ var IsoBlockLocator = class _IsoBlockLocator {
13222
13426
  isHeld(ssId) {
13223
13427
  return this.#held.has(ssId);
13224
13428
  }
13429
+ /** The payload held unplaced for `ssId`, if any. */
13430
+ heldSource(ssId) {
13431
+ return this.#held.get(ssId);
13432
+ }
13433
+ /**
13434
+ * The SS_IDs strictly between `a` and `b` that no repair has delimited a
13435
+ * block of yet: those from the coverage end on, or all of them before the
13436
+ * first repair. `missing` is the highest of them no source is held for;
13437
+ * absent, every one of them arrived (C.5.2: SS_IDs are consecutive). Null
13438
+ * when none lies past coverage. `flagged` is whether a source held among
13439
+ * them satisfies `flag` (a RAP fragment, say): the held packets read as
13440
+ * fec-multicast-00 Block Classification item 1 reads bounding packets.
13441
+ */
13442
+ undelimitedBetween(a, b, flag) {
13443
+ if (!serial32Precedes(a, b) || serial32Distance(a, b) <= 1) return null;
13444
+ const first = a + 1 >>> 0;
13445
+ const end = this.#coverageEnd;
13446
+ const start = end !== void 0 && serial32Precedes(first, end) ? end : first;
13447
+ if (!serial32Precedes(start, b)) return null;
13448
+ const length = serial32Distance(start, b);
13449
+ const missing = this.#highestMissing(start, length);
13450
+ let flagged = false;
13451
+ for (let i = 0; flag !== void 0 && !flagged && i < length; i++) {
13452
+ const payload = this.#held.get(serial32Add(start, i));
13453
+ flagged = payload !== void 0 && flag(payload);
13454
+ }
13455
+ return missing === void 0 ? { start, flagged } : { start, missing, flagged };
13456
+ }
13225
13457
  /**
13226
13458
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13227
13459
  * block states its range and places every held source in it; later repair
@@ -13450,6 +13682,7 @@ function resolveFecState(evidence) {
13450
13682
  const catalogFec = requireBoolean(evidence.catalogFec, "catalogFec");
13451
13683
  const bridgeAvailable = requireBoolean(evidence.bridgeAvailable, "bridgeAvailable");
13452
13684
  const multicastLegJoined = requireBoolean(evidence.multicastLegJoined, "multicastLegJoined");
13685
+ const datagramLegJoined = evidence.datagramLegJoined === void 0 ? false : requireBoolean(evidence.datagramLegJoined, "datagramLegJoined");
13453
13686
  const { transportPolicy, stats } = evidence;
13454
13687
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
13455
13688
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
@@ -13458,6 +13691,7 @@ function resolveFecState(evidence) {
13458
13691
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
13459
13692
  }
13460
13693
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
13694
+ if (datagramLegJoined) return { ...stats ?? {}, state: "active" };
13461
13695
  if (transportPolicy === "moq-only") return INACTIVE["reliable-moq"];
13462
13696
  if (!bridgeAvailable) return INACTIVE["no-multicast-bridge"];
13463
13697
  if (transportPolicy === "multicast-only" || multicastLegJoined) {
@@ -13498,31 +13732,26 @@ function deriveBlockClassifierGeometry(input) {
13498
13732
  );
13499
13733
  }
13500
13734
  if (input.trackKind === "audio") return { trackKind: "audio" };
13501
- if (!isPositiveFinite(input.framerate)) {
13502
- return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
13503
- }
13504
- const framerate = input.framerate;
13505
13735
  let keyframeInterval;
13506
13736
  if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
13507
13737
  keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
13508
13738
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
13509
13739
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
13510
- } else {
13511
- return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
13512
13740
  }
13741
+ const protect = (reason) => ({
13742
+ trackKind: "video",
13743
+ mode: "all-protected",
13744
+ reason,
13745
+ ...keyframeInterval === void 0 ? {} : { keyframeInterval }
13746
+ });
13747
+ if (!isPositiveFinite(input.framerate)) return protect("framerate-absent");
13748
+ const framerate = input.framerate;
13749
+ if (keyframeInterval === void 0) return protect("keyframe-cadence-absent");
13513
13750
  const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
13514
- if (gopFrames === null) {
13515
- return {
13516
- trackKind: "video",
13517
- mode: "all-protected",
13518
- reason: "keyframe-interval-not-integral"
13519
- };
13520
- }
13751
+ if (gopFrames === null) return protect("keyframe-interval-not-integral");
13521
13752
  const frameDurationMs = 1e3 / framerate;
13522
13753
  const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
13523
- if (interleaveUnits >= gopFrames) {
13524
- return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
13525
- }
13754
+ if (interleaveUnits >= gopFrames) return protect("block-spans-gop");
13526
13755
  return {
13527
13756
  trackKind: "video",
13528
13757
  mode: "classifying",
@@ -13533,7 +13762,7 @@ function deriveBlockClassifierGeometry(input) {
13533
13762
  };
13534
13763
  }
13535
13764
  function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13536
- if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return null;
13765
+ if (geometry2.trackKind !== "video" || geometry2.keyframeInterval === void 0) return null;
13537
13766
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
13538
13767
  const { ticks, timescale } = geometry2.keyframeInterval;
13539
13768
  if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
@@ -13542,9 +13771,14 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13542
13771
  if (scaled % divisor !== 0n) return null;
13543
13772
  return scaled / divisor;
13544
13773
  }
13774
+ function keyframeInstantBetween(start, interval, from, to) {
13775
+ const k = from >= start ? (from - start) / interval + 1n : 1n;
13776
+ return start + k * interval <= to;
13777
+ }
13545
13778
  function compareDataUnitStarts(a, b) {
13546
13779
  return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
13547
13780
  }
13781
+ var LATE_RAP_MAX_MPUS_BACK = 64;
13548
13782
  var UNPLACED = { rapNotMpuStart: false };
13549
13783
  var BlockClassifier = class {
13550
13784
  #geometry;
@@ -13585,6 +13819,7 @@ var BlockClassifier = class {
13585
13819
  #lastAnchor = null;
13586
13820
  /** Two anchors were exactly G fragments per MPU apart. */
13587
13821
  #fragmentsProven = false;
13822
+ /** The first RAP released of the latest MPU a RAP was released in, recorded in every mode. */
13588
13823
  #lastRap = null;
13589
13824
  constructor(geometry2) {
13590
13825
  this.#geometry = geometry2;
@@ -13655,6 +13890,7 @@ var BlockClassifier = class {
13655
13890
  noteSourceDiscontinuity() {
13656
13891
  this.#clearContiguityLedger();
13657
13892
  this.#clearMpuLayout();
13893
+ this.#lastRap = null;
13658
13894
  }
13659
13895
  /** Register a block that exists without evidence (a vanished block). */
13660
13896
  touch(sbn) {
@@ -13707,18 +13943,35 @@ var BlockClassifier = class {
13707
13943
  * RAP-bearing block is the one a wrong G calls delta), because the next
13708
13944
  * released RAP then belongs to m+2. Every MPU is one interval long, so the
13709
13945
  * span to any later released RAP proves or refutes all MPUs in between.
13710
- */
13711
- noteReleasedRap(mpu, presentationTime, mediaTimescale) {
13712
- if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
13713
- return [];
13714
- }
13715
- const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13716
- if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
13946
+ *
13947
+ * In every mode it keeps each MPU's first released RAP, with its decode
13948
+ * time, as the start keyframeFreeBetween measures the catalog interval
13949
+ * from, and a second RAP released inside one MPU refutes `mpuBoundsRaps`
13950
+ * when it lies off the catalog lattice (not a whole number of intervals
13951
+ * after the first; draft-ramadan-moq-mmt-02 4.4.3 binds every keyframe to
13952
+ * it): with no repair, released RAPs are the only evidence of where they
13953
+ * lie. Without a usable interval, or a decode time on either, any second
13954
+ * RAP with another presentation time refutes.
13955
+ */
13956
+ noteReleasedRap(mpu, presentationTime, mediaTimescale, decodeTime) {
13957
+ if (this.#geometry.trackKind === "audio") return [];
13717
13958
  const previous = this.#lastRap;
13718
13959
  if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
13960
+ if (presentationTime === previous.presentationTime) return [];
13961
+ const interval2 = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13962
+ if (interval2 === null || decodeTime === void 0 || previous.decodeTime === void 0 || (decodeTime - previous.decodeTime) % interval2 !== 0n) {
13963
+ this.#mpuBoundsRaps = false;
13964
+ }
13719
13965
  return [];
13720
13966
  }
13721
- this.#lastRap = { mpu, presentationTime, mediaTimescale };
13967
+ if (previous !== null && previous.mediaTimescale === mediaTimescale) {
13968
+ const back = previous.mpu - mpu >>> 0;
13969
+ if (back !== 0 && back <= LATE_RAP_MAX_MPUS_BACK && presentationTime < previous.presentationTime) return [];
13970
+ }
13971
+ this.#lastRap = { mpu, presentationTime, mediaTimescale, ...decodeTime === void 0 ? {} : { decodeTime } };
13972
+ if (this.#mode === "all-protected") return [];
13973
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13974
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
13722
13975
  if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
13723
13976
  return [];
13724
13977
  }
@@ -13727,6 +13980,22 @@ var BlockClassifier = class {
13727
13980
  }
13728
13981
  return this.#disable("rap-spacing-mismatch");
13729
13982
  }
13983
+ /**
13984
+ * Whether a gap inside MPU `mpu`, between the decode times `from` and `to`
13985
+ * of the frames on either side, holds no keyframe: MPU boundaries still
13986
+ * bound RAPs, the catalog states an interval exact in this timescale, and
13987
+ * none of its instants after the MPU's first released RAP lies in
13988
+ * `(from, to]` (fec-multicast-00 Block Classification item 3). Anything
13989
+ * unknown counts as a keyframe.
13990
+ */
13991
+ keyframeFreeBetween(mpu, from, to, mediaTimescale) {
13992
+ const rap = this.#lastRap;
13993
+ if (!this.#mpuBoundsRaps || rap?.mpu !== mpu || rap.mediaTimescale !== mediaTimescale || rap.decodeTime === void 0) {
13994
+ return false;
13995
+ }
13996
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
13997
+ return interval !== null && !keyframeInstantBetween(rap.decodeTime, interval, from, to);
13998
+ }
13730
13999
  #blockFor(sbn) {
13731
14000
  let block = this.#blocks.get(sbn);
13732
14001
  if (!block) {
@@ -14178,7 +14447,12 @@ var FECManager = class _FECManager {
14178
14447
  this.#repairHoldUntilMs = /* @__PURE__ */ new Map();
14179
14448
  // Receiver-measured multicast delivery gap: the late-symbol wait's jitter
14180
14449
  // term (see DeliveryGapEstimator for the statistic and why).
14181
- this.#deliveryGaps = new DeliveryGapEstimator();
14450
+ // One estimator per lossy path, so a hybrid session never lets one leg's
14451
+ // stall widen the other's wait; the wait reads the larger peak.
14452
+ this.#deliveryGaps = {
14453
+ multicast: new DeliveryGapEstimator(),
14454
+ "moq-datagram": new DeliveryGapEstimator()
14455
+ };
14182
14456
  this.#lifecycleTrace = [];
14183
14457
  // Worker-backed timeouts enqueue cleanup behind all prior symbol messages.
14184
14458
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
@@ -14370,6 +14644,14 @@ var FECManager = class _FECManager {
14370
14644
  // iso-ssbg1-v1 block location per stream (streamKey). A source belongs to a
14371
14645
  // block only once a repair symbol stated the block's (SS_Start, SSB_length).
14372
14646
  this.#isoLocators = /* @__PURE__ */ new Map();
14647
+ // The ts of the run behind the gap the release gate last asked about, per
14648
+ // stream (isoRepairlessWaitMs), keyed on the frame before the gap: kept, as
14649
+ // the source it came from may retire before the run's deadline, and the
14650
+ // earliest found wins, so a late frame that becomes the head restarts
14651
+ // nothing. It stays until the next run gap: a source discontinuity drops
14652
+ // it, and one older than twice the hold ceiling is not this gap's.
14653
+ // `counted` once the deadline passed (onUndelimitedRunGap).
14654
+ this.#runAnchors = /* @__PURE__ */ new Map();
14373
14655
  this.#deferIsoGaps = false;
14374
14656
  this.#isoRepairRefusedCount = 0;
14375
14657
  this.#isoSourceOversizeCount = 0;
@@ -14406,6 +14688,7 @@ var FECManager = class _FECManager {
14406
14688
  this.#decoderUnavailableEvents = 0;
14407
14689
  this.#repairSymbolSizeMismatchCount = 0;
14408
14690
  this.#unlistedRepairTrackRefusals = 0;
14691
+ this.#unresolvedRepairOwnerDrops = { unregistered: 0, ownerAbsent: 0, ownerAmbiguous: 0 };
14409
14692
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
14410
14693
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
14411
14694
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
@@ -14465,6 +14748,8 @@ var FECManager = class _FECManager {
14465
14748
  this.onBlockResolved = null;
14466
14749
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14467
14750
  this.onSourceDiscontinuity = null;
14751
+ /** The FEC deadline of a run no repair delimited passed, releasing the gap behind it (once per gap). */
14752
+ this.onUndelimitedRunGap = null;
14468
14753
  /**
14469
14754
  * The span and tolerance the catalog states for a keyframe overlay
14470
14755
  * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
@@ -14565,6 +14850,7 @@ var FECManager = class _FECManager {
14565
14850
  #highestSbn;
14566
14851
  #sourceFrontiers;
14567
14852
  #isoLocators;
14853
+ #runAnchors;
14568
14854
  #deferIsoGaps;
14569
14855
  #isoRepairRefusedCount;
14570
14856
  #isoSourceOversizeCount;
@@ -14580,6 +14866,7 @@ var FECManager = class _FECManager {
14580
14866
  #decoderUnavailableEvents;
14581
14867
  #repairSymbolSizeMismatchCount;
14582
14868
  #unlistedRepairTrackRefusals;
14869
+ #unresolvedRepairOwnerDrops;
14583
14870
  #onUndelimitedLoss;
14584
14871
  #onIsoHoleExpired;
14585
14872
  #encodeTrackName(catalogTrackName) {
@@ -15229,6 +15516,7 @@ var FECManager = class _FECManager {
15229
15516
  const discontinuity = () => {
15230
15517
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
15231
15518
  this.#noSpanRaps.delete(streamKey);
15519
+ this.#runAnchors.delete(streamKey);
15232
15520
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
15233
15521
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
15234
15522
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -15399,7 +15687,7 @@ var FECManager = class _FECManager {
15399
15687
  consider(geometry2, this.#parseStreamKey(streamKey).packetId);
15400
15688
  }
15401
15689
  for (const [packetId, config] of this.#trackConfigs) consider(config.geometry, packetId);
15402
- this.#deliveryGaps.setWindowMs(windowMs);
15690
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.setWindowMs(windowMs);
15403
15691
  }
15404
15692
  /**
15405
15693
  * The multicast late-symbol wait: the block span plus the larger of the
@@ -15412,14 +15700,14 @@ var FECManager = class _FECManager {
15412
15700
  * stream order and never feeds the estimator.
15413
15701
  */
15414
15702
  #multicastWaitMs(config) {
15415
- return this.#waitForGapMs(config, this.#deliveryGaps.peakGapMs(performance.now()));
15703
+ return this.#waitForGapMs(config, this.#peakDeliveryGapMs());
15416
15704
  }
15417
15705
  /**
15418
15706
  * The widest #multicastWaitMs can become: the estimator reports at most its
15419
15707
  * catalog window, so this is a catalog quantity that no measurement moves.
15420
15708
  */
15421
15709
  #maxMulticastWaitMs(config) {
15422
- return this.#waitForGapMs(config, this.#deliveryGaps.windowMs ?? 0);
15710
+ return this.#waitForGapMs(config, this.#deliveryGaps.multicast.windowMs ?? 0);
15423
15711
  }
15424
15712
  #waitForGapMs(config, gapMs) {
15425
15713
  if (!(gapMs > 0) || !(config.interleaveDepthMs > 0)) return config.timeoutMs;
@@ -15603,6 +15891,7 @@ var FECManager = class _FECManager {
15603
15891
  ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
15604
15892
  ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
15605
15893
  ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry },
15894
+ ...(config.groupDurationMs ?? previous.groupDurationMs) === void 0 ? {} : { groupDurationMs: config.groupDurationMs ?? previous.groupDurationMs },
15606
15895
  ...(config.repairLayers ?? previous.repairLayers) === void 0 ? {} : { repairLayers: config.repairLayers ?? previous.repairLayers },
15607
15896
  ...(config.heldLayers ?? previous.heldLayers) === void 0 ? {} : { heldLayers: config.heldLayers ?? previous.heldLayers }
15608
15897
  };
@@ -15709,6 +15998,10 @@ var FECManager = class _FECManager {
15709
15998
  lifecycleTrace: this.#lifecycleTrace.map((entry) => ({ ...entry }))
15710
15999
  };
15711
16000
  }
16001
+ /** Count a repair packet the router dropped for want of an owning track (BLO-55759). */
16002
+ countUnresolvedRepairOwner(reason) {
16003
+ this.#unresolvedRepairOwnerDrops[reason]++;
16004
+ }
15712
16005
  get fecStats() {
15713
16006
  const s = this.#fecStats;
15714
16007
  const affected = s.blocksRecovered + s.blocksFailed;
@@ -15749,6 +16042,7 @@ var FECManager = class _FECManager {
15749
16042
  })),
15750
16043
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
15751
16044
  unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
16045
+ unresolvedRepairOwnerDrops: { ...this.#unresolvedRepairOwnerDrops },
15752
16046
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
15753
16047
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
15754
16048
  };
@@ -15773,6 +16067,16 @@ var FECManager = class _FECManager {
15773
16067
  this.#startupRepairBoundaryCounts.clear();
15774
16068
  this.#startupRepairFailOpenPackets.clear();
15775
16069
  }
16070
+ /**
16071
+ * Start a new "mfu-datagram" leg (mmt-02 4.3.1) without discarding
16072
+ * track/decoder state: the same join-boundary rules as a multicast join,
16073
+ * since the leg starts at an arbitrary datagram too. It resets the whole
16074
+ * join boundary of this manager, a multicast ordered-relay frontier
16075
+ * included, so a host gives the leg a manager of its own.
16076
+ */
16077
+ beginLegJoin() {
16078
+ this.beginMulticastJoin();
16079
+ }
15776
16080
  /** How the multicast leg currently delivers symbols. */
15777
16081
  get multicastSymbolDelivery() {
15778
16082
  return this.#multicastSymbolDelivery;
@@ -15795,7 +16099,8 @@ var FECManager = class _FECManager {
15795
16099
  );
15796
16100
  }
15797
16101
  if (delivery === this.#multicastSymbolDelivery) return;
15798
- this.#deliveryGaps.reset();
16102
+ this.#deliveryGaps.multicast.reset();
16103
+ this.#runAnchors.clear();
15799
16104
  if (delivery === "ordered-relay") {
15800
16105
  for (const [packetId, config] of this.#trackConfigs) {
15801
16106
  this.#orderedHorizonBlocksFor(packetId, config);
@@ -15884,6 +16189,7 @@ var FECManager = class _FECManager {
15884
16189
  resetMap(this.#highestSbn);
15885
16190
  resetMap(this.#sourceFrontiers);
15886
16191
  resetMap(this.#isoLocators);
16192
+ resetMap(this.#runAnchors);
15887
16193
  resetMap(this.#sourceAnchors);
15888
16194
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
15889
16195
  this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
@@ -15993,6 +16299,7 @@ var FECManager = class _FECManager {
15993
16299
  dropMap(this.#highestSbn);
15994
16300
  dropMap(this.#sourceFrontiers);
15995
16301
  dropMap(this.#isoLocators);
16302
+ dropMap(this.#runAnchors);
15996
16303
  dropMap(this.#sourceAnchors);
15997
16304
  dropMap(this.#classifiers);
15998
16305
  dropMap(this.#noSpanRaps);
@@ -16060,8 +16367,8 @@ var FECManager = class _FECManager {
16060
16367
  const sourceSymbols = this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? this.#trackConfig(packetId).k;
16061
16368
  const isSourceSymbol = esi >= 0 && esi < sourceSymbols;
16062
16369
  const isStartupPartial = this.#startupPartialBlocks.has(blockKey);
16063
- const isReadyMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
16064
- const awaitingMulticastRepair = this.#startupRequireRepairReady && source === "multicast" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
16370
+ const isReadyMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !isSourceSymbol && this.#startupRepairReadyPackets.has(streamKey);
16371
+ const awaitingMulticastRepair = this.#startupRequireRepairReady && source !== "moq" && !this.#startupRepairReadyPackets.has(streamKey) && !this.#startupRepairFailOpenPackets.has(streamKey);
16065
16372
  if (awaitingMulticastRepair) {
16066
16373
  if (!isSourceSymbol) {
16067
16374
  this.#startupRepairReadyPackets.add(streamKey);
@@ -16115,12 +16422,14 @@ var FECManager = class _FECManager {
16115
16422
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
16116
16423
  multicastSymbols: 0,
16117
16424
  moqSymbols: 0,
16425
+ datagramSymbols: 0,
16118
16426
  complete: false
16119
16427
  };
16120
16428
  const receivedAtMs = this.#receiptNow();
16121
16429
  const anchorMs = this.#blockAnchorsMs.get(blockKey);
16122
16430
  if (anchorMs === void 0 || receivedAtMs < anchorMs) this.#blockAnchorsMs.set(blockKey, receivedAtMs);
16123
16431
  if (source === "multicast") counts.multicastSymbols++;
16432
+ else if (source === "moq-datagram") counts.datagramSymbols++;
16124
16433
  else counts.moqSymbols++;
16125
16434
  this.#blockPathCounts.set(blockKey, counts);
16126
16435
  this.#observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName);
@@ -16141,7 +16450,7 @@ var FECManager = class _FECManager {
16141
16450
  this.#unindexBlockKey(key);
16142
16451
  }
16143
16452
  }
16144
- if (isSourceSymbol && source === "multicast") {
16453
+ if (isSourceSymbol && source !== "moq") {
16145
16454
  this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
16146
16455
  }
16147
16456
  return true;
@@ -16230,8 +16539,22 @@ var FECManager = class _FECManager {
16230
16539
  * DeliveryGapEstimator). Datagram delivery only.
16231
16540
  */
16232
16541
  noteMulticastArrival(packetId, packetSequenceNumber) {
16233
- if (this.#multicastSymbolDelivery !== "datagram") return;
16234
- this.#deliveryGaps.noteArrival(performance.now(), packetId, packetSequenceNumber);
16542
+ this.noteArrival("multicast", packetId, packetSequenceNumber);
16543
+ }
16544
+ /**
16545
+ * Record one MMTP packet arrival on a lossy path for that path's
16546
+ * delivery-gap measurement: the multicast leg (datagram delivery only; an
16547
+ * ordered relay settles by stream order) or an "mfu-datagram" leg, whose
16548
+ * datagrams are always a lossy path (#lossyDatagramPath).
16549
+ */
16550
+ noteArrival(path, packetId, packetSequenceNumber) {
16551
+ if (!this.#lossyDatagramPath(path)) return;
16552
+ this.#deliveryGaps[path].noteArrival(performance.now(), packetId, packetSequenceNumber);
16553
+ }
16554
+ /** The largest delivery gap any lossy path measured over its window. */
16555
+ #peakDeliveryGapMs() {
16556
+ const now = performance.now();
16557
+ return Math.max(...Object.values(this.#deliveryGaps).map((estimator) => estimator.peakGapMs(now)));
16235
16558
  }
16236
16559
  /**
16237
16560
  * Resolved per-track multicast late-symbol wait in milliseconds: the span
@@ -16245,10 +16568,10 @@ var FECManager = class _FECManager {
16245
16568
  * Largest multicast delivery gap measured over the current window (ms), and
16246
16569
  * that window (undefined: held since the last reset). Diagnostics.
16247
16570
  */
16248
- multicastDeliveryGap() {
16571
+ multicastDeliveryGap(path = "multicast") {
16249
16572
  return {
16250
- peakGapMs: this.#deliveryGaps.peakGapMs(performance.now()),
16251
- windowMs: this.#deliveryGaps.windowMs
16573
+ peakGapMs: this.#deliveryGaps[path].peakGapMs(performance.now()),
16574
+ windowMs: this.#deliveryGaps[path].windowMs
16252
16575
  };
16253
16576
  }
16254
16577
  /**
@@ -16346,6 +16669,23 @@ var FECManager = class _FECManager {
16346
16669
  const config = this.#trackConfigs.get(packetId);
16347
16670
  return config === void 0 ? void 0 : this.#blockLifetimeMs(config);
16348
16671
  }
16672
+ /**
16673
+ * How long an "mfu-datagram" leg's duplicate ledgers must remember a packet
16674
+ * so a legal reorder never reads as a publisher restart: one block span,
16675
+ * the reorder tolerance (`timeoutMs` is span + tolerance) and one group,
16676
+ * since a datagram may trail the stream by a whole group behind a joining
16677
+ * FETCH (mmt-02 6.1 step 3). The group is the catalog group duration
16678
+ * (`groupDurationMs`), whatever the track kind; a video track configured
16679
+ * without one falls back to its keyframe interval (one GOP per group).
16680
+ * Undefined for an unconfigured packet id.
16681
+ */
16682
+ datagramLegLedgerRetentionMsForPacket(packetId) {
16683
+ const config = this.#trackConfigs.get(packetId);
16684
+ if (config === void 0) return void 0;
16685
+ const geometry2 = config.geometry;
16686
+ const groupMs = config.groupDurationMs ?? (geometry2?.trackKind === "video" && geometry2.mode === "classifying" ? geometry2.keyframeInterval.ticks / geometry2.keyframeInterval.timescale * 1e3 : 0);
16687
+ return config.timeoutMs + (Number.isFinite(groupMs) ? groupMs : 0);
16688
+ }
16349
16689
  /**
16350
16690
  * How long a terminal (clean, recovered or failed) block stays authoritative,
16351
16691
  * for late symbols and for the in-order release gate. It is also the gate's
@@ -16414,6 +16754,9 @@ var FECManager = class _FECManager {
16414
16754
  for (const key of [...this.#isoLocators.keys()]) {
16415
16755
  if (this.#belongsToPacket(key, packetId)) this.#isoLocators.delete(key);
16416
16756
  }
16757
+ for (const key of [...this.#runAnchors.keys()]) {
16758
+ if (this.#belongsToPacket(key, packetId)) this.#runAnchors.delete(key);
16759
+ }
16417
16760
  }
16418
16761
  /**
16419
16762
  * The iso-ssbg1-v1 locator horizon in blocks: every block the manager can
@@ -16463,9 +16806,9 @@ var FECManager = class _FECManager {
16463
16806
  holdIsoSource(packetId, catalogTrackName, ssId, source) {
16464
16807
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16465
16808
  const evictedBefore = locator.heldEvicted;
16466
- const held = locator.hold(ssId, source);
16809
+ const held = locator.hold(ssId, source.arrivedAtMs === void 0 ? { ...source, arrivedAtMs: this.#receiptNow() } : source);
16467
16810
  this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16468
- if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16811
+ if (held && source.source !== "moq") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16469
16812
  const evicted = locator.heldEvicted - evictedBefore;
16470
16813
  if (evicted > 0) {
16471
16814
  const before = this.#isoHeldEvictedCount;
@@ -16583,7 +16926,12 @@ var FECManager = class _FECManager {
16583
16926
  * Resolution of the SS_IDs strictly between two released frames' SS_IDs on
16584
16927
  * an iso-ssbg1-v1 stream, for in-order frame release: null while a block
16585
16928
  * that could hold them is pending or not yet stated by a repair, else the
16586
- * starts of the blocks that failed or vanished.
16929
+ * starts of the blocks that failed or vanished. SS_IDs no repair has
16930
+ * delimited yet that all arrived lost nothing and wait for no repair, only
16931
+ * the late-source allowance after the datagram of a lossy path that clocks
16932
+ * them arrived (#lossFreeRunReadyAtMs), and not even that when none of them
16933
+ * came as one; one missing makes a run that waits as one block
16934
+ * (isoRepairlessWaitMs).
16587
16935
  *
16588
16936
  * `untracked` reads as the release gate reads it (MmtpRouter
16589
16937
  * #createFecReleaseGate): a block holding either released frame's SS_ID
@@ -16596,7 +16944,16 @@ var FECManager = class _FECManager {
16596
16944
  isoSpanResolution(packetId, catalogTrackName, fromSsId, toSsId) {
16597
16945
  if (!serial32Precedes(fromSsId, toSsId) || serial32Distance(fromSsId, toSsId) <= 1) return [];
16598
16946
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16599
- if (!locator || !locator.coversBetween(fromSsId, toSsId)) return null;
16947
+ if (!locator) return null;
16948
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
16949
+ if (run?.missing !== void 0) return null;
16950
+ if (run !== null) {
16951
+ const config = this.#trackConfigs.get(packetId);
16952
+ const readyAtMs = config === void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
16953
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) return null;
16954
+ }
16955
+ if (locator.coverageEnd === void 0) return [];
16956
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return null;
16600
16957
  const highest = this.highestSbn(packetId, catalogTrackName);
16601
16958
  const lost = [];
16602
16959
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -16614,6 +16971,63 @@ var FECManager = class _FECManager {
16614
16971
  }
16615
16972
  return lost;
16616
16973
  }
16974
+ /**
16975
+ * When undelimited SS_IDs from `runStart` up to `toSsId` that all arrived
16976
+ * stop holding its frame: the late-source allowance after the receipt of
16977
+ * a datagram of a lossy path (#lossyDatagramPath: a multicast datagram, or
16978
+ * one of an "mfu-datagram" leg). Until then a frame between them may still
16979
+ * complete from a packet with no SS_ID (an untagged FT=0/FT=1 reordered
16980
+ * behind the next frame), and a repair may delimit them. The receipt is
16981
+ * `toSsId`'s own when it is held from such a datagram. Otherwise (its
16982
+ * packet came only as an overlap copy or from a MoQ stream, or was evicted
16983
+ * or retired) it is the newest among those SS_IDs, every one of which is
16984
+ * held and states its path. So the time moves at most once, when the
16985
+ * head's own datagram copy arrives while its frame waits or its held
16986
+ * source is dropped, and never on a later ask.
16987
+ *
16988
+ * Undefined, so the range releases at once, when no SS_ID of it came as
16989
+ * such a datagram: a MoQ arrival, an ordered relay's and the frame's own
16990
+ * are no clock for datagram reordering (#lossyReceiptMs). Undefined too
16991
+ * on a track with no catalog span, which states no allowance: the local
16992
+ * timeout is a cleanup bound, and isoRepairlessWaitMs arms no wake there,
16993
+ * so a wait would hold the frame until the next packet. The cost, on
16994
+ * multicast and on the leg too: an untagged FT=0/FT=1 reordered behind
16995
+ * the next frame of such a track is dropped stale.
16996
+ */
16997
+ #lossFreeRunReadyAtMs(config, locator, runStart, toSsId) {
16998
+ if (!_FECManager.#hasCatalogTiming(config)) return void 0;
16999
+ let clockMs = this.#lossyReceiptMs(locator.heldSource(toSsId));
17000
+ if (clockMs === void 0) {
17001
+ for (let ssId = runStart; ssId !== toSsId; ssId = ssId + 1 >>> 0) {
17002
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
17003
+ if (atMs !== void 0 && (clockMs === void 0 || atMs > clockMs)) clockMs = atMs;
17004
+ }
17005
+ }
17006
+ if (clockMs === void 0) return void 0;
17007
+ return clockMs + Math.max(0, this.#multicastWaitMs(config) - config.interleaveDepthMs);
17008
+ }
17009
+ /**
17010
+ * Receipt time of a held source that came as a datagram of a lossy path
17011
+ * (#lossyDatagramPath), else undefined: a MoQ stream and an ordered relay
17012
+ * deliver in order, so their arrivals clock no reorder allowance and no
17013
+ * FEC deadline. The path is the one the feed stated (IsoHeldSource.source,
17014
+ * and MulticastSymbolDelivery for a multicast source), never a guess.
17015
+ */
17016
+ #lossyReceiptMs(held) {
17017
+ return held !== void 0 && this.#lossyDatagramPath(held.source) ? held.arrivedAtMs : void 0;
17018
+ }
17019
+ /**
17020
+ * The one path predicate of the loss gates: whether a symbol fed as
17021
+ * `source` reached this manager as a datagram of its own, on a path that
17022
+ * loses and reorders (mmt-02 Section 2, a datagram leg). A multicast
17023
+ * symbol does unless its provider declared an ordered relay. An
17024
+ * "mfu-datagram" object always does (4.3.1): MulticastSymbolDelivery is
17025
+ * the multicast provider's statement and is never read for the leg. A MoQ
17026
+ * stream object never does, a stream copy of the leg included.
17027
+ */
17028
+ #lossyDatagramPath(source) {
17029
+ return source === "moq-datagram" || source === "multicast" && this.#multicastSymbolDelivery === "datagram";
17030
+ }
16617
17031
  /**
16618
17032
  * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
16619
17033
  * between two released frames' SS_IDs once only a late source can still
@@ -16621,10 +17035,11 @@ var FECManager = class _FECManager {
16621
17035
  * arrived nor held) lies in a repair-less span longer than K, which no
16622
17036
  * repair can state a block of (#openIsoSpan), or in a stated block its
16623
17037
  * own repair group cannot complete every SS_ID of which it misses lies
16624
- * between them (so the gap's decision covers all it lost), and a multicast
16625
- * source at or past `toSsId` arrived, so each is lost or reordered behind
16626
- * it (a MoQ source shows nothing: MoQ streams overtake one another). The
16627
- * span or block itself keeps its own wait.
17038
+ * between them (so the gap's decision covers all it lost), and a source of
17039
+ * a lossy leg (multicast, or an "mfu-datagram" leg's datagram) at or past
17040
+ * `toSsId` arrived, so each is lost or reordered behind it (a MoQ source
17041
+ * shows nothing: MoQ streams overtake one another). The span or block
17042
+ * itself keeps its own wait.
16628
17043
  *
16629
17044
  * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
16630
17045
  * hold a RAP packet an installed keyframe overlay can still rebuild (its
@@ -16635,14 +17050,56 @@ var FECManager = class _FECManager {
16635
17050
  * for an overlay that states no span, the span's whole wait (undefined).
16636
17051
  * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
16637
17052
  * the gap holds a stated block's loss.
16638
- */
16639
- isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
17053
+ *
17054
+ * A run of SS_IDs no repair has delimited yet, one of which never arrived,
17055
+ * is one block of its own instead (draft-ramadan-moq-fec-multicast-00,
17056
+ * Receiver Repair Policy; on an "mfu-datagram" leg fec-core-00 9.3 and
17057
+ * mmt-02 5.3.3): the frame then waits for that block's FEC deadline,
17058
+ * whatever the flags: ts plus the whole multicast wait (fec-core-00 9.3),
17059
+ * ts the receipt of the lowest held source above the run that came as a
17060
+ * datagram of a lossy path (#lossyDatagramPath), up to the newest
17061
+ * (fec-multicast-00, Deadline Anchoring; under reordering at or after the
17062
+ * draft's first signal, never before). The wait returned counts from
17063
+ * `arrivedAtMs`, the frame's arrival; without it, it is the whole wait.
17064
+ * With no such source held (never arrived, retired, or evicted, or every
17065
+ * one from a MoQ stream or an ordered relay) the frame keeps the hold
17066
+ * ceiling: a stream arrival is no clock for a datagram deadline.
17067
+ */
17068
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false, arrivedAtMs) {
16640
17069
  const config = this.#trackConfigs.get(packetId);
16641
17070
  if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
16642
- const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16643
- if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
17071
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
17072
+ const locator = this.#isoLocators.get(streamKey);
17073
+ if (locator === void 0) return void 0;
17074
+ const run = locator.undelimitedBetween(fromSsId, toSsId);
17075
+ const readyAtMs = run === null || run.missing !== void 0 ? void 0 : this.#lossFreeRunReadyAtMs(config, locator, run.start, toSsId);
17076
+ if (readyAtMs !== void 0 && this.#receiptNow() < readyAtMs) {
17077
+ return Math.max(0, readyAtMs - (arrivedAtMs ?? this.#receiptNow()));
17078
+ }
16644
17079
  const newestSource = locator.newestSource;
16645
17080
  if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
17081
+ if (run?.missing !== void 0) {
17082
+ if (this.isoSpanResolution(packetId, catalogTrackName, fromSsId, run.start) === null) return void 0;
17083
+ const kept = this.#runAnchors.get(streamKey);
17084
+ const anchor = kept?.fromSsId === fromSsId && this.#receiptNow() - kept.tsMs <= 2 * (config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config)) ? kept : void 0;
17085
+ let tsMs = anchor?.tsMs;
17086
+ for (let ssId = run.missing + 1 >>> 0; !serial32Precedes(newestSource, ssId); ssId = ssId + 1 >>> 0) {
17087
+ const atMs = this.#lossyReceiptMs(locator.heldSource(ssId));
17088
+ if (atMs === void 0) continue;
17089
+ if (tsMs === void 0 || atMs < tsMs) tsMs = atMs;
17090
+ break;
17091
+ }
17092
+ if (tsMs === void 0) return void 0;
17093
+ const waitMs2 = this.#multicastWaitMs(config);
17094
+ let counted = anchor?.counted === true;
17095
+ if (!counted && tsMs + waitMs2 <= this.#receiptNow()) {
17096
+ counted = true;
17097
+ this.onUndelimitedRunGap?.(packetId, catalogTrackName);
17098
+ }
17099
+ this.#runAnchors.set(streamKey, { fromSsId, tsMs, counted });
17100
+ return arrivedAtMs === void 0 ? waitMs2 : Math.max(0, tsMs + waitMs2 - arrivedAtMs);
17101
+ }
17102
+ if (!locator.coversBetween(fromSsId, run?.start ?? toSsId)) return void 0;
16646
17103
  let repairless = false;
16647
17104
  let stated = false;
16648
17105
  for (const block of locator.blocksBetween(fromSsId, toSsId)) {
@@ -16723,11 +17180,31 @@ var FECManager = class _FECManager {
16723
17180
  * it does not. A stream with no classifier yet has shown nothing against it,
16724
17181
  * and neither has a stream without catalog timing until it releases two
16725
17182
  * RAPs inside one MPU.
16726
- */
16727
- mpuBoundsRapsFor(packetId, catalogTrackName) {
17183
+ *
17184
+ * With catalog timing and a `gap` inside one MPU, between the authored
17185
+ * timing of the frames on either side, it also takes the catalog keyframe
17186
+ * interval to rule a keyframe out of the gap
17187
+ * (`BlockClassifier.keyframeFreeBetween`, fec-multicast-00 Block
17188
+ * Classification item 3), and no source held between the frames' SS_IDs
17189
+ * may carry the RAP flag or another MPU's number (item 1 read on the held
17190
+ * packets: a RAP the loss cut in two is never released, so the frames
17191
+ * alone cannot show it); anything unknown counts as a keyframe.
17192
+ */
17193
+ mpuBoundsRapsFor(packetId, catalogTrackName, gap) {
16728
17194
  const streamKey = this.#streamKey(packetId, catalogTrackName);
16729
17195
  if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
16730
- return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
17196
+ const classifier = this.#classifiers.get(streamKey);
17197
+ if (gap === void 0) return classifier?.mpuBoundsRaps ?? true;
17198
+ const { mpu, from, to, fromSsId, toSsId } = gap;
17199
+ if (fromSsId !== void 0 && toSsId !== void 0) {
17200
+ const run = this.#isoLocators.get(streamKey)?.undelimitedBetween(
17201
+ fromSsId,
17202
+ toSsId,
17203
+ ({ evidence }) => evidence.rap || evidence.mpu !== void 0 && evidence.mpu !== mpu
17204
+ );
17205
+ if (run?.flagged) return false;
17206
+ }
17207
+ return classifier !== void 0 && from !== void 0 && to !== void 0 && from.mediaTimescale === to.mediaTimescale && classifier.keyframeFreeBetween(mpu, from.decodeTime, to.decodeTime, from.mediaTimescale);
16731
17208
  }
16732
17209
  /** A block's class now, or frozen at its resolution. */
16733
17210
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -16750,9 +17227,11 @@ var FECManager = class _FECManager {
16750
17227
  }
16751
17228
  /**
16752
17229
  * Record a RAP frame released in order, for the classifier's RAP-spacing
16753
- * invariant (consecutive MPUs exactly one keyframe interval apart).
17230
+ * invariant (consecutive MPUs exactly one keyframe interval apart) and,
17231
+ * with its decode time, as the MPU start gap decisions measure the catalog
17232
+ * keyframe interval from (mpuBoundsRapsFor).
16754
17233
  */
16755
- noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
17234
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale, decodeTime) {
16756
17235
  if (!this.#trackConfigs.has(packetId)) return;
16757
17236
  if (!this.#hasCatalogTimingForPacket(packetId)) {
16758
17237
  const streamKey = this.#streamKey(packetId, catalogTrackName);
@@ -16767,7 +17246,8 @@ var FECManager = class _FECManager {
16767
17246
  this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
16768
17247
  mpu,
16769
17248
  presentationTime,
16770
- mediaTimescale
17249
+ mediaTimescale,
17250
+ decodeTime
16771
17251
  )
16772
17252
  );
16773
17253
  }
@@ -17470,9 +17950,11 @@ var FECManager = class _FECManager {
17470
17950
  * its sources in send order, so one that moves the stream's newest source
17471
17951
  * position past a block leaves the sources that block still misses
17472
17952
  * reordered behind it at best: it shortens the wait of every block it
17473
- * passed that only a late source can complete. MoQ is left out: its streams
17474
- * can overtake one another, so a MoQ source shows nothing about the sources
17475
- * sent before it.
17953
+ * passed that only a late source can complete. Reliable MoQ is left out:
17954
+ * its streams can overtake one another, so a MoQ source shows nothing
17955
+ * about the sources sent before it. An "mfu-datagram" leg is in: its
17956
+ * datagrams leave the publisher in send order and reorder only within the
17957
+ * path's tolerance, as multicast does.
17476
17958
  */
17477
17959
  #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17478
17960
  const previous = locator.newestSource;
@@ -17939,7 +18421,7 @@ var FECManager = class _FECManager {
17939
18421
  blockDeliveryProvenance(sbn, packetId, catalogTrackName) {
17940
18422
  const counts = this.blockPathCount(sbn, packetId, catalogTrackName);
17941
18423
  if (!counts) return "unknown";
17942
- if (counts.moqSymbols > 0) return "mixed";
18424
+ if (counts.moqSymbols > 0 || counts.datagramSymbols > 0) return "mixed";
17943
18425
  if (counts.multicastSymbols > 0) return "multicast";
17944
18426
  return "unknown";
17945
18427
  }
@@ -17966,7 +18448,7 @@ var FECManager = class _FECManager {
17966
18448
  this.#activeBlockDeadlinesMs.clear();
17967
18449
  this.#blockWaitDeadlinesMs.clear();
17968
18450
  this.#repairHoldUntilMs.clear();
17969
- this.#deliveryGaps.reset();
18451
+ for (const estimator of Object.values(this.#deliveryGaps)) estimator.reset();
17970
18452
  this.#pendingWorkerCleanups.clear();
17971
18453
  this.#pendingWorkerCleanupClients.clear();
17972
18454
  for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
@@ -18017,6 +18499,7 @@ var FECManager = class _FECManager {
18017
18499
  this.#highestSbn.clear();
18018
18500
  this.#sourceFrontiers.clear();
18019
18501
  this.#isoLocators.clear();
18502
+ this.#runAnchors.clear();
18020
18503
  this.#sourceAnchors.clear();
18021
18504
  this.#trackConfigs.clear();
18022
18505
  this.#fecDecoders.clear();
@@ -21487,12 +21970,12 @@ function validPort(value) {
21487
21970
  return Number.isInteger(value) && value >= 0 && value <= 65535;
21488
21971
  }
21489
21972
  function parseIpv42(address) {
21490
- const fields = address.split(".");
21491
- if (fields.length !== 4 || fields.some((field) => !/^\d+$/.test(field))) {
21973
+ const fields2 = address.split(".");
21974
+ if (fields2.length !== 4 || fields2.some((field) => !/^\d+$/.test(field))) {
21492
21975
  throw new Error(`invalid IPv4 address ${address}`);
21493
21976
  }
21494
- const values = fields.map(Number);
21495
- if (values.some((value, index) => value > 255 || String(value) !== fields[index])) {
21977
+ const values = fields2.map(Number);
21978
+ if (values.some((value, index) => value > 255 || String(value) !== fields2[index])) {
21496
21979
  throw new Error(`invalid IPv4 address ${address}`);
21497
21980
  }
21498
21981
  return Uint8Array.from(values);
@@ -21706,7 +22189,7 @@ function bitLen(n) {
21706
22189
  return len;
21707
22190
  }
21708
22191
  var bitMask = (n) => (_1n << BigInt(n)) - _1n;
21709
- function _validateObject(object2, fields, optFields = {}) {
22192
+ function _validateObject(object2, fields2, optFields = {}) {
21710
22193
  if (!object2 || typeof object2 !== "object")
21711
22194
  throw new Error("expected valid options object");
21712
22195
  function checkField2(fieldName, expectedType, isOpt) {
@@ -21717,7 +22200,7 @@ function _validateObject(object2, fields, optFields = {}) {
21717
22200
  if (current !== expectedType || val === null)
21718
22201
  throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
21719
22202
  }
21720
- Object.entries(fields).forEach(([k, v]) => checkField2(k, v, false));
22203
+ Object.entries(fields2).forEach(([k, v]) => checkField2(k, v, false));
21721
22204
  Object.entries(optFields).forEach(([k, v]) => checkField2(k, v, true));
21722
22205
  }
21723
22206
  var notImplemented = () => {
@@ -23698,6 +24181,20 @@ var MmtpRouter = class {
23698
24181
  /** The flow whose receiver admitted a stream's source datagrams, by packetId then catalog track name: recovered packets answer to it. */
23699
24182
  #provenanceStreamFlow = /* @__PURE__ */ new Map();
23700
24183
  #unregisteredFlowDrops = 0;
24184
+ /** "mfu-datagram" leg packets of a packet id the ingress does not name (never the signaling flow). */
24185
+ #datagramLegIngressDrops = 0;
24186
+ /** "mfu-datagram" leg packets of the signaling flow (packet id 0): expected, one per group. */
24187
+ #datagramLegSignalingPackets = 0;
24188
+ /**
24189
+ * The streams a live "mfu-datagram" leg has fed, catalog track names by
24190
+ * packet id: their ledgers and release gate take the leg's bounds. A stream
24191
+ * leaves when its leg does: `endDatagramLeg`, `resetTrack`, `dispose`, or
24192
+ * the first multicast packet of its packet id (the ordered switch retires
24193
+ * the leg first). The "mfu" sibling shares the packet id, never the name.
24194
+ */
24195
+ #datagramLegStreams = /* @__PURE__ */ new Map();
24196
+ /** The leg's presentation budget (setDatagramLegPresentationBudget), or null: no presentation bound. */
24197
+ #datagramLegPresentationBudgetMs = null;
23701
24198
  #ambiguousRecoveredDrops = 0;
23702
24199
  // Temp state set by #processMMTP before calling parser.feed(),
23703
24200
  // read by the parser's onFrame callback for CMAF assembly + dedup.
@@ -24073,10 +24570,11 @@ var MmtpRouter = class {
24073
24570
  const blockLifetimeMs = fec.blockLifetimeMsForPacket(packetId);
24074
24571
  if (blockSpanMs === void 0 || blockLifetimeMs === void 0) return NO_FEC_GEOMETRY_HORIZON;
24075
24572
  if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
24076
- return {
24077
- kind: "fec-horizon",
24078
- retentionMs: duplicateRetentionMs({ blockSpanMs, blockLifetimeMs })
24079
- };
24573
+ let retentionMs = duplicateRetentionMs({ blockSpanMs, blockLifetimeMs });
24574
+ if (this.#datagramLegStreams.has(packetId)) {
24575
+ retentionMs = Math.max(retentionMs, fec.datagramLegLedgerRetentionMsForPacket?.(packetId) ?? 0);
24576
+ }
24577
+ return { kind: "fec-horizon", retentionMs };
24080
24578
  }
24081
24579
  /**
24082
24580
  * Init segments rejected since construction because their packetId had no
@@ -24499,7 +24997,7 @@ var MmtpRouter = class {
24499
24997
  const blockStart = placement.block.start;
24500
24998
  if (placement.span !== void 0) this.#replayOverlaySources(inst, placement.span.block.start, placement.span.placed);
24501
24999
  this.#replayOverlaySources(inst, blockStart, placement.placed);
24502
- if (source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
25000
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
24503
25001
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
24504
25002
  const recovered = fec.feedRepairSymbol(pid, repair.ssStart, repair.ssbLength, repair.rsId, repair.symbolData, name);
24505
25003
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, blockStart, recovered);
@@ -24507,7 +25005,7 @@ var MmtpRouter = class {
24507
25005
  #replayOverlaySources(inst, blockStart, placed) {
24508
25006
  const { fec, repairPacketId: pid, streamName: name } = inst;
24509
25007
  for (const { ssId, payload } of placed) {
24510
- if (payload.source === "moq") this.#noteOverlayMoqBlock(inst, blockStart);
25008
+ if (payload.source !== "multicast") this.#noteOverlayMoqBlock(inst, blockStart);
24511
25009
  if (payload.oversized) continue;
24512
25010
  const alreadyCompleted = fec.isBlockCompleted(blockStart, pid, name);
24513
25011
  const recovered = fec.feedSourceSymbol(pid, ssId, payload.symbolData, name);
@@ -24560,7 +25058,7 @@ var MmtpRouter = class {
24560
25058
  });
24561
25059
  continue;
24562
25060
  }
24563
- if (source === "moq") this.#noteOverlayMoqBlock(inst, coords.sbn);
25061
+ if (source !== "multicast") this.#noteOverlayMoqBlock(inst, coords.sbn);
24564
25062
  if (oversized) continue;
24565
25063
  const alreadyCompleted = fec.isBlockCompleted(coords.sbn, pid, name);
24566
25064
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
@@ -25149,6 +25647,46 @@ var MmtpRouter = class {
25149
25647
  get unregisteredFlowDropCount() {
25150
25648
  return this.#unregisteredFlowDrops;
25151
25649
  }
25650
+ /** "mfu-datagram" leg packets dropped because the leg's ingress does not name their packet id (packet id 0 apart). */
25651
+ get datagramLegIngressDropCount() {
25652
+ return this.#datagramLegIngressDrops;
25653
+ }
25654
+ /** "mfu-datagram" leg packets of the MMTP signaling flow (packet id 0), which no track owns. */
25655
+ get datagramLegSignalingPacketCount() {
25656
+ return this.#datagramLegSignalingPackets;
25657
+ }
25658
+ /**
25659
+ * The "mfu-datagram" leg's presentation bound (mmt-02 6.1 step 6): how
25660
+ * long after a frame arrives it must leave the release gate when the gap
25661
+ * before it holds no RAP, FT=0 or FT=1 data (the player's presentation
25662
+ * delay less its decode lead). The gap is then decided at the earlier of
25663
+ * the FEC block deadline and this bound; a gap that may hold a RAP keeps
25664
+ * the block deadline. Null, or a value that is not finite and positive:
25665
+ * the block deadline alone, as on multicast.
25666
+ */
25667
+ setDatagramLegPresentationBudget(budgetMs) {
25668
+ this.#datagramLegPresentationBudgetMs = budgetMs;
25669
+ }
25670
+ /**
25671
+ * The "mfu-datagram" leg is over (unsubscribed, or switched to another
25672
+ * path): no stream keeps its presentation bound or its ledger retention.
25673
+ * Parser, FEC and ledger state stay, so the packet ids continue on the
25674
+ * next path without an epoch. A later leg datagram starts a leg again.
25675
+ */
25676
+ endDatagramLeg() {
25677
+ this.#datagramLegStreams.clear();
25678
+ this.#datagramLegPresentationBudgetMs = null;
25679
+ }
25680
+ #datagramLegPresentationWaitMs(packetId, catalogTrackName) {
25681
+ if (this.#datagramLegPresentationBudgetMs === null || this.#datagramLegStreams.get(packetId)?.has(catalogTrackName) !== true) return void 0;
25682
+ let budgetMs;
25683
+ try {
25684
+ budgetMs = this.#datagramLegPresentationBudgetMs(packetId, catalogTrackName);
25685
+ } catch {
25686
+ return void 0;
25687
+ }
25688
+ return Number.isFinite(budgetMs) && budgetMs > 0 ? budgetMs : void 0;
25689
+ }
25152
25690
  /** Recovered packets dropped because more than one protected flow could own their stream. */
25153
25691
  get ambiguousRecoveredDropCount() {
25154
25692
  return this.#ambiguousRecoveredDrops;
@@ -25166,6 +25704,10 @@ var MmtpRouter = class {
25166
25704
  * caller that forgot it silently attributed its bytes to a multicast socket
25167
25705
  * they may never have crossed — and that attribution is what the physical-
25168
25706
  * delivery evidence path is built on. Absence is not multicast; say which.
25707
+ * `"moq-datagram"` is an "mfu-datagram" subscription (MmtpIngestSource):
25708
+ * `ingress.tracks` MUST name the datagram catalog track for its packet id,
25709
+ * and a packet of a packet id it does not name is dropped and counted
25710
+ * (`datagramLegIngressDropCount`; the signaling flow, packet id 0, apart).
25169
25711
  */
25170
25712
  feedPacket(packet, source, ingress) {
25171
25713
  if (this.#disposed) return;
@@ -25215,15 +25757,18 @@ var MmtpRouter = class {
25215
25757
  }
25216
25758
  /**
25217
25759
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
25218
- * header and delegates to FECManager for FEC recovery.
25760
+ * header and delegates to FECManager for FEC recovery. `source` is
25761
+ * `"moq-datagram"` for a repair object of an "mfu-datagram" track's repair
25762
+ * track, which arrives as a datagram and so counts as an in-band symbol of
25763
+ * the leg; a FETCHed repair stays `"moq"` (RepairVia `quic`).
25219
25764
  */
25220
- feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName) {
25765
+ feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source = "moq") {
25221
25766
  if (this.#disposed) return;
25222
25767
  this.#withDeferredFecPokes(() => {
25223
- this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName);
25768
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source);
25224
25769
  });
25225
25770
  }
25226
- #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, admitted = false) {
25771
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, admitted = false) {
25227
25772
  let header;
25228
25773
  try {
25229
25774
  header = parseMMTPHeader(packet);
@@ -25233,7 +25778,7 @@ var MmtpRouter = class {
25233
25778
  const repairPacketId = header.packetId;
25234
25779
  const overlay = this.#overlayRepairTarget(repairPacketId, repairTrackName);
25235
25780
  if (overlay !== void 0) {
25236
- this.#routeOverlayRepair(overlay, repairPacketId, packet, header, "moq");
25781
+ this.#routeOverlayRepair(overlay, repairPacketId, packet, header, source);
25237
25782
  return;
25238
25783
  }
25239
25784
  const hintedOwner = ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null ? ownerPacketIdHint : null;
@@ -25245,7 +25790,7 @@ var MmtpRouter = class {
25245
25790
  }
25246
25791
  let unlisted = false;
25247
25792
  if (ownerPacketId != null && !admitted) {
25248
- const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, true));
25793
+ const admit = this.#admitUnicast(repairPacketId, packet, () => this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName, repairTrackName, source, true));
25249
25794
  if (admit === "held" || admit === "dropped") return;
25250
25795
  unlisted = admit === "unlisted";
25251
25796
  }
@@ -25266,7 +25811,7 @@ var MmtpRouter = class {
25266
25811
  this.#noteUnreadableFecPayloadId(ownerPacketId, "repair");
25267
25812
  return;
25268
25813
  }
25269
- this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, "moq", repairTrackName);
25814
+ this.#handleIsoRepair(ownerPacketId, catalogTrackName, parsed, source, repairTrackName);
25270
25815
  }
25271
25816
  }
25272
25817
  // ── Packet FEC geometry and block profile ───────────────────────
@@ -25471,6 +26016,7 @@ var MmtpRouter = class {
25471
26016
  debugRouter(
25472
26017
  `[MmtpRouter] Dropping repair packet pid=${packetId}: physical PID is unregistered`
25473
26018
  );
26019
+ this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
25474
26020
  return null;
25475
26021
  }
25476
26022
  const registeredOwners = this.#repairOwnersByPacketId.get(packetId) ?? /* @__PURE__ */ new Set();
@@ -25479,6 +26025,7 @@ var MmtpRouter = class {
25479
26025
  debugRouter(
25480
26026
  `[MmtpRouter] Dropping repair packet pid=${packetId}: catalog owner is ${owners.length === 0 ? "absent" : "ambiguous"}`
25481
26027
  );
26028
+ this.#fecManager?.countUnresolvedRepairOwner?.(owners.length === 0 ? "ownerAbsent" : "ownerAmbiguous");
25482
26029
  return null;
25483
26030
  }
25484
26031
  /** Route a recovered FEC block through the parser + dedup pipeline.
@@ -25528,6 +26075,8 @@ var MmtpRouter = class {
25528
26075
  }
25529
26076
  this.#parser.resetTrack(packetId, catalogTrackName);
25530
26077
  this.resetKeyframeOverlays(packetId, catalogTrackName);
26078
+ const legNames = this.#datagramLegStreams.get(packetId);
26079
+ if (legNames?.delete(catalogTrackName) && legNames.size === 0) this.#datagramLegStreams.delete(packetId);
25531
26080
  this.#restampedStreams.delete(this.#mediaStreamKey(packetId, catalogTrackName));
25532
26081
  const assistPrefix = assistKey(packetId, catalogTrackName, 0).slice(0, -1);
25533
26082
  for (const key of this.#assistBlocks.keys()) if (key.startsWith(assistPrefix)) this.#assistBlocks.delete(key);
@@ -25869,6 +26418,7 @@ var MmtpRouter = class {
25869
26418
  this.#fecWakes.clear();
25870
26419
  this.#parser.dispose();
25871
26420
  this.#streams.clear();
26421
+ this.endDatagramLeg();
25872
26422
  this.#trackPacketCallbacks.clear();
25873
26423
  this.#latestVideoSeqByStream.clear();
25874
26424
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -26058,20 +26608,27 @@ var MmtpRouter = class {
26058
26608
  // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
26059
26609
  // other rap-next, whose gap may hold a whole MPU and the keyframe the
26060
26610
  // overlay protects) waits for that overlay's repair too (BLO-52085
26061
- // D4). The FEC check comes first: most held gaps are not behind such a
26062
- // span, and deciding one scans both frames' bitstreams.
26611
+ // D4). A run no repair has delimited instead waits for its FEC
26612
+ // deadline, whatever the decision (FECManager.isoRepairlessWaitMs). The
26613
+ // FEC check comes first: most held gaps are not behind such a span, and
26614
+ // deciding one scans both frames' bitstreams.
26063
26615
  unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
26064
26616
  const fec = this.#fecManager;
26065
26617
  const { packetId, catalogTrackName } = after.meta;
26066
- const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
26067
- if (!fec || allowanceMs === void 0) return void 0;
26618
+ const arrivedAtMs = after.arrivedAtMs;
26619
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, false, arrivedAtMs);
26620
+ const presentationMs = this.#datagramLegPresentationWaitMs(packetId, catalogTrackName);
26621
+ if (!fec || allowanceMs === void 0 && presentationMs === void 0) return void 0;
26068
26622
  const decision = this.#decideGap(before, after, [], false);
26069
26623
  const mpu = before.meta.mpuSequenceNumber;
26070
26624
  const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26071
26625
  if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
26072
- return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
26626
+ return allowanceMs === void 0 ? void 0 : fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true, false, arrivedAtMs);
26073
26627
  }
26074
- return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
26628
+ const waitMs = allowanceMs === void 0 ? void 0 : decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true, arrivedAtMs) : allowanceMs;
26629
+ if (decision.reason === "delta-lost" && !((fec.interleaveDepthMsForPacket?.(packetId) ?? 0) > 0)) return waitMs;
26630
+ if (presentationMs === void 0) return waitMs;
26631
+ return waitMs === void 0 ? presentationMs : Math.min(waitMs, presentationMs);
26075
26632
  },
26076
26633
  decide: (before, after, lostBlocks, discontinuity) => {
26077
26634
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
@@ -26113,7 +26670,8 @@ var MmtpRouter = class {
26113
26670
  meta.catalogTrackName,
26114
26671
  meta.mpuSequenceNumber,
26115
26672
  timing.presentationTime,
26116
- timing.mediaTimescale
26673
+ timing.mediaTimescale,
26674
+ timing.decodeTime
26117
26675
  );
26118
26676
  }
26119
26677
  };
@@ -26132,7 +26690,19 @@ var MmtpRouter = class {
26132
26690
  const { packetId, catalogTrackName } = after.meta;
26133
26691
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
26134
26692
  const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
26135
- const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26693
+ const mpu = before.meta.mpuSequenceNumber;
26694
+ const sameMpu = trackKind === "video" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu;
26695
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(
26696
+ packetId,
26697
+ catalogTrackName,
26698
+ sameMpu ? {
26699
+ mpu,
26700
+ from: before.meta.authoredTiming,
26701
+ to: after.meta.authoredTiming,
26702
+ fromSsId: before.meta.fecSbn,
26703
+ toSsId: after.meta.fecSbnFirst ?? after.meta.fecSbn
26704
+ } : void 0
26705
+ ) === true;
26136
26706
  const evidence = (frame) => {
26137
26707
  const timing = frame.meta.authoredTiming;
26138
26708
  const sampleNumber = frame.meta.sampleNumber;
@@ -26248,18 +26818,34 @@ var MmtpRouter = class {
26248
26818
  if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
26249
26819
  if (source === "multicast" && !manifestAdmitted) {
26250
26820
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
26821
+ } else if (source === "moq-datagram" && !manifestAdmitted) {
26822
+ this.#fecManager?.noteArrival?.("moq-datagram", info.packetId, info.sequenceNumber);
26251
26823
  }
26252
- if (source === "multicast" && !ingressHasPacketId(ingress, info.packetId)) {
26824
+ if (source !== "moq" && !ingressHasPacketId(ingress, info.packetId)) {
26825
+ if (source === "moq-datagram") {
26826
+ if (info.packetId === MMTP_SIGNALING_PACKET_ID) this.#datagramLegSignalingPackets++;
26827
+ else this.#datagramLegIngressDrops++;
26828
+ }
26253
26829
  debugRouter(
26254
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`
26830
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: absent from ingress tracks`
26255
26831
  );
26256
26832
  return;
26257
26833
  }
26834
+ if (source === "moq-datagram") {
26835
+ if (!info.isRepair) {
26836
+ let names = this.#datagramLegStreams.get(info.packetId);
26837
+ if (!names) this.#datagramLegStreams.set(info.packetId, names = /* @__PURE__ */ new Set());
26838
+ names.add(catalogTrackNameForPacket(ingress, info.packetId));
26839
+ }
26840
+ } else if (source === "multicast") {
26841
+ this.#datagramLegStreams.delete(info.packetId);
26842
+ }
26258
26843
  const packetRole = this.#packetIdRoles.get(info.packetId);
26259
- if (source === "multicast" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
26844
+ if (source !== "moq" && this.#classifyPacketId(info.packetId) === null && (!info.isRepair || packetRole !== "repair")) {
26260
26845
  debugRouter(
26261
- `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: physical PID is unregistered`
26846
+ `[MmtpRouter] Dropping ${source} packet pid=${info.packetId}: physical PID is unregistered`
26262
26847
  );
26848
+ if (info.isRepair) this.#fecManager?.countUnresolvedRepairOwner?.("unregistered");
26263
26849
  return;
26264
26850
  }
26265
26851
  if (!info.isRepair && hasAmbiguousCatalogTrackName(ingress, info.packetId)) {
@@ -26295,7 +26881,7 @@ var MmtpRouter = class {
26295
26881
  }
26296
26882
  return;
26297
26883
  }
26298
- if (source === "moq" && !manifestAdmitted) {
26884
+ if (source !== "multicast" && !manifestAdmitted) {
26299
26885
  const admit = this.#admitUnicast(info.packetId, packet, () => this.#processMMTP(packet, source, true, ingress, overlapCopy, true), overlapCopy);
26300
26886
  if (admit !== "unlisted") {
26301
26887
  if (admit === "admitted") this.#processMMTP(packet, source, true, ingress, overlapCopy);
@@ -26324,7 +26910,7 @@ var MmtpRouter = class {
26324
26910
  );
26325
26911
  if (!repair) return;
26326
26912
  if (ownerPacketId != null && this.#fecManager) {
26327
- if ((flowless && this.#userAgentGoverns(ownerPacketId) || source === "moq" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
26913
+ if ((flowless && this.#userAgentGoverns(ownerPacketId) || source !== "multicast" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
26328
26914
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
26329
26915
  const count = this.#repairPidCounts[info.packetId];
26330
26916
  if (count <= 2 || count % 500 === 0) {
@@ -26363,7 +26949,7 @@ var MmtpRouter = class {
26363
26949
  const fecSource = this.#fecManager !== null && fecPayloadId != null;
26364
26950
  const coords = fecSource && fecPayloadId ? this.#locateFecSource(info.packetId, catalogTrackName, fecPayloadId.ssId) ?? void 0 : void 0;
26365
26951
  duplicates.advance(coords?.sbn);
26366
- if (source === "multicast" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
26952
+ if (source !== "moq" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, fecPayloadId?.ssId)) {
26367
26953
  this.#publisherRestarts++;
26368
26954
  console.warn(
26369
26955
  `[MmtpRouter] publisher restart on pid=${info.packetId} track=${catalogTrackName}: packet_sequence_number=${info.sequenceNumber} predates the stream's FEC horizon; starting a new epoch`
@@ -26424,6 +27010,7 @@ var MmtpRouter = class {
26424
27010
  evidence: sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber),
26425
27011
  oversized: !(this.#fecManager.isoSourceFits?.(info.packetId, rawSymbol.length) ?? false)
26426
27012
  }) ?? false;
27013
+ if (held) this.#requestFecPoke(info.packetId, catalogTrackName);
26427
27014
  parseSourceSymbol = held && !duplicates.parsedSymbols.has(ssId);
26428
27015
  }
26429
27016
  } else if (fecUnreadable && info.fecPayloadId) {
@@ -26551,7 +27138,9 @@ var MmtpRouter = class {
26551
27138
  const feedOptions = {
26552
27139
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
26553
27140
  recovered: parserOptions?.recovered,
26554
- source: parserOptions?.source,
27141
+ // Frame attribution is the transport path: an "mfu-datagram" object
27142
+ // crossed QUIC, so its frames are 'moq' (provenance 'mixed').
27143
+ source: parserOptions?.source === "moq-datagram" ? "moq" : parserOptions?.source,
26555
27144
  deliveryProvenance: parserOptions?.deliveryProvenance,
26556
27145
  catalogTrackName: parserOptions?.catalogTrackName,
26557
27146
  ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
@@ -27811,14 +28400,14 @@ function createWasmMmtpContainerParser(config) {
27811
28400
  var JOIN_SUCCEEDED = Object.freeze({ ok: true });
27812
28401
  function providerErrorOf(error) {
27813
28402
  if (typeof error !== "object" || error === null) return void 0;
27814
- const fields = error;
28403
+ const fields2 = error;
27815
28404
  let name;
27816
28405
  let message;
27817
28406
  let code;
27818
28407
  try {
27819
- name = fields.name;
27820
- message = fields.message;
27821
- code = fields.code;
28408
+ name = fields2.name;
28409
+ message = fields2.message;
28410
+ code = fields2.code;
27822
28411
  } catch {
27823
28412
  return void 0;
27824
28413
  }
@@ -28716,6 +29305,7 @@ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
28716
29305
  stalls: 0,
28717
29306
  concealedBlocks: 0,
28718
29307
  concealedGaps: 0,
29308
+ undelimitedRunGaps: 0,
28719
29309
  concealedFrames: 0,
28720
29310
  concealedAudioMs: 0,
28721
29311
  vanishedBlocks: 0
@@ -29222,6 +29812,9 @@ var MulticastManager = class {
29222
29812
  reason
29223
29813
  });
29224
29814
  };
29815
+ this.#fec.onUndelimitedRunGap = (packetId, catalogTrackName) => {
29816
+ this.#statsFor(packetId, catalogTrackName).undelimitedRunGaps++;
29817
+ };
29225
29818
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
29226
29819
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
29227
29820
  };
@@ -29526,6 +30119,7 @@ var MulticastManager = class {
29526
30119
  assertPositiveGeometry("timescale", config.timescale);
29527
30120
  assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
29528
30121
  assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
30122
+ assertPositiveGeometry("groupDurationMs", config.groupDurationMs);
29529
30123
  assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
29530
30124
  assertNonNegativeGeometry(
29531
30125
  "fecReorderToleranceMs",
@@ -29558,7 +30152,8 @@ var MulticastManager = class {
29558
30152
  timeoutMs: deliveryWindowMs,
29559
30153
  ...trackKind === void 0 ? {} : { trackKind },
29560
30154
  ...config.codec === void 0 ? {} : { codec: config.codec },
29561
- ...geometry2 === void 0 ? {} : { geometry: geometry2 }
30155
+ ...geometry2 === void 0 ? {} : { geometry: geometry2 },
30156
+ ...config.groupDurationMs === void 0 ? {} : { groupDurationMs: config.groupDurationMs }
29562
30157
  };
29563
30158
  this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
29564
30159
  this.#configureTrackMapper(packetId, fecConfig);
@@ -30259,6 +30854,70 @@ var MulticastManager = class {
30259
30854
  feedPacket(data, ingress, sourceAddress) {
30260
30855
  this.#transport.feedPacket(data, ingress, sourceAddress);
30261
30856
  }
30857
+ /**
30858
+ * Start an "mfu-datagram" leg (draft-ramadan-moq-mmt-02 4.3.1): a
30859
+ * subscription whose objects arrive as datagrams, a lossy unicast path.
30860
+ * Arms the join-boundary rules exactly as a multicast join does (the leg
30861
+ * starts at an arbitrary datagram), keeping configured tracks, decoders
30862
+ * and diagnostics. No MulticastTransport is involved: no takeover, no
30863
+ * failback watchdog, no bridge. While the leg is up the player publishes
30864
+ * `datagramLegDiagnostics(...)` in its FEC stats (`DatagramLegDiagnostics`:
30865
+ * `datagramLegJoined`, `datagramLegIngressDrops`,
30866
+ * `datagramLegRepairBeforePacketId`, `datagramUnknownAlias`,
30867
+ * `transport.maxDatagramSize`), the same keys in every player.
30868
+ */
30869
+ startDatagramLeg(options = {}) {
30870
+ this.#router.setDatagramLegPresentationBudget(options.presentationBudgetMs ?? null);
30871
+ this.#fec.beginLegJoin();
30872
+ }
30873
+ /**
30874
+ * Feed one object of an "mfu-datagram" subscription (one MMTP packet) in
30875
+ * arrival order. `ingress.tracks` names the datagram catalog track for the
30876
+ * packet id; the router restores serial order, holds FEC sources until a
30877
+ * repair states their block, and declares loss at the block deadline
30878
+ * (mmt-02 5.3.3). Bypasses MulticastTransport, unlike `feedPacket`.
30879
+ */
30880
+ feedDatagramLegPacket(packet, ingress) {
30881
+ this.#router.feedPacket(packet, "moq-datagram", ingress);
30882
+ }
30883
+ /**
30884
+ * Feed one repair object of an "mfu-datagram" track's repair track (sent
30885
+ * as datagrams, mmt-02 4.3.1): the repair track's own packet id names no
30886
+ * owner, so the subscription supplies it, as `router.feedRepairPacket`
30887
+ * does for a MoQ repair; the symbol counts as in-band (`RepairVia`
30888
+ * `inband`), unlike a FETCHed repair.
30889
+ */
30890
+ feedDatagramLegRepair(packet, ownerPacketId, catalogTrackName, repairTrackName) {
30891
+ this.#router.feedRepairPacket(packet, ownerPacketId, catalogTrackName, repairTrackName, "moq-datagram");
30892
+ }
30893
+ /**
30894
+ * End the "mfu-datagram" leg: call it when the subscription is dropped and
30895
+ * before the first packet of the path that replaces it (the ordered switch
30896
+ * to multicast, a fallback to the "mfu" track). The leg's presentation
30897
+ * bound and ledger retention stop applying; tracks, decoders, FEC state
30898
+ * and diagnostics stay, so the next path continues without a new epoch.
30899
+ */
30900
+ stopDatagramLeg() {
30901
+ this.#router.endDatagramLeg();
30902
+ }
30903
+ /** "mfu-datagram" leg packets dropped because their packet id is not the leg's (`MmtpRouter.datagramLegIngressDropCount`). */
30904
+ get datagramLegIngressDropCount() {
30905
+ return this.#router.datagramLegIngressDropCount;
30906
+ }
30907
+ /**
30908
+ * The leg's diagnostics as one object with the shared names
30909
+ * (`DatagramLegDiagnostics`): the player supplies what it alone counts and
30910
+ * spreads the result into its published FEC stats while a leg is up.
30911
+ */
30912
+ datagramLegDiagnostics(player) {
30913
+ return {
30914
+ datagramLegJoined: player.joined,
30915
+ datagramLegIngressDrops: this.#router.datagramLegIngressDropCount,
30916
+ datagramLegRepairBeforePacketId: player.repairBeforePacketId,
30917
+ datagramUnknownAlias: player.unknownAlias,
30918
+ transport: { maxDatagramSize: player.maxDatagramSize ?? null }
30919
+ };
30920
+ }
30262
30921
  /**
30263
30922
  * Declare how packets given to feedPacket() reach this manager. A consumer
30264
30923
  * that owns the multicast socket itself declares its own leg; join()
@@ -31628,15 +32287,15 @@ function asSeconds(n) {
31628
32287
  }
31629
32288
  return n;
31630
32289
  }
31631
- function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0) {
32290
+ function groupIdForTicks(ticks, groupDurationTicks2, presentationAnchorTicks = 0) {
31632
32291
  if (!Number.isInteger(ticks)) {
31633
32292
  throw new Error(
31634
32293
  `[align] groupIdForTicks: ticks must be an integer, got ${ticks}`
31635
32294
  );
31636
32295
  }
31637
- if (!Number.isInteger(groupDurationTicks) || groupDurationTicks <= 0) {
32296
+ if (!Number.isInteger(groupDurationTicks2) || groupDurationTicks2 <= 0) {
31638
32297
  throw new Error(
31639
- `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks}`
32298
+ `[align] groupIdForTicks: groupDurationTicks must be a positive integer, got ${groupDurationTicks2}`
31640
32299
  );
31641
32300
  }
31642
32301
  if (!Number.isInteger(presentationAnchorTicks)) {
@@ -31655,7 +32314,7 @@ function groupIdForTicks(ticks, groupDurationTicks, presentationAnchorTicks = 0)
31655
32314
  `[align] groupIdForTicks: ticks ${ticks} precede presentationAnchorTicks ${presentationAnchorTicks}; the publisher must reject this MPU (moq-mmt-01 4.4.1)`
31656
32315
  );
31657
32316
  }
31658
- return Math.floor(relativeTicks / groupDurationTicks);
32317
+ return Math.floor(relativeTicks / groupDurationTicks2);
31659
32318
  }
31660
32319
  function groupIdFor(mediaTimeSec, groupDurationSec) {
31661
32320
  if (!Number.isFinite(mediaTimeSec)) {
@@ -32880,6 +33539,234 @@ function resolveCatalogTrackFec(catalog, tracks) {
32880
33539
  };
32881
33540
  }
32882
33541
 
33542
+ // src/mmtp-mode-selection.ts
33543
+ function selectMmtpMode(input) {
33544
+ if (input.transportPolicy === "multicast-only") return { mode: "mfu", reason: "multicast-only" };
33545
+ if (input.override === "mfu") return { mode: "mfu", reason: "override" };
33546
+ if (!input.datagramSibling) return { mode: "mfu", reason: "no-datagram-sibling" };
33547
+ if (input.datagramFecDecodable === false) return { mode: "mfu", reason: "datagram-fec-undecodable" };
33548
+ if (input.override === "mfu-datagram") {
33549
+ return input.unreliable ? { mode: "mfu-datagram", reason: "override" } : { mode: "mfu", reason: "override-refused-reliable" };
33550
+ }
33551
+ if (!input.unreliable) return { mode: "mfu", reason: "reliable-session" };
33552
+ if (input.maxDatagramSize !== void 0 && input.symbolSize !== void 0 && input.maxDatagramSize < datagramLegObjectMax(input.symbolSize)) {
33553
+ return { mode: "mfu", reason: "repair-object-too-large" };
33554
+ }
33555
+ return { mode: "mfu-datagram", reason: "datagram" };
33556
+ }
33557
+
33558
+ // src/datagram-leg-deadline.ts
33559
+ var positive = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
33560
+ function fecWindow(fec) {
33561
+ if (!Array.isArray(fec) || !positive(fec[0]?.interleaveDepthMs)) return void 0;
33562
+ let window2 = 0;
33563
+ for (const instance of fec) {
33564
+ const tolerance = instance?.reorderToleranceMs;
33565
+ if (tolerance !== void 0 && !(typeof tolerance === "number" && Number.isFinite(tolerance) && tolerance >= 0)) {
33566
+ return void 0;
33567
+ }
33568
+ if (!positive(instance?.interleaveDepthMs)) continue;
33569
+ try {
33570
+ window2 = Math.max(window2, fecSpanDeliveryWindowMs(instance.interleaveDepthMs, tolerance));
33571
+ } catch {
33572
+ return void 0;
33573
+ }
33574
+ }
33575
+ return window2;
33576
+ }
33577
+ function computeDatagramLegDeadlines(input) {
33578
+ const window2 = fecWindow(input?.fec);
33579
+ if (window2 === void 0) return { take: false, reason: "no-fec-span" };
33580
+ const group = input.groupDurationMs;
33581
+ if (!positive(group)) return { take: false, reason: "no-group-duration", fecWindowMs: window2 };
33582
+ const delay = input.delayTargetMs;
33583
+ if (!positive(delay)) return { take: false, reason: "no-delay-target", fecWindowMs: window2 };
33584
+ const unit = positive(input.mediaUnitMs) ? input.mediaUnitMs : 0;
33585
+ const tolerance = input.fec[0]?.reorderToleranceMs;
33586
+ const fits = window2 <= delay;
33587
+ return {
33588
+ take: fits || input.forced === true,
33589
+ reason: fits ? "ok" : "fec-window-exceeds-delay-target",
33590
+ fecWindowMs: window2,
33591
+ joinDarkMs: Math.ceil(group + window2),
33592
+ darkMs: Math.ceil(Math.max(delay, window2)),
33593
+ noFrameMs: Math.ceil(Math.max(delay, group + unit + window2)),
33594
+ confirmMs: positive(tolerance) ? tolerance : unit
33595
+ };
33596
+ }
33597
+ var DatagramLegWatch = class {
33598
+ #options;
33599
+ #setTimeout;
33600
+ #clearTimeout;
33601
+ #now;
33602
+ #limits;
33603
+ #timer;
33604
+ #stopped = false;
33605
+ #pausedMs = 0;
33606
+ #pausedAt;
33607
+ #joinAt;
33608
+ #lastSourceAt;
33609
+ #frameClockAt;
33610
+ #chain = false;
33611
+ #suspect;
33612
+ constructor(options) {
33613
+ this.#options = options;
33614
+ const timers = options.timers;
33615
+ this.#setTimeout = (handler, ms) => timers ? timers.setTimeout(handler, ms) : setTimeout(handler, ms);
33616
+ this.#clearTimeout = (handle) => timers ? timers.clearTimeout(handle) : clearTimeout(handle);
33617
+ this.#now = options.now ?? (() => typeof performance === "undefined" ? Date.now() : performance.now());
33618
+ this.#joinAt = this.#clock();
33619
+ this.#arm();
33620
+ }
33621
+ /** SUBSCRIBE_OK: the join clock starts again. */
33622
+ subscribed() {
33623
+ if (this.#stopped || this.#lastSourceAt !== void 0) return;
33624
+ this.#joinAt = this.#clock();
33625
+ }
33626
+ /** A source object of the track arrived as a datagram. Never call it for repair, fill or FETCH objects. */
33627
+ source() {
33628
+ if (this.#stopped) return;
33629
+ const at2 = this.#clock();
33630
+ const first = this.#lastSourceAt === void 0;
33631
+ this.#lastSourceAt = at2;
33632
+ this.#frameClockAt ??= at2;
33633
+ if (first) this.#arm();
33634
+ }
33635
+ /**
33636
+ * A frame left the leg. Without `meta` every frame counts (audio, or a sink
33637
+ * that already counts decodable frames). With `meta` a frame counts when it
33638
+ * is a keyframe, or stands behind one with no stall decision between.
33639
+ */
33640
+ frame(meta) {
33641
+ if (this.#stopped) return;
33642
+ if (meta !== void 0) {
33643
+ if (meta.keyframe === true) this.#chain = true;
33644
+ else if (meta.gapBefore?.action === "stall") this.#chain = false;
33645
+ if (!this.#chain) return;
33646
+ }
33647
+ if (this.#frameClockAt !== void 0) this.#frameClockAt = this.#clock();
33648
+ }
33649
+ /** false while the player itself does not read the track: that time is not silence. */
33650
+ setReading(reading) {
33651
+ if (this.#stopped) return;
33652
+ if (!reading) {
33653
+ this.#pausedAt ??= this.#now();
33654
+ return;
33655
+ }
33656
+ if (this.#pausedAt === void 0) return;
33657
+ this.#pausedMs += this.#now() - this.#pausedAt;
33658
+ this.#pausedAt = void 0;
33659
+ if (this.#timer === void 0) this.#arm();
33660
+ }
33661
+ /**
33662
+ * The limits moved: arm on the new ones now. Call it when the delay target
33663
+ * shrinks, and when `limits()` first has numbers after the watch started
33664
+ * without them: an unarmed watch stays unarmed through frames and through
33665
+ * every source datagram but the first.
33666
+ */
33667
+ refresh() {
33668
+ if (this.#stopped) return;
33669
+ this.#suspect = void 0;
33670
+ this.#arm();
33671
+ }
33672
+ stop() {
33673
+ this.#stopped = true;
33674
+ this.#clear();
33675
+ }
33676
+ /** The leg's own time: it stands still while the player is not reading. */
33677
+ #clock() {
33678
+ return (this.#pausedAt ?? this.#now()) - this.#pausedMs;
33679
+ }
33680
+ #clear() {
33681
+ if (this.#timer === void 0) return;
33682
+ this.#clearTimeout(this.#timer);
33683
+ this.#timer = void 0;
33684
+ }
33685
+ #readLimits() {
33686
+ const next = this.#options.limits();
33687
+ const usable = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
33688
+ if (next && usable(next.joinDarkMs) && usable(next.darkMs) && usable(next.noFrameMs)) {
33689
+ this.#limits = {
33690
+ joinDarkMs: next.joinDarkMs,
33691
+ darkMs: next.darkMs,
33692
+ noFrameMs: next.noFrameMs,
33693
+ confirmMs: usable(next.confirmMs) ? next.confirmMs : 0
33694
+ };
33695
+ }
33696
+ return this.#limits;
33697
+ }
33698
+ #clocks(limits) {
33699
+ const joining = this.#lastSourceAt === void 0 && this.#options.joinsAtNextGroup;
33700
+ const clocks = [
33701
+ {
33702
+ clock: "dark",
33703
+ since: this.#lastSourceAt ?? this.#joinAt,
33704
+ limit: joining ? limits.joinDarkMs : limits.darkMs
33705
+ }
33706
+ ];
33707
+ if (this.#frameClockAt !== void 0) {
33708
+ clocks.push({ clock: "frame", since: this.#frameClockAt, limit: limits.noFrameMs });
33709
+ }
33710
+ return clocks;
33711
+ }
33712
+ #arm() {
33713
+ this.#clear();
33714
+ if (this.#stopped || this.#pausedAt !== void 0) return;
33715
+ const limits = this.#readLimits();
33716
+ if (!limits) return;
33717
+ const at2 = this.#clock();
33718
+ let wait = Number.POSITIVE_INFINITY;
33719
+ for (const clock of this.#clocks(limits)) {
33720
+ wait = Math.min(wait, clock.since + clock.limit - limits.confirmMs - at2);
33721
+ }
33722
+ this.#timer = this.#setTimeout(() => this.#suspectTurn(), Math.max(0, wait));
33723
+ }
33724
+ #suspectTurn() {
33725
+ this.#timer = void 0;
33726
+ if (this.#stopped || this.#pausedAt !== void 0) return;
33727
+ const limits = this.#readLimits();
33728
+ if (!limits) return;
33729
+ const at2 = this.#clock();
33730
+ const reached = this.#clocks(limits).find((clock) => at2 >= clock.since + clock.limit - limits.confirmMs);
33731
+ if (!reached) {
33732
+ this.#arm();
33733
+ return;
33734
+ }
33735
+ this.#suspect = { clock: reached.clock, since: reached.since };
33736
+ this.#timer = this.#setTimeout(() => this.#verdictTurn(), limits.confirmMs);
33737
+ }
33738
+ #verdictTurn() {
33739
+ this.#timer = void 0;
33740
+ const suspect = this.#suspect;
33741
+ this.#suspect = void 0;
33742
+ if (this.#stopped || suspect === void 0 || this.#pausedAt !== void 0) return;
33743
+ const limits = this.#readLimits();
33744
+ if (!limits) return;
33745
+ const at2 = this.#clock();
33746
+ const clock = this.#clocks(limits).find((candidate) => candidate.clock === suspect.clock);
33747
+ if (!clock || clock.since !== suspect.since) {
33748
+ this.#arm();
33749
+ return;
33750
+ }
33751
+ const silentMs = at2 - clock.since;
33752
+ if (silentMs < clock.limit) {
33753
+ this.#suspect = suspect;
33754
+ this.#timer = this.#setTimeout(() => this.#verdictTurn(), clock.limit - silentMs);
33755
+ return;
33756
+ }
33757
+ this.#stopped = true;
33758
+ const joining = this.#lastSourceAt === void 0 && this.#options.joinsAtNextGroup;
33759
+ const verdict = clock.clock === "frame" ? "no-frame" : joining ? "join" : "dark";
33760
+ this.#options.onVerdict(verdict, silentMs, clock.limit);
33761
+ }
33762
+ };
33763
+ var wholeCount = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0;
33764
+ function datagramLegRetryDelayMs(joinDarkMs, n, rand) {
33765
+ if (!positive(joinDarkMs)) return void 0;
33766
+ const jitter = typeof rand === "number" && rand >= 0 && rand < 1 ? rand : 0;
33767
+ return Math.ceil(joinDarkMs * 2 ** wholeCount(n) * (1 + jitter));
33768
+ }
33769
+
32883
33770
  // src/mmtp-fec-session.ts
32884
33771
  var PATH_BITS = { moq: 1, multicast: 2 };
32885
33772
  var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
@@ -33938,6 +34825,22 @@ function wireRepairFetch(mc, opts) {
33938
34825
  dispatch();
33939
34826
  return;
33940
34827
  }
34828
+ if (event.type === "gap") {
34829
+ if (event.action !== "stall" || event.reason !== "discontinuity") return;
34830
+ const now = performance.now();
34831
+ let expired = false;
34832
+ for (const entry2 of [...entries.values()]) {
34833
+ if (entry2.packetId !== event.stream.packetId) continue;
34834
+ if (entry2.catalogTrackName !== (event.stream.catalogTrackName ?? void 0)) continue;
34835
+ if (!entry2.running || entry2.deadlineAt > now) continue;
34836
+ stop(entry2, "expired");
34837
+ retire(entry2);
34838
+ clearEntry(entry2);
34839
+ expired = true;
34840
+ }
34841
+ if (expired) dispatch();
34842
+ return;
34843
+ }
33941
34844
  if (event.type !== "recovered" && event.type !== "failed") return;
33942
34845
  const entry = entries.get(
33943
34846
  requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? void 0)
@@ -34236,6 +35139,7 @@ export {
34236
35139
  CmsfCatalogValidationError,
34237
35140
  DEFAULT_AMT_RELAY_PORT,
34238
35141
  DEFAULT_REPAIR_PRIORITY,
35142
+ DatagramLegWatch,
34239
35143
  DeliveryGapEstimator,
34240
35144
  FECManager,
34241
35145
  FEC_BLOCK_PROFILES,
@@ -34302,11 +35206,13 @@ export {
34302
35206
  classifyHevcKeyframe,
34303
35207
  classifyPacket,
34304
35208
  codecStringFromAvcC,
35209
+ computeDatagramLegDeadlines,
34305
35210
  computeFecDeliveryWindowMediaUnits,
34306
35211
  computeFecDeliveryWindowMs,
34307
35212
  computeFecLossWindowMs,
34308
35213
  createFragment,
34309
35214
  createWasmMmtpContainerParser,
35215
+ datagramLegRetryDelayMs,
34310
35216
  datagramMfuReassembly,
34311
35217
  decideGap,
34312
35218
  decodeFecSourceInfo,
@@ -34368,6 +35274,7 @@ export {
34368
35274
  mfuReassemblyTimeoutMs,
34369
35275
  mmtpFrameReorderWindowFrames,
34370
35276
  mmtpTimestampToMicros,
35277
+ mmtpTrackIssues,
34371
35278
  multicastFromConfig,
34372
35279
  multicastFromEnv,
34373
35280
  normalizeDeliveryCatalog,
@@ -34396,6 +35303,7 @@ export {
34396
35303
  resolveRepairLayers,
34397
35304
  runtimeFecCatalogReport,
34398
35305
  secondsFromTicks,
35306
+ selectMmtpMode,
34399
35307
  setupFecWorkerForTrack,
34400
35308
  setupTrackPipeline,
34401
35309
  splitAnnexBNalUnits,