@blockcast/mmt-container 0.1.0-main.47cd40b694a0 → 0.1.0-main.57d1f55dc6a3

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 (67) hide show
  1. package/dist/browser-runtime.js +713 -104
  2. package/dist/browser-runtime.js.map +4 -4
  3. package/dist/carp-catalog.d.ts +5 -2
  4. package/dist/carp-catalog.d.ts.map +1 -1
  5. package/dist/carp-catalog.js +336 -12
  6. package/dist/carp-catalog.js.map +4 -4
  7. package/dist/catalog-fec-params.d.ts +75 -5
  8. package/dist/catalog-fec-params.d.ts.map +1 -1
  9. package/dist/catalog-fec-params.js +428 -5
  10. package/dist/catalog-fec-params.js.map +4 -4
  11. package/dist/fec-manager.js.map +2 -2
  12. package/dist/fec-worker-setup.js.map +2 -2
  13. package/dist/index.d.ts +3 -3
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +39 -1
  16. package/dist/index.js.map +2 -2
  17. package/dist/media-router.js.map +2 -2
  18. package/dist/mfu-reassembler.d.ts +45 -10
  19. package/dist/mfu-reassembler.d.ts.map +1 -1
  20. package/dist/mfu-reassembler.js +44 -19
  21. package/dist/mfu-reassembler.js.map +2 -2
  22. package/dist/mmtp-container-parser.js +44 -19
  23. package/dist/mmtp-container-parser.js.map +2 -2
  24. package/dist/mmtp-container-parser.no-modules.js +380 -31
  25. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  26. package/dist/mmtp-decode-pipeline.d.ts +34 -0
  27. package/dist/mmtp-decode-pipeline.d.ts.map +1 -1
  28. package/dist/mmtp-decode-pipeline.js +105 -43
  29. package/dist/mmtp-decode-pipeline.js.map +3 -3
  30. package/dist/mmtp-router.js +44 -19
  31. package/dist/mmtp-router.js.map +2 -2
  32. package/dist/multicast-manager.js +44 -19
  33. package/dist/multicast-manager.js.map +2 -2
  34. package/dist/no-modules.js +380 -31
  35. package/dist/no-modules.js.map +4 -4
  36. package/dist/repair-layers.d.ts +141 -0
  37. package/dist/repair-layers.d.ts.map +1 -0
  38. package/dist/repair-layers.js +303 -0
  39. package/dist/repair-layers.js.map +7 -0
  40. package/dist/track-session.d.ts +57 -13
  41. package/dist/track-session.d.ts.map +1 -1
  42. package/dist/track-session.js +128 -45
  43. package/dist/track-session.js.map +2 -2
  44. package/dist/wasm-mfu-reassembler.js.map +2 -2
  45. package/dist/wasm-mmtp-container-parser.js +44 -19
  46. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  47. package/package.json +6 -6
  48. package/schemas/catalog.schema.json +82 -5
  49. package/src/carp-catalog.ts +78 -6
  50. package/src/catalog-fec-params.ts +289 -8
  51. package/src/index.ts +31 -0
  52. package/src/mfu-reassembler.ts +100 -29
  53. package/src/mmtp-decode-pipeline.ts +93 -24
  54. package/src/repair-layers.ts +490 -0
  55. package/src/track-session.ts +181 -57
  56. package/test-vectors/catalog/README.md +16 -1
  57. package/test-vectors/catalog/negative/fec-enhancement-repair-removed.json +27 -0
  58. package/test-vectors/catalog/negative/fec-repair-layer-geometry.json +32 -0
  59. package/test-vectors/catalog/negative/fec-repair-layer-missing-symbols.json +30 -0
  60. package/test-vectors/catalog/negative/fec-repair-multiple-depends.json +31 -0
  61. package/test-vectors/catalog/negative/fec-repair-overlay-with-layer.json +33 -0
  62. package/test-vectors/catalog/negative/fec-repair-priority-out-of-band.json +23 -0
  63. package/test-vectors/catalog/negative/fec-repair-source-symbols-without-scope.json +32 -0
  64. package/test-vectors/catalog/negative/media-track-repair-layer.json +16 -0
  65. package/test-vectors/catalog/negative/raptorq-source-symbols-over-max.json +23 -0
  66. package/test-vectors/catalog/negative/repair-track-legacy-shape.json +2 -1
  67. package/test-vectors/catalog/positive/fec-layered-repair.json +104 -0
@@ -1032,7 +1032,7 @@ var COMPLETED_ADDRESS_WINDOW_MULTIPLE = 2;
1032
1032
  function parkedRunHoldsASlot(hasOpenRun, fragmentCount) {
1033
1033
  return !hasOpenRun && fragmentCount > 0;
1034
1034
  }
1035
- var _buffers, _timeouts, _activeDataUnits, _pendingContinuations, _emitted, _emittedOrder, _completed, _completedOrder, _timeoutMs, _maxBuffered, _nextAdmissionSeq, _MFUReassembler_instances, addAssociatedFragment_fn, parkContinuation_fn, drainPendingContinuations_fn, incompleteRunCount_fn, evictLeastRecentlyAdmitted_fn, releaseSlot_fn, reject_fn, associateDataUnit_fn, tryReassemble_fn, assemble_fn, setTimeout_fn, clearPendingTimeout_fn, armHeadlessPendingTimeout_fn, deletePendingRun_fn, onPendingTimeout_fn, clearTimeout_fn, markEmitted_fn, markCompleted_fn, orderValue_fn, removeActiveDataUnitForBuffer_fn, openRunAt_fn, onTimeout_fn, pendingDebugSamples_fn;
1035
+ var _buffers, _timeouts, _activeDataUnits, _pendingContinuations, _emitted, _emittedOrder, _completed, _completedOrder, _timeoutMs, _maxBuffered, _nextAdmissionSeq, _MFUReassembler_instances, addAssociatedFragment_fn, parkContinuation_fn, drainPendingContinuations_fn, unopenedParkedRunCount_fn, incompleteRunCount_fn, evictLeastRecentlyAdmitted_fn, releaseSlot_fn, reject_fn, associateDataUnit_fn, tryReassemble_fn, assemble_fn, setTimeout_fn, clearPendingTimeout_fn, armHeadlessPendingTimeout_fn, deletePendingRun_fn, onPendingTimeout_fn, clearTimeout_fn, markEmitted_fn, markCompleted_fn, orderValue_fn, removeActiveDataUnitForBuffer_fn, openRunAt_fn, onTimeout_fn, pendingDebugSamples_fn;
1036
1036
  var MFUReassembler = class {
1037
1037
  constructor(options) {
1038
1038
  __privateAdd(this, _MFUReassembler_instances);
@@ -1101,7 +1101,7 @@ var MFUReassembler = class {
1101
1101
  for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1102
1102
  if (pending.timeoutId !== void 0) clearTimeout(pending.timeoutId);
1103
1103
  delete pending.timeoutId;
1104
- if (ms !== null && __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) === void 0) {
1104
+ if (ms !== null && parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1105
1105
  pending.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address), Math.max(0, pending.startedAt + ms - now));
1106
1106
  }
1107
1107
  }
@@ -1271,7 +1271,8 @@ var MFUReassembler = class {
1271
1271
  * unit that holds a slot.
1272
1272
  *
1273
1273
  * This is not one of the four charging sites, but it shares their second term,
1274
- * so it takes the same rule. Rust's public `buffered_count()` is
1274
+ * so it takes the same rule — by delegating to `#unopenedParkedRunCount`, the
1275
+ * one site that applies it. Rust's public `buffered_count()` is
1275
1276
  * `inner.buffered_count() + unopened_parked_run_count()`, and that count is
1276
1277
  * `parked_run_holds_a_slot` — so filtering here on the open run alone would
1277
1278
  * report a phantom slot for an empty published queue in TypeScript and not in
@@ -1281,16 +1282,11 @@ var MFUReassembler = class {
1281
1282
  *
1282
1283
  * Distinct from `#incompleteRunCount`, which sums `#activeDataUnits` rather
1283
1284
  * than `#buffers`. Those are different quantities by design and are not being
1284
- * merged; only the parked term they share is required to agree.
1285
+ * merged; only the parked term they share is required to agree, which is what
1286
+ * routing both through one method makes structural rather than conventional.
1285
1287
  */
1286
1288
  get pendingCount() {
1287
- let count = __privateGet(this, _buffers).size;
1288
- for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1289
- if (parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1290
- count++;
1291
- }
1292
- }
1293
- return count;
1289
+ return __privateGet(this, _buffers).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
1294
1290
  }
1295
1291
  /**
1296
1292
  * Get current buffer status
@@ -1358,6 +1354,7 @@ parkContinuation_fn = function(address, fragment) {
1358
1354
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
1359
1355
  }
1360
1356
  }
1357
+ let reAnchored = false;
1361
1358
  if (pending === void 0) {
1362
1359
  pending = {
1363
1360
  fragments: /* @__PURE__ */ new Map(),
@@ -1372,12 +1369,13 @@ parkContinuation_fn = function(address, fragment) {
1372
1369
  pending.admissionSeq = __privateWrapper(this, _nextAdmissionSeq)._++;
1373
1370
  pending.startedAt = Date.now();
1374
1371
  __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1375
- __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
1372
+ reAnchored = true;
1376
1373
  }
1377
1374
  if (pending.fragments.has(fragment.fragmentCounter)) {
1378
1375
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "duplicate queued continuation counter would replace retained media");
1379
1376
  }
1380
1377
  pending.fragments.set(fragment.fragmentCounter, fragment);
1378
+ if (reAnchored) __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
1381
1379
  };
1382
1380
  drainPendingContinuations_fn = function(address, runKey) {
1383
1381
  while (true) {
@@ -1400,12 +1398,20 @@ drainPendingContinuations_fn = function(address, runKey) {
1400
1398
  }
1401
1399
  }
1402
1400
  };
1403
- /** Every open run plus every headless parked data unit that holds a slot,
1404
- * one slot each. This is the quantity maxBuffered bounds. Membership is
1405
- * `parkedRunHoldsASlot`, the same rule #evictLeastRecentlyAdmitted offers as
1406
- * candidates, so nothing can be counted here that eviction cannot reclaim. */
1407
- incompleteRunCount_fn = function() {
1408
- let count = __privateGet(this, _activeDataUnits).size;
1401
+ /** Parked data units that hold a `maxBuffered` slot of their own. Membership
1402
+ * is `parkedRunHoldsASlot`, the same rule #evictLeastRecentlyAdmitted offers
1403
+ * as candidates, so nothing can be counted here that eviction cannot reclaim.
1404
+ *
1405
+ * One site, two callers — `#incompleteRunCount` and `pendingCount` — mirroring
1406
+ * Rust's `unopened_parked_run_count`, which `incomplete_run_count` and
1407
+ * `buffered_count` both delegate to. Both callers used to inline this loop
1408
+ * verbatim, so converging the *rule* moved one copy and left the other as the
1409
+ * divergence (Ally's review of #400). The rule can no longer drift now that
1410
+ * every site routes through `parkedRunHoldsASlot`; keeping the loop itself at
1411
+ * one site is what stops the scaffolding drifting the next time this question
1412
+ * grows an argument. */
1413
+ unopenedParkedRunCount_fn = function() {
1414
+ let count = 0;
1409
1415
  for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1410
1416
  if (parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1411
1417
  count++;
@@ -1413,6 +1419,14 @@ incompleteRunCount_fn = function() {
1413
1419
  }
1414
1420
  return count;
1415
1421
  };
1422
+ /** Every open run plus every headless parked data unit that holds a slot,
1423
+ * one slot each. This is the quantity maxBuffered bounds. The parked term is
1424
+ * `#unopenedParkedRunCount`, whose membership is `parkedRunHoldsASlot` — the
1425
+ * same rule #evictLeastRecentlyAdmitted offers as candidates, so nothing can
1426
+ * be counted here that eviction cannot reclaim. */
1427
+ incompleteRunCount_fn = function() {
1428
+ return __privateGet(this, _activeDataUnits).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
1429
+ };
1416
1430
  /**
1417
1431
  * Drop the incomplete data unit admitted longest ago so a newly arriving one
1418
1432
  * can take its slot. Selection is by monotonic admission ordinal, never by
@@ -1652,11 +1666,18 @@ clearPendingTimeout_fn = function(address) {
1652
1666
  /**
1653
1667
  * A queue whose run closed without completing is headless again and expires
1654
1668
  * from its own first arrival, exactly as it would had the head never come.
1669
+ *
1670
+ * An empty queue is not armed: it holds no data unit that could fail to
1671
+ * complete, so there is nothing for a deadline to expire. Both arming sites
1672
+ * take that test through `parkedRunHoldsASlot` rather than filtering on the
1673
+ * open run alone, which is how this engine reaches Rust's answer — its
1674
+ * `next_timeout_at` derives candidate deadlines from the queue's live
1675
+ * entries, so an empty queue yields none (BLO-32420).
1655
1676
  */
1656
1677
  armHeadlessPendingTimeout_fn = function(address) {
1657
1678
  const pending = __privateGet(this, _pendingContinuations).get(address);
1658
1679
  if (pending === void 0 || pending.timeoutId !== void 0 || __privateGet(this, _timeoutMs) === null) return;
1659
- if (__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0) return;
1680
+ if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) return;
1660
1681
  pending.timeoutId = setTimeout(
1661
1682
  () => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address),
1662
1683
  Math.max(0, pending.startedAt + __privateGet(this, _timeoutMs) - Date.now())
@@ -1669,6 +1690,10 @@ deletePendingRun_fn = function(address) {
1669
1690
  onPendingTimeout_fn = function(address) {
1670
1691
  const pending = __privateGet(this, _pendingContinuations).get(address);
1671
1692
  if (pending === void 0) return;
1693
+ if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1694
+ __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1695
+ return;
1696
+ }
1672
1697
  this.stats.timedOutMFUs++;
1673
1698
  console.warn(
1674
1699
  `[MfuReassembler] timeout: run=${address} fragments=${pending.fragments.size} (continuations awaiting first fragment, discarded)`
@@ -5782,6 +5807,289 @@ function resolveMulticastAuthCatalog(catalog, playerMode) {
5782
5807
  };
5783
5808
  }
5784
5809
 
5810
+ // src/repair-layers.ts
5811
+ var REPAIR_PRIORITY_MIN = 192;
5812
+ var REPAIR_PRIORITY_MAX = 255;
5813
+ var DEFAULT_REPAIR_PRIORITY = 240;
5814
+ var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
5815
+ var MAX_REPAIR_SYMBOLS = 16777215;
5816
+ var MAX_ENCODING_SYMBOL_ID = 16777215;
5817
+ var RepairContractError = class extends Error {
5818
+ constructor(code, path, message) {
5819
+ super(`[repair-layers:${code}] ${path}: ${message}`);
5820
+ this.code = code;
5821
+ this.path = path;
5822
+ this.name = "RepairContractError";
5823
+ }
5824
+ };
5825
+ var throwRepairContractError = (code, path, message) => {
5826
+ throw new RepairContractError(code, path, message);
5827
+ };
5828
+ var REPAIR_FIELDS = ["depends", "repairLayer", "repairSymbols", "priority", "scope", "sourceSymbols"];
5829
+ var REPAIR_TRACK_GEOMETRY_KEYS = [
5830
+ "mmtpMode",
5831
+ "timescale",
5832
+ "groupDurationMs",
5833
+ "groupDurationTicks",
5834
+ "keyframeIntervalMs",
5835
+ "keyframeIntervalTicks",
5836
+ "fec",
5837
+ "symbolSize",
5838
+ "interleaveDepthMs"
5839
+ ];
5840
+ var REPAIR_TRACK_ONLY_KEYS = ["repairLayer", "repairSymbols", "sourceSymbols", "scope"];
5841
+ function rejectRepairTrackGeometry(path, fields, fail) {
5842
+ for (const key of REPAIR_TRACK_GEOMETRY_KEYS) {
5843
+ if (fields[key] !== void 0) {
5844
+ fail(
5845
+ "track_repair_geometry",
5846
+ `${path}.${key}`,
5847
+ "a repair track carries no block geometry; it is shared with the source track's fec object"
5848
+ );
5849
+ }
5850
+ }
5851
+ }
5852
+ function repairReachability(fecObjects) {
5853
+ let declaresFecSource = false;
5854
+ const layerZeroNames = /* @__PURE__ */ new Set();
5855
+ for (const candidate of fecObjects) {
5856
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) continue;
5857
+ const fec = candidate;
5858
+ if (fec["algorithm"] === "none") continue;
5859
+ declaresFecSource = true;
5860
+ const repairTrack = fec["repairTrack"];
5861
+ if (typeof repairTrack === "string" && repairTrack.length > 0) layerZeroNames.add(repairTrack);
5862
+ }
5863
+ return { declaresFecSource, layerZeroNames };
5864
+ }
5865
+ function assertRepairTrackReachable(descriptor, reachability, fail) {
5866
+ if (dependsTarget(descriptor) !== void 0) return;
5867
+ if (reachability.declaresFecSource && !reachability.layerZeroNames.has(descriptor.name)) {
5868
+ fail(
5869
+ "track_repair_depends",
5870
+ `${descriptor.path}.depends`,
5871
+ "no source names this repair track in fec.repairTrack and it declares no depends"
5872
+ );
5873
+ }
5874
+ }
5875
+ function rejectRepairFieldsOnMediaTrack(path, fields, fail) {
5876
+ for (const key of REPAIR_TRACK_ONLY_KEYS) {
5877
+ if (fields[key] !== void 0) {
5878
+ fail("track_repair_layer", `${path}.${key}`, `${key} is a repair track field`);
5879
+ }
5880
+ }
5881
+ }
5882
+ function describeRepairTrack(name, path, fields) {
5883
+ const descriptor = { name, path };
5884
+ for (const field of REPAIR_FIELDS) {
5885
+ if (field in fields) descriptor[field] = fields[field];
5886
+ }
5887
+ return descriptor;
5888
+ }
5889
+ function isSafeInteger(value) {
5890
+ return typeof value === "number" && Number.isSafeInteger(value);
5891
+ }
5892
+ function positiveInteger(value) {
5893
+ return isSafeInteger(value) && value > 0;
5894
+ }
5895
+ function dependsTarget(descriptor) {
5896
+ const depends = descriptor.depends;
5897
+ return Array.isArray(depends) && depends.length === 1 && typeof depends[0] === "string" && depends[0].length > 0 ? depends[0] : void 0;
5898
+ }
5899
+ function validateRepairTrackFields(descriptor, fail) {
5900
+ const { path } = descriptor;
5901
+ if (descriptor.depends !== void 0 && dependsTarget(descriptor) === void 0) {
5902
+ fail("track_repair_depends", `${path}.depends`, "must name exactly one source track");
5903
+ }
5904
+ if (descriptor.repairLayer !== void 0 && (!isSafeInteger(descriptor.repairLayer) || descriptor.repairLayer < 0)) {
5905
+ fail("track_repair_layer", `${path}.repairLayer`, "must be a non-negative integer");
5906
+ }
5907
+ if (descriptor.repairSymbols !== void 0 && (!positiveInteger(descriptor.repairSymbols) || descriptor.repairSymbols > MAX_REPAIR_SYMBOLS)) {
5908
+ fail("track_repair_layer", `${path}.repairSymbols`, `must be a positive integer at most ${MAX_REPAIR_SYMBOLS}`);
5909
+ }
5910
+ if (descriptor.priority !== void 0 && (!isSafeInteger(descriptor.priority) || descriptor.priority < REPAIR_PRIORITY_MIN || descriptor.priority > REPAIR_PRIORITY_MAX)) {
5911
+ fail(
5912
+ "track_repair_priority",
5913
+ `${path}.priority`,
5914
+ `must be an integer from ${REPAIR_PRIORITY_MIN} to ${REPAIR_PRIORITY_MAX} (MoQT scale, lower first)`
5915
+ );
5916
+ }
5917
+ if (descriptor.scope !== void 0) {
5918
+ if (descriptor.scope !== "keyframe") {
5919
+ fail("track_repair_overlay", `${path}.scope`, 'must be "keyframe"');
5920
+ }
5921
+ if (descriptor.repairLayer !== void 0) {
5922
+ fail("track_repair_overlay", `${path}.repairLayer`, "an overlay is a separate FEC instance and carries no repairLayer");
5923
+ }
5924
+ for (const field of ["depends", "sourceSymbols", "repairSymbols", "priority"]) {
5925
+ if (descriptor[field] === void 0) {
5926
+ fail("track_repair_overlay", `${path}.${field}`, `an overlay must declare ${field}`);
5927
+ }
5928
+ }
5929
+ }
5930
+ if (descriptor.sourceSymbols !== void 0) {
5931
+ if (descriptor.scope === void 0) {
5932
+ fail("track_repair_overlay", `${path}.sourceSymbols`, "only an overlay (scope: keyframe) declares its own sourceSymbols");
5933
+ }
5934
+ if (!positiveInteger(descriptor.sourceSymbols) || descriptor.sourceSymbols > MAX_RAPTORQ_SOURCE_SYMBOLS) {
5935
+ fail(
5936
+ "track_fec_bounds",
5937
+ `${path}.sourceSymbols`,
5938
+ `must be a positive integer at most ${MAX_RAPTORQ_SOURCE_SYMBOLS} (RFC 6330 source block limit)`
5939
+ );
5940
+ }
5941
+ }
5942
+ if (isSafeInteger(descriptor.repairLayer) && descriptor.repairLayer >= 1) {
5943
+ for (const field of ["depends", "repairSymbols", "priority"]) {
5944
+ if (descriptor[field] === void 0) {
5945
+ fail("track_repair_layer", `${path}.${field}`, `repair layer ${descriptor.repairLayer} must declare ${field}`);
5946
+ }
5947
+ }
5948
+ }
5949
+ }
5950
+ function assembleRepairLayers(source, descriptors, fail = throwRepairContractError, options = {}) {
5951
+ const layerZeroName = typeof source.repairTrack === "string" && source.repairTrack.length > 0 ? source.repairTrack : void 0;
5952
+ const layerZero = layerZeroName === void 0 ? void 0 : descriptors.find((d) => d.name === layerZeroName);
5953
+ if (layerZeroName !== void 0 && layerZero === void 0 && options.layerZeroMustBeDeclared) {
5954
+ fail("track_repair_track", `${source.path}.repairTrack`, `unknown FEC repair track ${JSON.stringify(layerZeroName)}`);
5955
+ }
5956
+ const dependents = descriptors.filter((d) => d.name !== layerZeroName && dependsTarget(d) === source.name);
5957
+ const k = positiveInteger(source.sourceSymbols) ? source.sourceSymbols : 0;
5958
+ if (source.algorithm === "raptorq" && k > MAX_RAPTORQ_SOURCE_SYMBOLS) {
5959
+ fail(
5960
+ "track_fec_bounds",
5961
+ `${source.path}.sourceSymbols`,
5962
+ `must be at most ${MAX_RAPTORQ_SOURCE_SYMBOLS} (RFC 6330 source block limit)`
5963
+ );
5964
+ }
5965
+ if (layerZeroName === void 0) {
5966
+ if (dependents.length === 0) return void 0;
5967
+ fail(
5968
+ "track_repair_layer",
5969
+ `${dependents[0].path}.depends`,
5970
+ `repair layers of ${JSON.stringify(source.name)} require a layer 0 (fec.repairTrack) on the source`
5971
+ );
5972
+ }
5973
+ const layered = dependents.length > 0;
5974
+ let layerZeroSymbols = 0;
5975
+ if (positiveInteger(source.repairSymbols)) {
5976
+ layerZeroSymbols = source.repairSymbols;
5977
+ } else if (layered) {
5978
+ fail("track_fec", `${source.path}.repairSymbols`, "layered or overlay repair needs a positive integer repairSymbols on layer 0");
5979
+ }
5980
+ if (layered && !positiveInteger(source.sourceSymbols)) {
5981
+ fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
5982
+ }
5983
+ if (layered && source.algorithm !== "raptorq") {
5984
+ fail(
5985
+ "track_fec",
5986
+ `${source.path}.algorithm`,
5987
+ "repair layers and overlays are defined only for raptorq: a block code fixes its codeword length, so symbols of a larger P are not symbols of the code a receiver holding fewer layers decodes"
5988
+ );
5989
+ }
5990
+ let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
5991
+ if (layerZero !== void 0) {
5992
+ if (layerZero.depends !== void 0 && dependsTarget(layerZero) !== source.name) {
5993
+ fail(
5994
+ "track_repair_depends",
5995
+ `${layerZero.path}.depends`,
5996
+ `layer 0 of ${JSON.stringify(source.name)} must depend on that source`
5997
+ );
5998
+ }
5999
+ if (layerZero.repairLayer !== void 0 && layerZero.repairLayer !== 0) {
6000
+ fail("track_repair_layer", `${layerZero.path}.repairLayer`, "the track named by fec.repairTrack is layer 0");
6001
+ }
6002
+ if (layerZero.scope !== void 0) {
6003
+ fail("track_repair_overlay", `${layerZero.path}.scope`, "the track named by fec.repairTrack is base layer 0, not an overlay");
6004
+ }
6005
+ if (layerZero.repairSymbols !== void 0 && layerZero.repairSymbols !== layerZeroSymbols) {
6006
+ fail(
6007
+ "track_repair_layer",
6008
+ `${layerZero.path}.repairSymbols`,
6009
+ `must agree with the source's fec.repairSymbols (${layerZeroSymbols})`
6010
+ );
6011
+ }
6012
+ if (typeof layerZero.priority === "number") layerZeroPriority = layerZero.priority;
6013
+ }
6014
+ const baseLayers = [
6015
+ { layer: 0, repairTrackName: layerZeroName, repairSymbols: layerZeroSymbols, rsIdOffset: 0, priority: layerZeroPriority }
6016
+ ];
6017
+ const overlays = [];
6018
+ for (const d of dependents) {
6019
+ if (d.scope === void 0 && d.repairLayer === void 0) {
6020
+ fail(
6021
+ "track_repair_layer",
6022
+ `${d.path}.repairLayer`,
6023
+ `a repair track that depends on ${JSON.stringify(source.name)} must declare repairLayer (1..n) or scope: "keyframe"`
6024
+ );
6025
+ }
6026
+ }
6027
+ const layerTracks = dependents.filter((d) => d.scope === void 0).sort((a, b) => a.repairLayer - b.repairLayer);
6028
+ for (const d of dependents) {
6029
+ if (d.scope !== "keyframe") continue;
6030
+ if (overlays.length === 1) {
6031
+ fail(
6032
+ "track_repair_overlay",
6033
+ `${d.path}.scope`,
6034
+ `${JSON.stringify(source.name)} already has keyframe overlay ${JSON.stringify(overlays[0].repairTrackName)}: a RAP packet carries exactly two Source FEC Payload IDs (base, then overlay), so one overlay per source`
6035
+ );
6036
+ }
6037
+ const sourceSymbols = d.sourceSymbols;
6038
+ const repairSymbols = d.repairSymbols;
6039
+ if (sourceSymbols + repairSymbols - 1 > MAX_ENCODING_SYMBOL_ID) {
6040
+ fail(
6041
+ "track_fec_bounds",
6042
+ `${d.path}.repairSymbols`,
6043
+ `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6044
+ );
6045
+ }
6046
+ overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
6047
+ }
6048
+ let offset = layerZeroSymbols;
6049
+ let previousPriority = layerZeroPriority;
6050
+ layerTracks.forEach((d, i) => {
6051
+ const expected = i + 1;
6052
+ if (d.repairLayer === 0) {
6053
+ fail("track_repair_layer", `${d.path}.repairLayer`, `layer 0 of ${JSON.stringify(source.name)} is ${JSON.stringify(layerZeroName)}, named by fec.repairTrack`);
6054
+ }
6055
+ if (d.repairLayer !== expected) {
6056
+ fail(
6057
+ "track_repair_layer",
6058
+ `${d.path}.repairLayer`,
6059
+ i > 0 && d.repairLayer === layerTracks[i - 1].repairLayer ? `repair layer ${d.repairLayer} is declared twice for ${JSON.stringify(source.name)}` : `repair layers must be contiguous from 1: expected ${expected}, found ${d.repairLayer}`
6060
+ );
6061
+ }
6062
+ const priority = d.priority;
6063
+ if (priority < previousPriority) {
6064
+ fail(
6065
+ "track_repair_priority",
6066
+ `${d.path}.priority`,
6067
+ `must be at least ${previousPriority}, the priority of layer ${expected - 1}: priority is monotonic non-decreasing with layer index`
6068
+ );
6069
+ }
6070
+ previousPriority = priority;
6071
+ const repairSymbols = d.repairSymbols;
6072
+ baseLayers.push({ layer: expected, repairTrackName: d.name, repairSymbols, rsIdOffset: offset, priority });
6073
+ offset += repairSymbols;
6074
+ });
6075
+ const totalBaseRepairSymbols = offset;
6076
+ if (totalBaseRepairSymbols > MAX_REPAIR_SYMBOLS) {
6077
+ fail(
6078
+ "track_fec_bounds",
6079
+ `${layerTracks.length === 0 ? source.path : layerTracks[layerTracks.length - 1].path}.repairSymbols`,
6080
+ `total repair symbols across base layers exceeds the 24-bit RS_ID space (${MAX_REPAIR_SYMBOLS})`
6081
+ );
6082
+ }
6083
+ if (k + totalBaseRepairSymbols - 1 > MAX_ENCODING_SYMBOL_ID) {
6084
+ fail(
6085
+ "track_fec_bounds",
6086
+ `${source.path}.sourceSymbols`,
6087
+ `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6088
+ );
6089
+ }
6090
+ return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
6091
+ }
6092
+
5785
6093
  // src/carp-catalog.ts
5786
6094
  var VALID_ROLE_SUFFIXES = /* @__PURE__ */ new Set(["base", "delta", "repair"]);
5787
6095
  function parseTrackRole(trackName) {
@@ -5908,7 +6216,7 @@ function validateCmsfMmtpCatalog(value) {
5908
6216
  const tracks = catalog["tracks"];
5909
6217
  const trackRecords = [];
5910
6218
  const effective = (track, field) => track[field] ?? common[field];
5911
- const positiveInteger = (input) => Number.isSafeInteger(input) && input > 0;
6219
+ const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
5912
6220
  const positiveNumber = (input) => typeof input === "number" && Number.isFinite(input) && input > 0;
5913
6221
  for (let index = 0; index < tracks.length; index++) {
5914
6222
  const raw = tracks[index];
@@ -5944,21 +6252,27 @@ function validateCmsfMmtpCatalog(value) {
5944
6252
  const groupDurationTicks = effective(track, "groupDurationTicks");
5945
6253
  const keyframeIntervalMs = effective(track, "keyframeIntervalMs");
5946
6254
  const keyframeIntervalTicks = effective(track, "keyframeIntervalTicks");
5947
- if (groupDurationMs !== void 0 && !positiveInteger(groupDurationMs)) {
6255
+ if (groupDurationMs !== void 0 && !positiveInteger2(groupDurationMs)) {
5948
6256
  catalogError("track_group_duration_ms", `${path}.groupDurationMs`, "must be a positive integer");
5949
6257
  }
5950
- if (groupDurationTicks !== void 0 && !positiveInteger(groupDurationTicks)) {
6258
+ if (groupDurationTicks !== void 0 && !positiveInteger2(groupDurationTicks)) {
5951
6259
  catalogError("track_group_duration_ticks", `${path}.groupDurationTicks`, "must be a positive integer");
5952
6260
  }
5953
- if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger(keyframeIntervalTicks)) {
6261
+ if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
5954
6262
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
5955
6263
  }
6264
+ if (packaging === "fec-repair") {
6265
+ rejectRepairTrackGeometry(path, track, catalogError);
6266
+ validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
6267
+ } else {
6268
+ rejectRepairFieldsOnMediaTrack(path, track, catalogError);
6269
+ }
5956
6270
  if (packaging === "mmtp") {
5957
6271
  const mmtpMode = effective(track, "mmtpMode");
5958
6272
  if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
5959
6273
  catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
5960
6274
  }
5961
- if (!positiveInteger(timescale)) {
6275
+ if (!positiveInteger2(timescale)) {
5962
6276
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
5963
6277
  }
5964
6278
  if (groupDurationMs === void 0 && groupDurationTicks === void 0) {
@@ -5985,12 +6299,19 @@ function validateCmsfMmtpCatalog(value) {
5985
6299
  if ("interleaveDepth" in config || "interleaveMs" in config) {
5986
6300
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
5987
6301
  }
5988
- if (config["interleaveDepthMs"] !== void 0 && !positiveInteger(config["interleaveDepthMs"])) {
6302
+ if ("enhancementRepair" in config) {
6303
+ catalogError(
6304
+ "track_fec",
6305
+ `${path}.fec.enhancementRepair`,
6306
+ "repair layers are self-describing fec-repair tracks (depends, repairLayer); fec.enhancementRepair is not supported"
6307
+ );
6308
+ }
6309
+ if (config["interleaveDepthMs"] !== void 0 && !positiveInteger2(config["interleaveDepthMs"])) {
5989
6310
  catalogError("track_fec", `${path}.fec.interleaveDepthMs`, "must be a positive integer");
5990
6311
  }
5991
6312
  if (algorithm !== "none") {
5992
6313
  for (const field of ["sourceSymbols", "repairSymbols", "symbolSize"]) {
5993
- if (!positiveInteger(config[field])) {
6314
+ if (!positiveInteger2(config[field])) {
5994
6315
  catalogError("track_fec", `${path}.fec.${field}`, "must be a positive integer");
5995
6316
  }
5996
6317
  }
@@ -6000,15 +6321,43 @@ function validateCmsfMmtpCatalog(value) {
6000
6321
  }
6001
6322
  }
6002
6323
  }
6324
+ const repairDescriptors = trackRecords.flatMap(
6325
+ (track, index) => effective(track, "packaging") === "fec-repair" ? [describeRepairTrack(track["name"], `$.tracks[${index}]`, track)] : []
6326
+ );
6327
+ const reachability = repairReachability(
6328
+ trackRecords.filter((track) => effective(track, "packaging") !== "fec-repair").map((track) => track["fec"])
6329
+ );
6330
+ for (const descriptor of repairDescriptors) {
6331
+ assertRepairTrackReachable(descriptor, reachability, catalogError);
6332
+ const target = dependsTarget(descriptor);
6333
+ if (target === void 0) continue;
6334
+ const source = trackRecords.find((candidate) => candidate["name"] === target);
6335
+ const sourceFec = source?.["fec"];
6336
+ if (!source || effective(source, "packaging") !== "mmtp" || !sourceFec || sourceFec["algorithm"] === "none") {
6337
+ catalogError(
6338
+ "track_repair_depends",
6339
+ `${descriptor.path}.depends`,
6340
+ `${JSON.stringify(target)} is not an mmtp track with FEC`
6341
+ );
6342
+ }
6343
+ }
6003
6344
  for (let index = 0; index < trackRecords.length; index++) {
6004
6345
  const track = trackRecords[index];
6005
6346
  const fec = track["fec"];
6006
6347
  if (!fec || fec["algorithm"] === "none") continue;
6007
- const repairTrack = fec["repairTrack"];
6008
- const target = trackRecords.find((candidate) => candidate["name"] === repairTrack);
6009
- if (!target || effective(target, "packaging") !== "fec-repair") {
6010
- catalogError("track_repair_track", `$.tracks[${index}].fec.repairTrack`, `unknown FEC repair track ${JSON.stringify(repairTrack)}`);
6011
- }
6348
+ assembleRepairLayers(
6349
+ {
6350
+ name: track["name"],
6351
+ path: `$.tracks[${index}].fec`,
6352
+ algorithm: fec["algorithm"],
6353
+ sourceSymbols: fec["sourceSymbols"],
6354
+ repairSymbols: fec["repairSymbols"],
6355
+ repairTrack: fec["repairTrack"]
6356
+ },
6357
+ repairDescriptors,
6358
+ catalogError,
6359
+ { layerZeroMustBeDeclared: true }
6360
+ );
6012
6361
  }
6013
6362
  const switchingSets = /* @__PURE__ */ new Map();
6014
6363
  for (let index = 0; index < trackRecords.length; index++) {
@@ -8685,7 +9034,7 @@ function computeFecDeliveryWindowMediaUnits(config, timestampTimescale) {
8685
9034
  }
8686
9035
  return deliveryWindow;
8687
9036
  }
8688
- var _state, _subscription, _hysteresisTimer, _joinDeadlineTimer, _previousPrimary, _manager, _suppressFired, _TrackSession_instances, transition_fn, clearHysteresis_fn, armJoinDeadline_fn, clearJoinDeadline_fn, suppress_fn, unsuppress_fn;
9037
+ var _state, _subscription, _hysteresisTimer, _joinDeadlineTimer, _previousPrimary, _manager, _suppressFired, _fecArmed, _TrackSession_instances, transition_fn, clearHysteresis_fn, armJoinDeadline_fn, clearJoinDeadline_fn, armFec_fn, disarmFec_fn, suppress_fn, unsuppress_fn;
8689
9038
  var TrackSession = class {
8690
9039
  constructor(config, manager) {
8691
9040
  __privateAdd(this, _TrackSession_instances);
@@ -8702,6 +9051,12 @@ var TrackSession = class {
8702
9051
  // from `failing` (exactly where a starving track sits) was re-subscribed to
8703
9052
  // unicast with the host's media still muted: MoQ playing into a dead sink.
8704
9053
  __privateAdd(this, _suppressFired, false);
9054
+ // Single FEC authority flag: set by the fec-setup edges (joinStarted,
9055
+ // enterUnicastFallback), cleared by the fec-teardown edge in #transition.
9056
+ // Setup and teardown are paired by construction, so a takeover timeout that
9057
+ // parks the session in `unicast` keeps the decoder the still-joined
9058
+ // transport is feeding, and the later unsubscribe still tears it down.
9059
+ __privateAdd(this, _fecArmed, false);
8705
9060
  this.config = config;
8706
9061
  __privateSet(this, _manager, manager);
8707
9062
  }
@@ -8776,7 +9131,7 @@ var TrackSession = class {
8776
9131
  joinStarted() {
8777
9132
  if (__privateGet(this, _state) !== "unicast") return;
8778
9133
  __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "joining");
8779
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-setup" }, this.config);
9134
+ __privateMethod(this, _TrackSession_instances, armFec_fn).call(this);
8780
9135
  }
8781
9136
  /**
8782
9137
  * any non-fallback state → unicast-fallback. Used when the SSM bridge is
@@ -8797,7 +9152,7 @@ var TrackSession = class {
8797
9152
  __privateMethod(this, _TrackSession_instances, clearHysteresis_fn).call(this);
8798
9153
  __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast-fallback");
8799
9154
  __privateMethod(this, _TrackSession_instances, suppress_fn).call(this);
8800
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-setup" }, this.config);
9155
+ __privateMethod(this, _TrackSession_instances, armFec_fn).call(this);
8801
9156
  }
8802
9157
  /**
8803
9158
  * unicast-fallback → unicast. Called when the SSM bridge appears mid-session
@@ -8856,23 +9211,19 @@ var TrackSession = class {
8856
9211
  const prefs = this.config.preferredTransports;
8857
9212
  const currentIdx = current ? prefs.indexOf(current) : -1;
8858
9213
  const nextMode = prefs[currentIdx + 1];
8859
- if (nextMode) {
8860
- if (nextMode === "moq") {
8861
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast");
8862
- __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
8863
- if (this.config.trackType === "audio") {
8864
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "reset" }, this.config);
8865
- }
8866
- } else {
8867
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "joining");
8868
- __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
8869
- }
8870
- } else {
8871
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast");
9214
+ if (nextMode !== void 0 && nextMode !== "moq") {
9215
+ __privateSet(this, _previousPrimary, nextMode);
9216
+ __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "joining");
8872
9217
  __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
8873
- if (this.config.trackType === "audio") {
8874
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "reset" }, this.config);
8875
- }
9218
+ return;
9219
+ }
9220
+ const from = __privateGet(this, _state);
9221
+ __privateSet(this, _previousPrimary, null);
9222
+ __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast");
9223
+ __privateMethod(this, _TrackSession_instances, disarmFec_fn).call(this);
9224
+ __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
9225
+ if (from !== "unicast" && this.config.trackType === "audio") {
9226
+ __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "reset" }, this.config);
8876
9227
  }
8877
9228
  }
8878
9229
  /** Hysteresis expired → failback to next transport (Claim 9g). */
@@ -8896,11 +9247,20 @@ var TrackSession = class {
8896
9247
  get isUnicastFallback() {
8897
9248
  return __privateGet(this, _state) === "unicast-fallback";
8898
9249
  }
9250
+ /**
9251
+ * True while this track owns a FEC decoder (fec-setup fired, fec-teardown
9252
+ * not yet). Stays true across a takeover timeout that parked the session in
9253
+ * `unicast`; SessionManager.failbackAll uses it to release such sessions.
9254
+ */
9255
+ get isFecArmed() {
9256
+ return __privateGet(this, _fecArmed);
9257
+ }
8899
9258
  dispose() {
8900
9259
  __privateMethod(this, _TrackSession_instances, clearHysteresis_fn).call(this);
8901
9260
  __privateMethod(this, _TrackSession_instances, clearJoinDeadline_fn).call(this);
8902
9261
  __privateSet(this, _state, "idle");
8903
9262
  __privateSet(this, _subscription, null);
9263
+ __privateMethod(this, _TrackSession_instances, disarmFec_fn).call(this);
8904
9264
  }
8905
9265
  };
8906
9266
  _state = new WeakMap();
@@ -8910,20 +9270,20 @@ _joinDeadlineTimer = new WeakMap();
8910
9270
  _previousPrimary = new WeakMap();
8911
9271
  _manager = new WeakMap();
8912
9272
  _suppressFired = new WeakMap();
9273
+ _fecArmed = new WeakMap();
8913
9274
  _TrackSession_instances = new WeakSet();
8914
9275
  // -----------------------------------------------------------------------
8915
9276
  // Internal
8916
9277
  // -----------------------------------------------------------------------
8917
- transition_fn = function(to) {
9278
+ transition_fn = function(to, opts) {
8918
9279
  const from = __privateGet(this, _state);
8919
9280
  if (from === to) return;
9281
+ const joinDeadlineMs = to === "joining" ? __privateGet(this, _manager).takeoverDeadlineMs : void 0;
8920
9282
  __privateSet(this, _state, to);
8921
9283
  if (from === "joining") __privateMethod(this, _TrackSession_instances, clearJoinDeadline_fn).call(this);
8922
- if (to === "joining") __privateMethod(this, _TrackSession_instances, armJoinDeadline_fn).call(this);
9284
+ if (joinDeadlineMs !== void 0) __privateMethod(this, _TrackSession_instances, armJoinDeadline_fn).call(this, joinDeadlineMs);
8923
9285
  const fecActive = (s) => s === "joining" || s === "multicast" || s === "amt" || s === "failing" || s === "unicast-fallback";
8924
- if (fecActive(from) && !fecActive(to)) {
8925
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-teardown" }, this.config);
8926
- }
9286
+ if (!fecActive(to) && !opts?.retainFec) __privateMethod(this, _TrackSession_instances, disarmFec_fn).call(this);
8927
9287
  __privateGet(this, _manager).callbacks?.onStateChange?.(this.config.trackName, from, to);
8928
9288
  };
8929
9289
  clearHysteresis_fn = function() {
@@ -8932,14 +9292,13 @@ clearHysteresis_fn = function() {
8932
9292
  __privateSet(this, _hysteresisTimer, null);
8933
9293
  }
8934
9294
  };
8935
- armJoinDeadline_fn = function() {
9295
+ armJoinDeadline_fn = function(deadlineMs) {
8936
9296
  __privateMethod(this, _TrackSession_instances, clearJoinDeadline_fn).call(this);
8937
- const deadlineMs = __privateGet(this, _manager).takeoverDeadlineMs;
8938
- if (deadlineMs <= 0) return;
9297
+ if (deadlineMs === 0) return;
8939
9298
  __privateSet(this, _joinDeadlineTimer, setTimeout(() => {
8940
9299
  __privateSet(this, _joinDeadlineTimer, null);
8941
9300
  if (__privateGet(this, _state) !== "joining") return;
8942
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast");
9301
+ __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast", { retainFec: true });
8943
9302
  __privateGet(this, _manager).callbacks?.onTakeoverTimeout?.(this.config.trackName);
8944
9303
  }, deadlineMs));
8945
9304
  };
@@ -8949,6 +9308,18 @@ clearJoinDeadline_fn = function() {
8949
9308
  __privateSet(this, _joinDeadlineTimer, null);
8950
9309
  }
8951
9310
  };
9311
+ /** Fire fec-setup exactly once per FEC epoch. */
9312
+ armFec_fn = function() {
9313
+ if (__privateGet(this, _fecArmed)) return;
9314
+ __privateSet(this, _fecArmed, true);
9315
+ __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-setup" }, this.config);
9316
+ };
9317
+ /** Fire fec-teardown for an armed decoder; no-op when none is armed. */
9318
+ disarmFec_fn = function() {
9319
+ if (!__privateGet(this, _fecArmed)) return;
9320
+ __privateSet(this, _fecArmed, false);
9321
+ __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-teardown" }, this.config);
9322
+ };
8952
9323
  /** Fire onSuppress(true) exactly once per suppression epoch. */
8953
9324
  suppress_fn = function() {
8954
9325
  if (__privateGet(this, _suppressFired)) return;
@@ -8961,18 +9332,14 @@ unsuppress_fn = function() {
8961
9332
  __privateSet(this, _suppressFired, false);
8962
9333
  __privateGet(this, _manager).callbacks?.onSuppress?.(this.config.trackName, false);
8963
9334
  };
9335
+ var MAX_TAKEOVER_DEADLINE_MS = 2147483647;
9336
+ var _takeoverDeadlineMs, _SessionManager_instances, requireTakeoverDeadlineMs_fn;
8964
9337
  var SessionManager = class {
8965
9338
  constructor(poolOptions) {
9339
+ __privateAdd(this, _SessionManager_instances);
8966
9340
  this.sessions = /* @__PURE__ */ new Map();
8967
9341
  this.callbacks = null;
8968
- /**
8969
- * Takeover deadline (BLO-9413/D9): max time a session may sit in `joining`
8970
- * without a RAP before returning to `unicast` and firing onTakeoverTimeout.
8971
- * MoQ is never suppressed during `joining`, so expiry is a silent abandon —
8972
- * playback never glitches. Hosts tune per stream (e.g. GOP length); 0
8973
- * disables.
8974
- */
8975
- this.takeoverDeadlineMs = 5e3;
9342
+ __privateAdd(this, _takeoverDeadlineMs);
8976
9343
  this.pool = new TransportPool(poolOptions);
8977
9344
  this.pool.onSubscriptionFailed((sub) => {
8978
9345
  for (const trackName of sub.consumers) {
@@ -8981,18 +9348,56 @@ var SessionManager = class {
8981
9348
  }
8982
9349
  });
8983
9350
  }
9351
+ /**
9352
+ * Takeover deadline (BLO-9413/D9): the time a session may sit in `joining`
9353
+ * without a RAP before returning to `unicast` and firing onTakeoverTimeout.
9354
+ * MoQ is never suppressed during `joining`, so expiry abandons the takeover
9355
+ * without a playback glitch. The host derives it from the catalog (RAP
9356
+ * cadence from groupDurationTicks/timescale plus the signaled FEC delivery
9357
+ * window or reorder tolerance) and sets it before addTrack(). There is no
9358
+ * default: an unset value fails addTrack() closed, and reading the getter
9359
+ * before assignment throws the same way, so no host ever holds a
9360
+ * `number | undefined` it could coalesce back into a default.
9361
+ * `hasTakeoverDeadline` answers whether one was admitted. A declared 0
9362
+ * disables the deadline. The value is an integer number of milliseconds:
9363
+ * setTimeout truncates fractions, so a host that divides ticks by a
9364
+ * timescale must round before assigning.
9365
+ *
9366
+ * Assignment validates, so the diagnostic lands at the host's own call site.
9367
+ * That is what bounds the blast radius: `joining` is entered from
9368
+ * joinStarted(), from the transportFailed() failover branch -- itself
9369
+ * reachable from a setTimeout via hysteresisExpired(), where no caller could
9370
+ * catch a throw -- and from the activateMulticast()/activateAmt()/pool-failure
9371
+ * loops, where a throw on one session would abandon its siblings mid-loop
9372
+ * (the split-brain those loops exist to prevent). Refusing a bad value at
9373
+ * assignment means no host mutation can make an already-admitted session
9374
+ * throw out of a transport edge.
9375
+ */
9376
+ get takeoverDeadlineMs() {
9377
+ return __privateMethod(this, _SessionManager_instances, requireTakeoverDeadlineMs_fn).call(this);
9378
+ }
9379
+ set takeoverDeadlineMs(value) {
9380
+ if (!Number.isInteger(value) || value < 0 || value > MAX_TAKEOVER_DEADLINE_MS) {
9381
+ throw new Error(
9382
+ `[SessionManager] takeoverDeadlineMs must be an integer from 0 to ${MAX_TAKEOVER_DEADLINE_MS} (0 disables it, larger values overflow setTimeout); got ${String(value)}`
9383
+ );
9384
+ }
9385
+ __privateSet(this, _takeoverDeadlineMs, value);
9386
+ }
9387
+ /** True once the host has admitted a deadline; a declared 0 counts. */
9388
+ get hasTakeoverDeadline() {
9389
+ return __privateGet(this, _takeoverDeadlineMs) !== void 0;
9390
+ }
8984
9391
  /** Narrow to MMTP callbacks (onTrackEvent). Safe — optional chaining handles PIM-only consumers. */
8985
9392
  get mmtp() {
8986
9393
  return this.callbacks;
8987
9394
  }
8988
- // -----------------------------------------------------------------------
8989
- // Track management
8990
- // -----------------------------------------------------------------------
8991
9395
  /** Add a track session from catalog config. */
8992
9396
  addTrack(config) {
8993
9397
  if (this.sessions.has(config.trackName)) {
8994
9398
  throw new Error(`[SessionManager] Track "${config.trackName}" already exists`);
8995
9399
  }
9400
+ __privateMethod(this, _SessionManager_instances, requireTakeoverDeadlineMs_fn).call(this);
8996
9401
  const session = new TrackSession(config, this);
8997
9402
  this.sessions.set(config.trackName, session);
8998
9403
  return session;
@@ -9016,8 +9421,9 @@ var SessionManager = class {
9016
9421
  * Prevents split-brain between video and audio.
9017
9422
  *
9018
9423
  * A takeover deadline can return a track from `joining` to `unicast` while
9019
- * the multicast socket keeps delivering packets. If a valid RAP arrives
9020
- * later, allow that late-RAP edge to suppress unicast and promote multicast.
9424
+ * the multicast socket keeps delivering packets and the track keeps its FEC
9425
+ * decoder armed. If a valid RAP arrives later, that late-RAP edge suppresses
9426
+ * unicast and promotes multicast without a second fec-setup.
9021
9427
  */
9022
9428
  activateMulticast() {
9023
9429
  for (const [, session] of this.sessions) {
@@ -9049,13 +9455,17 @@ var SessionManager = class {
9049
9455
  * and they must drain uninterrupted across transport-state events.
9050
9456
  *
9051
9457
  * Coherence invariant (BLO-9413): after this returns, every non-fallback
9052
- * session is `unicast` (or `idle`) AND unsuppressed — unsubscribe() unwinds
9053
- * any outstanding suppression regardless of the state it tears down from
9054
- * (`failing` included; see TrackSession.#suppressFired).
9458
+ * session is `unicast` (or `idle`), unsuppressed, and without a FEC decoder.
9459
+ * unsubscribe() unwinds any outstanding suppression regardless of the state
9460
+ * it tears down from (`failing` included; see TrackSession.#suppressFired),
9461
+ * and a session that a takeover timeout parked in `unicast` with its decoder
9462
+ * still armed is cycled too, because this transport edge is what releases
9463
+ * that decoder (unsubscribe fires fec-teardown).
9055
9464
  */
9056
9465
  failbackAll() {
9057
9466
  for (const [, session] of this.sessions) {
9058
- if (session.state !== "idle" && session.state !== "unicast" && session.state !== "unicast-fallback") {
9467
+ const parkedWithFec = session.state === "unicast" && session.isFecArmed;
9468
+ if (parkedWithFec || session.state !== "idle" && session.state !== "unicast" && session.state !== "unicast-fallback") {
9059
9469
  session.unsubscribe();
9060
9470
  session.subscribe();
9061
9471
  }
@@ -9139,6 +9549,27 @@ var SessionManager = class {
9139
9549
  this.callbacks = null;
9140
9550
  }
9141
9551
  };
9552
+ _takeoverDeadlineMs = new WeakMap();
9553
+ _SessionManager_instances = new WeakSet();
9554
+ // -----------------------------------------------------------------------
9555
+ // Track management
9556
+ // -----------------------------------------------------------------------
9557
+ /**
9558
+ * The admitted takeover deadline. Throws only when the host never set one,
9559
+ * every other invalid value being refused by the setter, and returns a
9560
+ * declared 0 as 0. The getter and addTrack() both route through it, so a
9561
+ * session cannot exist without an admitted deadline, which is what makes
9562
+ * the #transition() read unable to throw on an already-admitted session.
9563
+ */
9564
+ requireTakeoverDeadlineMs_fn = function() {
9565
+ const value = __privateGet(this, _takeoverDeadlineMs);
9566
+ if (value === void 0) {
9567
+ throw new Error(
9568
+ "[SessionManager] takeoverDeadlineMs is unset; set a catalog-derived takeover deadline (0 disables it) before adding tracks"
9569
+ );
9570
+ }
9571
+ return value;
9572
+ };
9142
9573
 
9143
9574
  // src/fec-manager.ts
9144
9575
  var MIN_INTERLEAVE_DEPTH_MS = 33;
@@ -12193,7 +12624,7 @@ buildFrameMeta_fn = function(assembled, packetId, seq, timing, recovered = false
12193
12624
  }
12194
12625
  return meta;
12195
12626
  };
12196
- sequencerFor_fn = function(packetId, _trackType, catalogTrackName) {
12627
+ sequencerFor_fn = function(packetId, _trackType2, catalogTrackName) {
12197
12628
  const windowSize = __privateGet(this, _reassemblyPolicy) ? mmtpFrameReorderWindowFrames(__privateGet(this, _reassemblyPolicy), __privateGet(this, _reorderWindow)) : __privateGet(this, _reorderWindow);
12198
12629
  if (windowSize <= 0) return null;
12199
12630
  const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn2).call(this, packetId, catalogTrackName);
@@ -16658,7 +17089,7 @@ _readIndex = new WeakMap();
16658
17089
  _stalled = new WeakMap();
16659
17090
 
16660
17091
  // src/mmtp-decode-pipeline.ts
16661
- var _parser2, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _gateDropped, _gateEmitted, _fedObjects, _warnedNoParser, _feedOutcomes, _MmtpDecodePipeline_instances, gatedEmit_fn;
17092
+ var _parser2, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _trackType, _gateDropped, _gateEmitted, _fedObjects, _warnedNoParser, _feedOutcomes, _MmtpDecodePipeline_instances, tag_fn, gatedEmit_fn;
16662
17093
  var MmtpDecodePipeline = class {
16663
17094
  constructor() {
16664
17095
  __privateAdd(this, _MmtpDecodePipeline_instances);
@@ -16667,7 +17098,11 @@ var MmtpDecodePipeline = class {
16667
17098
  __privateAdd(this, _frameCb2, null);
16668
17099
  __privateAdd(this, _initCb2, null);
16669
17100
  __privateAdd(this, _needsKeyframe, false);
16670
- __privateAdd(this, _codec, "");
17101
+ __privateAdd(this, _codec, null);
17102
+ /** Set together with #codec at configure(). Also the diagnostic label: a
17103
+ * player builds one pipeline per track, and codec alone does not say which
17104
+ * role a line belongs to at a glance. */
17105
+ __privateAdd(this, _trackType, null);
16671
17106
  /** Diagnostic counters. The keyframe gate drops silently, so a parser that
16672
17107
  * never marks a frame as a keyframe stalls the whole pipeline with no
16673
17108
  * output anywhere: frames are fed, frames are parsed, and nothing is
@@ -16696,6 +17131,7 @@ var MmtpDecodePipeline = class {
16696
17131
  __privateSet(this, _warnedNoParser, false);
16697
17132
  __privateSet(this, _codec, config.codec);
16698
17133
  const trackType = isVideoCodec(config.codec) ? "video" : "audio";
17134
+ __privateSet(this, _trackType, trackType);
16699
17135
  const trackInfo = {
16700
17136
  type: trackType,
16701
17137
  codec: config.codec,
@@ -16739,6 +17175,24 @@ var MmtpDecodePipeline = class {
16739
17175
  get reorderStats() {
16740
17176
  return __privateGet(this, _parser2)?.reorderStats ?? null;
16741
17177
  }
17178
+ /**
17179
+ * Feed tallies for this track. A fresh snapshot per call, not a live view.
17180
+ *
17181
+ * Unlike reorderStats this never returns null: the counters belong to the
17182
+ * pipeline rather than the parser, so they survive dispose(). That is
17183
+ * deliberate — a wedged pipeline is usually read after teardown, which is
17184
+ * exactly when the parser is already gone.
17185
+ */
17186
+ get feedStats() {
17187
+ return {
17188
+ trackType: __privateGet(this, _trackType),
17189
+ codec: __privateGet(this, _codec),
17190
+ fedObjects: __privateGet(this, _fedObjects),
17191
+ emitted: __privateGet(this, _gateEmitted),
17192
+ gateDropped: __privateGet(this, _gateDropped),
17193
+ outcomes: Object.fromEntries(__privateGet(this, _feedOutcomes))
17194
+ };
17195
+ }
16742
17196
  /**
16743
17197
  * Feed a raw MoQ object payload (one MMTP packet per MoQ object).
16744
17198
  * Optionally feeds source symbols to FEC client before parsing.
@@ -16747,33 +17201,37 @@ var MmtpDecodePipeline = class {
16747
17201
  if (!__privateGet(this, _parser2)) {
16748
17202
  if (!__privateGet(this, _warnedNoParser)) {
16749
17203
  __privateSet(this, _warnedNoParser, true);
16750
- console.warn("[mmtp-pipeline] feedMoqObject called with NO PARSER configured \u2014 packet dropped");
17204
+ console.warn(`[mmtp-pipeline] feedMoqObject called with NO PARSER configured ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} \u2014 packet dropped`);
16751
17205
  }
16752
17206
  return;
16753
17207
  }
16754
17208
  __privateSet(this, _fedObjects, __privateGet(this, _fedObjects) + 1);
16755
17209
  if (__privateGet(this, _fedObjects) === 1) {
16756
- console.log(`[mmtp-pipeline] first object fed codec=${__privateGet(this, _codec)} bytes=${packet.length}`);
17210
+ console.log(`[mmtp-pipeline] first object fed ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${packet.length}`);
16757
17211
  }
16758
- if (__privateGet(this, _fecClient)?.addSourceSymbol) {
16759
- const info = __privateGet(this, _parser2).parseHeader(packet);
16760
- if (info?.fecPayloadId) {
16761
- __privateGet(this, _fecClient).addSourceSymbol(info.fecPayloadId.ssId, packet);
17212
+ let outcomeKind = "threw";
17213
+ try {
17214
+ if (__privateGet(this, _fecClient)?.addSourceSymbol) {
17215
+ const info = __privateGet(this, _parser2).parseHeader(packet);
17216
+ if (info?.fecPayloadId) {
17217
+ __privateGet(this, _fecClient).addSourceSymbol(info.fecPayloadId.ssId, packet);
17218
+ }
17219
+ }
17220
+ const record = __privateGet(this, _parser2).feed(packet);
17221
+ outcomeKind = record?.kind ?? "null(parse-or-extract-failed)";
17222
+ } finally {
17223
+ const seen = (__privateGet(this, _feedOutcomes).get(outcomeKind) ?? 0) + 1;
17224
+ __privateGet(this, _feedOutcomes).set(outcomeKind, seen);
17225
+ if (seen === 1) {
17226
+ console.log(
17227
+ `[mmtp-pipeline] feed outcome FIRST '${outcomeKind}' ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} at object #${__privateGet(this, _fedObjects)} bytes=${packet.length}`
17228
+ );
16762
17229
  }
16763
- }
16764
- const record = __privateGet(this, _parser2).feed(packet);
16765
- const kind = record?.kind ?? "null(parse-or-extract-failed)";
16766
- const seen = (__privateGet(this, _feedOutcomes).get(kind) ?? 0) + 1;
16767
- __privateGet(this, _feedOutcomes).set(kind, seen);
16768
- if (seen === 1) {
16769
- console.log(
16770
- `[mmtp-pipeline] feed outcome FIRST '${kind}' at object #${__privateGet(this, _fedObjects)} bytes=${packet.length}`
16771
- );
16772
17230
  }
16773
17231
  if (__privateGet(this, _fedObjects) % 200 === 0) {
16774
17232
  const hist = [...__privateGet(this, _feedOutcomes)].map(([k, v]) => `${k}=${v}`).join(" ");
16775
17233
  console.log(
16776
- `[mmtp-pipeline] feed histogram @${__privateGet(this, _fedObjects)}: ${hist} | emitted=${__privateGet(this, _gateEmitted)} gateDropped=${__privateGet(this, _gateDropped)}`
17234
+ `[mmtp-pipeline] feed histogram ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} @${__privateGet(this, _fedObjects)}: ${hist} | emitted=${__privateGet(this, _gateEmitted)} gateDropped=${__privateGet(this, _gateDropped)}`
16777
17235
  );
16778
17236
  }
16779
17237
  }
@@ -16793,7 +17251,10 @@ var MmtpDecodePipeline = class {
16793
17251
  ...meta.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: meta.mmtpTimestamp },
16794
17252
  keyframe: meta.keyframe,
16795
17253
  packetId: meta.packetId,
16796
- trackType: isVideoCodec(__privateGet(this, _codec)) ? "video" : "audio",
17254
+ // Same derivation as configure(), read from the field it set rather than
17255
+ // recomputed. Pre-configure the parser is null and routeFrame below is a
17256
+ // no-op, so the fallback is unreachable in practice.
17257
+ trackType: __privateGet(this, _trackType) ?? "audio",
16797
17258
  packetSequenceNumber: meta.packetSequenceNumber
16798
17259
  };
16799
17260
  if (meta.sourceDiscontinuity) frameMeta.sourceDiscontinuity = true;
@@ -16819,7 +17280,7 @@ var MmtpDecodePipeline = class {
16819
17280
  const droppedFrames = (__privateGet(this, _parser2)?.reorderStats.droppedOnLiveDispose ?? droppedBefore) - droppedBefore;
16820
17281
  if (droppedFrames > 0) {
16821
17282
  console.warn(
16822
- `[MmtpDecodePipeline] live dispose dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
17283
+ `[MmtpDecodePipeline] live dispose ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
16823
17284
  );
16824
17285
  }
16825
17286
  __privateSet(this, _parser2, null);
@@ -16834,12 +17295,19 @@ _frameCb2 = new WeakMap();
16834
17295
  _initCb2 = new WeakMap();
16835
17296
  _needsKeyframe = new WeakMap();
16836
17297
  _codec = new WeakMap();
17298
+ _trackType = new WeakMap();
16837
17299
  _gateDropped = new WeakMap();
16838
17300
  _gateEmitted = new WeakMap();
16839
17301
  _fedObjects = new WeakMap();
16840
17302
  _warnedNoParser = new WeakMap();
16841
17303
  _feedOutcomes = new WeakMap();
16842
17304
  _MmtpDecodePipeline_instances = new WeakSet();
17305
+ /** Identity prefix for diagnostics: one pipeline per track means two
17306
+ * instances write to the same console, and unlabelled lines interleave into
17307
+ * a single unreadable stream. */
17308
+ tag_fn = function() {
17309
+ return `track=${__privateGet(this, _trackType) ?? "unconfigured"} codec=${__privateGet(this, _codec) ?? "none"}`;
17310
+ };
16843
17311
  gatedEmit_fn = function(data, meta) {
16844
17312
  var _a;
16845
17313
  let sourceDiscontinuity = false;
@@ -16848,7 +17316,7 @@ gatedEmit_fn = function(data, meta) {
16848
17316
  __privateSet(this, _gateDropped, __privateGet(this, _gateDropped) + 1);
16849
17317
  if (__privateGet(this, _gateDropped) <= 3 || __privateGet(this, _gateDropped) % 200 === 0) {
16850
17318
  console.warn(
16851
- `[mmtp-pipeline] keyframe gate DROP #${__privateGet(this, _gateDropped)} codec=${__privateGet(this, _codec)} bytes=${data.length} fed=${__privateGet(this, _fedObjects)} emitted=${__privateGet(this, _gateEmitted)}`
17319
+ `[mmtp-pipeline] keyframe gate DROP #${__privateGet(this, _gateDropped)} ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length} fed=${__privateGet(this, _fedObjects)} emitted=${__privateGet(this, _gateEmitted)}`
16852
17320
  );
16853
17321
  }
16854
17322
  return;
@@ -16856,12 +17324,12 @@ gatedEmit_fn = function(data, meta) {
16856
17324
  __privateSet(this, _needsKeyframe, false);
16857
17325
  sourceDiscontinuity = true;
16858
17326
  console.log(
16859
- `[mmtp-pipeline] keyframe gate OPENED codec=${__privateGet(this, _codec)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects)}`
17327
+ `[mmtp-pipeline] keyframe gate OPENED ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects)}`
16860
17328
  );
16861
17329
  }
16862
17330
  __privateSet(this, _gateEmitted, __privateGet(this, _gateEmitted) + 1);
16863
17331
  if (__privateGet(this, _gateEmitted) === 1) {
16864
- console.log(`[mmtp-pipeline] first frame emitted codec=${__privateGet(this, _codec)} bytes=${data.length}`);
17332
+ console.log(`[mmtp-pipeline] first frame emitted ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length}`);
16865
17333
  }
16866
17334
  const outMeta = sourceDiscontinuity ? { ...meta, sourceDiscontinuity: true } : meta;
16867
17335
  (_a = __privateGet(this, _frameCb2)) == null ? void 0 : _a.call(this, data, outMeta);
@@ -17535,6 +18003,7 @@ emit_fn = function(params) {
17535
18003
  };
17536
18004
 
17537
18005
  // src/catalog-fec-params.ts
18006
+ var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
17538
18007
  function timescaleHz(value) {
17539
18008
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
17540
18009
  }
@@ -17543,7 +18012,7 @@ function catalogGroupDurationMs(rendition) {
17543
18012
  const ticks = numericField(rendition.groupDurationTicks);
17544
18013
  const ms = numericField(rendition.groupDurationMs);
17545
18014
  const timescale = timescaleHz(rendition.container?.kind === "mmtp" ? rendition.container.timescale : void 0) ?? timescaleHz(rendition.timescale);
17546
- if (ticks !== void 0 && Number.isSafeInteger(ticks) && timescale !== void 0) {
18015
+ if (ticks !== void 0 && timescale !== void 0 && Number.isSafeInteger(ticks) && ticks <= timescale * MAX_SAFE_TICKS_PER_HZ) {
17547
18016
  return resolveGroupDurationMs({ groupDurationTicks: ticks }, timescale);
17548
18017
  }
17549
18018
  return ms;
@@ -17555,9 +18024,119 @@ function resolveCatalogTrackGroupDurationMs(catalog, track) {
17555
18024
  var NO_FEC = {
17556
18025
  fecK: 0,
17557
18026
  fecRepairCount: 0,
18027
+ fecTotalRepairCount: 0,
17558
18028
  fecSymbolSize: 0,
17559
18029
  fecInterleaveMs: 0
17560
18030
  };
18031
+ function recordOf(value) {
18032
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
18033
+ }
18034
+ function msfTracks(catalog) {
18035
+ const raw = catalog.tracks;
18036
+ if (!Array.isArray(raw)) return void 0;
18037
+ const common = recordOf(catalog.commonTrackFields) ?? {};
18038
+ return { tracks: raw.map((t) => recordOf(t) ?? {}), common };
18039
+ }
18040
+ function resolveRepairLayers(catalog, source) {
18041
+ if (!catalog) return void 0;
18042
+ const sourceName = typeof source === "string" ? source : source.name;
18043
+ const hang = catalog;
18044
+ const roles = typeof source === "string" ? ["video", "audio"] : source.type === "audio" ? ["audio"] : source.type === "video" ? ["video"] : ["video", "audio"];
18045
+ const role = roles.find((r) => recordOf(hang[r]?.renditions?.[sourceName]) !== void 0);
18046
+ if (role !== void 0) {
18047
+ const renditionPath = `$.${role}.renditions[${JSON.stringify(sourceName)}]`;
18048
+ const rendition = recordOf(hang[role].renditions[sourceName]);
18049
+ rejectRepairFieldsOnMediaTrack(renditionPath, rendition, throwRepairContractError);
18050
+ const repairRenditions = recordOf(hang.repair?.renditions) ?? {};
18051
+ const descriptors2 = Object.entries(repairRenditions).map(([name, entry]) => {
18052
+ const path = `$.repair.renditions[${JSON.stringify(name)}]`;
18053
+ const fields = recordOf(entry);
18054
+ if (fields === void 0) {
18055
+ throwRepairContractError("track_repair_layer", path, "a repair rendition must be an object");
18056
+ }
18057
+ rejectRepairTrackGeometry(path, fields, throwRepairContractError);
18058
+ return describeRepairTrack(name, path, fields);
18059
+ });
18060
+ const fecOfRendition = (entry) => {
18061
+ const fec2 = recordOf(recordOf(entry)?.["fec"]);
18062
+ return fec2 !== void 0 && fec2["algorithm"] !== "none" ? fec2 : void 0;
18063
+ };
18064
+ const mediaRenditions = [
18065
+ ...Object.values(recordOf(hang.video?.renditions) ?? {}),
18066
+ ...Object.values(recordOf(hang.audio?.renditions) ?? {})
18067
+ ];
18068
+ const reachability2 = repairReachability(mediaRenditions.map((entry) => recordOf(entry)?.["fec"]));
18069
+ for (const d of descriptors2) {
18070
+ validateRepairTrackFields(d, throwRepairContractError);
18071
+ assertRepairTrackReachable(d, reachability2, throwRepairContractError);
18072
+ const target = dependsTarget(d);
18073
+ if (target === void 0) continue;
18074
+ const targetFec = fecOfRendition(hang.video?.renditions?.[target]) ?? fecOfRendition(hang.audio?.renditions?.[target]);
18075
+ if (targetFec === void 0) {
18076
+ throwRepairContractError(
18077
+ "track_repair_depends",
18078
+ `${d.path}.depends`,
18079
+ `${JSON.stringify(target)} is not a video or audio rendition with FEC`
18080
+ );
18081
+ }
18082
+ }
18083
+ return assembleRepairLayers(
18084
+ geometryOf(sourceName, `${renditionPath}.fec`, recordOf(rendition["fec"])),
18085
+ descriptors2,
18086
+ throwRepairContractError
18087
+ );
18088
+ }
18089
+ const msf = msfTracks(catalog);
18090
+ const msfIndex = msf ? msf.tracks.findIndex((t) => t["name"] === sourceName) : -1;
18091
+ if (!msf || msfIndex < 0) return void 0;
18092
+ const track = msf.tracks[msfIndex];
18093
+ const fec = recordOf(track["fec"]);
18094
+ const packagingOf = (t) => t["packaging"] ?? msf.common["packaging"];
18095
+ const fecOfTrack = (t) => {
18096
+ const trackFec = recordOf(t?.["fec"]);
18097
+ return trackFec !== void 0 && trackFec["algorithm"] !== "none" ? trackFec : void 0;
18098
+ };
18099
+ const descriptors = [];
18100
+ const mediaTracks = [];
18101
+ msf.tracks.forEach((t, i) => {
18102
+ const path = `$.tracks[${i}]`;
18103
+ if (packagingOf(t) === "fec-repair") {
18104
+ rejectRepairTrackGeometry(path, t, throwRepairContractError);
18105
+ if (typeof t["name"] === "string") descriptors.push(describeRepairTrack(t["name"], path, t));
18106
+ return;
18107
+ }
18108
+ rejectRepairFieldsOnMediaTrack(path, t, throwRepairContractError);
18109
+ mediaTracks.push(t);
18110
+ });
18111
+ const reachability = repairReachability(mediaTracks.map((t) => t["fec"]));
18112
+ for (const d of descriptors) {
18113
+ validateRepairTrackFields(d, throwRepairContractError);
18114
+ assertRepairTrackReachable(d, reachability, throwRepairContractError);
18115
+ const target = dependsTarget(d);
18116
+ if (target === void 0) continue;
18117
+ const targetTrack = msf.tracks.find((t) => t["name"] === target);
18118
+ if (targetTrack === void 0 || packagingOf(targetTrack) !== "mmtp" || fecOfTrack(targetTrack) === void 0) {
18119
+ throwRepairContractError(
18120
+ "track_repair_depends",
18121
+ `${d.path}.depends`,
18122
+ `${JSON.stringify(target)} is not an mmtp track with FEC`
18123
+ );
18124
+ }
18125
+ }
18126
+ return assembleRepairLayers(geometryOf(sourceName, `$.tracks[${msfIndex}].fec`, fec), descriptors, throwRepairContractError, {
18127
+ layerZeroMustBeDeclared: true
18128
+ });
18129
+ }
18130
+ function geometryOf(name, path, fec) {
18131
+ return {
18132
+ name,
18133
+ path,
18134
+ algorithm: fec?.["algorithm"],
18135
+ sourceSymbols: fec?.["sourceSymbols"],
18136
+ repairSymbols: fec?.["repairSymbols"],
18137
+ repairTrack: fec?.["repairTrack"]
18138
+ };
18139
+ }
17561
18140
  function numericField(value) {
17562
18141
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
17563
18142
  return Number.isFinite(n) && n > 0 ? n : void 0;
@@ -17566,13 +18145,16 @@ function nonNegativeField(value) {
17566
18145
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
17567
18146
  return Number.isFinite(n) && n >= 0 ? n : void 0;
17568
18147
  }
17569
- function fecParams(rendition, fps, sampleRate) {
18148
+ function fecParams(catalog, track, rendition, fps, sampleRate) {
17570
18149
  const mediaRate = sampleRate === void 0 ? { fps } : { fps, sampleRate };
17571
18150
  const fec = rendition?.fec;
17572
18151
  if (!fec) return { ...NO_FEC, ...mediaRate };
18152
+ const repair = track ? resolveRepairLayers(catalog, track) : void 0;
17573
18153
  return {
17574
18154
  fecK: fec.sourceSymbols ?? 0,
17575
18155
  fecRepairCount: fec.repairSymbols ?? 0,
18156
+ // The wire RSB_length: every base layer's packets carry the base total (§7.1).
18157
+ fecTotalRepairCount: repair?.totalBaseRepairSymbols ?? fec.repairSymbols ?? 0,
17576
18158
  fecSymbolSize: fec.symbolSize ?? 0,
17577
18159
  // interleaveDepthMs is the FEC block span in MILLISECONDS (§5.1) — the
17578
18160
  // only interleave key the catalog carries post-BLO-14526. Receivers
@@ -17584,6 +18166,8 @@ function fecParams(rendition, fps, sampleRate) {
17584
18166
  // so it cannot be reused here — a declared 0 is a legitimate value.
17585
18167
  fecReorderToleranceMs: nonNegativeField(fec.reorderToleranceMs),
17586
18168
  repairTrackName: fec.repairTrack,
18169
+ repairLayers: repair?.baseLayers,
18170
+ repairOverlays: repair?.overlays,
17587
18171
  ...mediaRate
17588
18172
  };
17589
18173
  }
@@ -17597,8 +18181,14 @@ function resolveCatalogTrackFec(catalog, tracks) {
17597
18181
  const catalogFps = numericField(video?.framerate);
17598
18182
  const sampleRate = numericField(audio?.sampleRate ?? audio?.samplerate);
17599
18183
  const audioFps = sampleRate ? sampleRate / 1024 : void 0;
17600
- const videoParams = fecParams(video, catalogFps);
17601
- const audioParams = fecParams(audio, audioFps, sampleRate);
18184
+ const videoParams = fecParams(catalog, videoTrackName ? { name: videoTrackName, type: "video" } : void 0, video, catalogFps);
18185
+ const audioParams = fecParams(
18186
+ catalog,
18187
+ audioTrackName ? { name: audioTrackName, type: "audio" } : void 0,
18188
+ audio,
18189
+ audioFps,
18190
+ sampleRate
18191
+ );
17602
18192
  return {
17603
18193
  videoTrackName,
17604
18194
  audioTrackName,
@@ -17761,6 +18351,7 @@ export {
17761
18351
  CmafGroupBatcher,
17762
18352
  CmcdProducer,
17763
18353
  CmsfCatalogValidationError,
18354
+ DEFAULT_REPAIR_PRIORITY,
17764
18355
  FECManager,
17765
18356
  FEC_ESI_MAX,
17766
18357
  FEC_SBN_MAX,
@@ -17768,6 +18359,10 @@ export {
17768
18359
  FecStarvationDetector,
17769
18360
  KEYFRAME_LOST_TIMEOUT_SLACK,
17770
18361
  LOCHeaderExtensionId,
18362
+ MAX_ENCODING_SYMBOL_ID,
18363
+ MAX_RAPTORQ_SOURCE_SYMBOLS,
18364
+ MAX_REPAIR_SYMBOLS,
18365
+ MAX_TAKEOVER_DEADLINE_MS,
17771
18366
  MFUReassembler,
17772
18367
  MediaRouter,
17773
18368
  MfuReassemblyError,
@@ -17782,7 +18377,12 @@ export {
17782
18377
  NoneCodec,
17783
18378
  REPAIR_LIFECYCLE_EVENT_TYPE,
17784
18379
  REPAIR_LIFECYCLE_LOG_PREFIX,
18380
+ REPAIR_PRIORITY_MAX,
18381
+ REPAIR_PRIORITY_MIN,
18382
+ REPAIR_TRACK_GEOMETRY_KEYS,
18383
+ REPAIR_TRACK_ONLY_KEYS,
17785
18384
  ReedSolomonCodec,
18385
+ RepairContractError,
17786
18386
  SampleCombineError,
17787
18387
  SampleCombiner,
17788
18388
  SessionManager,
@@ -17793,6 +18393,8 @@ export {
17793
18393
  WasmMfuReassembler,
17794
18394
  annexBToAvcc,
17795
18395
  asSeconds,
18396
+ assembleRepairLayers,
18397
+ assertRepairTrackReachable,
17796
18398
  avccToAnnexB,
17797
18399
  buildAudioInitSegment,
17798
18400
  buildVideoInitSegment,
@@ -17813,6 +18415,8 @@ export {
17813
18415
  decodeLocHeader,
17814
18416
  decodeLocTimestamp,
17815
18417
  decodeTimestamp,
18418
+ dependsTarget,
18419
+ describeRepairTrack,
17816
18420
  detectH264Keyframe,
17817
18421
  driftCheck,
17818
18422
  encodeDataSegment,
@@ -17866,13 +18470,17 @@ export {
17866
18470
  parseAacSampleRate,
17867
18471
  parseOpusFrameSamples,
17868
18472
  processMMTPWithReassembly,
18473
+ rejectRepairFieldsOnMediaTrack,
18474
+ rejectRepairTrackGeometry,
17869
18475
  reliableMoqMfuReassembly,
17870
18476
  removeEmulationPrevention,
18477
+ repairReachability,
17871
18478
  resolveCatalogTrackFec,
17872
18479
  resolveCatalogTrackGroupDurationMs,
17873
18480
  resolveGlobalMmtWasmBindings,
17874
18481
  resolveGroupDurationMs,
17875
18482
  resolveGroupDurationTicks,
18483
+ resolveRepairLayers,
17876
18484
  secondsFromTicks,
17877
18485
  setupFecWorkerForTrack,
17878
18486
  setupTrackPipeline,
@@ -17882,6 +18490,7 @@ export {
17882
18490
  unwrapMulticastPacket,
17883
18491
  validateCmsfMmtpCatalog,
17884
18492
  validateMulticastContainerContract,
18493
+ validateRepairTrackFields,
17885
18494
  validateSwitchingSetTiming,
17886
18495
  wireRepairFetch,
17887
18496
  wrapAdtsFrame