@blockcast/mmt-container 0.1.0-main.7633a101ae0c → 0.1.0-main.779dee7c6ab7

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 (82) hide show
  1. package/dist/browser-runtime.js +2166 -229
  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 +105 -0
  8. package/dist/catalog-fec-params.d.ts.map +1 -1
  9. package/dist/catalog-fec-params.js +495 -4
  10. package/dist/catalog-fec-params.js.map +4 -4
  11. package/dist/cmaf-block-assembler.d.ts +8 -0
  12. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  13. package/dist/cmaf-block-assembler.js +11 -8
  14. package/dist/cmaf-block-assembler.js.map +2 -2
  15. package/dist/cmaf-group-batcher.js.map +1 -1
  16. package/dist/fec-manager.js.map +2 -2
  17. package/dist/fec-worker-setup.js.map +2 -2
  18. package/dist/index.d.ts +3 -3
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +43 -1
  21. package/dist/index.js.map +2 -2
  22. package/dist/media-router.js.map +2 -2
  23. package/dist/mfu-reassembler.d.ts +49 -10
  24. package/dist/mfu-reassembler.d.ts.map +1 -1
  25. package/dist/mfu-reassembler.js +48 -27
  26. package/dist/mfu-reassembler.js.map +2 -2
  27. package/dist/mmtp-container-parser.js +48 -27
  28. package/dist/mmtp-container-parser.js.map +2 -2
  29. package/dist/mmtp-container-parser.no-modules.js +386 -40
  30. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  31. package/dist/mmtp-decode-pipeline.d.ts +34 -0
  32. package/dist/mmtp-decode-pipeline.d.ts.map +1 -1
  33. package/dist/mmtp-decode-pipeline.js +109 -51
  34. package/dist/mmtp-decode-pipeline.js.map +3 -3
  35. package/dist/mmtp-router.js +59 -35
  36. package/dist/mmtp-router.js.map +2 -2
  37. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  38. package/dist/mmtp-to-cmaf.js +2 -1
  39. package/dist/mmtp-to-cmaf.js.map +2 -2
  40. package/dist/multicast-manager.js +1394 -58
  41. package/dist/multicast-manager.js.map +4 -4
  42. package/dist/multicast-transport.d.ts +1 -2
  43. package/dist/multicast-transport.d.ts.map +1 -1
  44. package/dist/multicast-transport.js +1335 -23
  45. package/dist/multicast-transport.js.map +4 -4
  46. package/dist/no-modules.js +386 -40
  47. package/dist/no-modules.js.map +4 -4
  48. package/dist/repair-layers.d.ts +141 -0
  49. package/dist/repair-layers.d.ts.map +1 -0
  50. package/dist/repair-layers.js +303 -0
  51. package/dist/repair-layers.js.map +7 -0
  52. package/dist/track-session.d.ts +57 -13
  53. package/dist/track-session.d.ts.map +1 -1
  54. package/dist/track-session.js +128 -45
  55. package/dist/track-session.js.map +2 -2
  56. package/dist/wasm-mfu-reassembler.js.map +2 -2
  57. package/dist/wasm-mmtp-container-parser.js +48 -27
  58. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  59. package/package.json +6 -6
  60. package/schemas/catalog.schema.json +82 -5
  61. package/src/carp-catalog.ts +78 -6
  62. package/src/catalog-fec-params.ts +342 -2
  63. package/src/cmaf-block-assembler.ts +17 -0
  64. package/src/index.ts +34 -0
  65. package/src/mfu-reassembler.ts +120 -37
  66. package/src/mmtp-decode-pipeline.ts +93 -24
  67. package/src/mmtp-to-cmaf.ts +25 -1
  68. package/src/multicast-transport.ts +13 -27
  69. package/src/repair-layers.ts +490 -0
  70. package/src/track-session.ts +181 -57
  71. package/test-vectors/catalog/README.md +16 -1
  72. package/test-vectors/catalog/negative/fec-enhancement-repair-removed.json +27 -0
  73. package/test-vectors/catalog/negative/fec-repair-layer-geometry.json +32 -0
  74. package/test-vectors/catalog/negative/fec-repair-layer-missing-symbols.json +30 -0
  75. package/test-vectors/catalog/negative/fec-repair-multiple-depends.json +31 -0
  76. package/test-vectors/catalog/negative/fec-repair-overlay-with-layer.json +33 -0
  77. package/test-vectors/catalog/negative/fec-repair-priority-out-of-band.json +23 -0
  78. package/test-vectors/catalog/negative/fec-repair-source-symbols-without-scope.json +32 -0
  79. package/test-vectors/catalog/negative/media-track-repair-layer.json +16 -0
  80. package/test-vectors/catalog/negative/raptorq-source-symbols-over-max.json +23 -0
  81. package/test-vectors/catalog/negative/repair-track-legacy-shape.json +2 -1
  82. 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);
@@ -1098,12 +1098,9 @@ var MFUReassembler = class {
1098
1098
  state.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onTimeout_fn).call(this, bufferKey), Math.max(0, state.startedAt + ms - now));
1099
1099
  }
1100
1100
  }
1101
- for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1102
- if (pending.timeoutId !== void 0) clearTimeout(pending.timeoutId);
1103
- delete pending.timeoutId;
1104
- if (ms !== null && __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) === void 0) {
1105
- pending.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address), Math.max(0, pending.startedAt + ms - now));
1106
- }
1101
+ for (const address of __privateGet(this, _pendingContinuations).keys()) {
1102
+ __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1103
+ __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
1107
1104
  }
1108
1105
  }
1109
1106
  get timeoutMs() {
@@ -1271,7 +1268,8 @@ var MFUReassembler = class {
1271
1268
  * unit that holds a slot.
1272
1269
  *
1273
1270
  * 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
1271
+ * so it takes the same rule — by delegating to `#unopenedParkedRunCount`, the
1272
+ * one site that applies it. Rust's public `buffered_count()` is
1275
1273
  * `inner.buffered_count() + unopened_parked_run_count()`, and that count is
1276
1274
  * `parked_run_holds_a_slot` — so filtering here on the open run alone would
1277
1275
  * report a phantom slot for an empty published queue in TypeScript and not in
@@ -1281,16 +1279,11 @@ var MFUReassembler = class {
1281
1279
  *
1282
1280
  * Distinct from `#incompleteRunCount`, which sums `#activeDataUnits` rather
1283
1281
  * than `#buffers`. Those are different quantities by design and are not being
1284
- * merged; only the parked term they share is required to agree.
1282
+ * merged; only the parked term they share is required to agree, which is what
1283
+ * routing both through one method makes structural rather than conventional.
1285
1284
  */
1286
1285
  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;
1286
+ return __privateGet(this, _buffers).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
1294
1287
  }
1295
1288
  /**
1296
1289
  * Get current buffer status
@@ -1358,26 +1351,26 @@ parkContinuation_fn = function(address, fragment) {
1358
1351
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
1359
1352
  }
1360
1353
  }
1354
+ let armAfterInsert = false;
1361
1355
  if (pending === void 0) {
1362
1356
  pending = {
1363
1357
  fragments: /* @__PURE__ */ new Map(),
1364
1358
  startedAt: Date.now(),
1365
1359
  admissionSeq: open !== void 0 ? open[1].admissionSeq : __privateWrapper(this, _nextAdmissionSeq)._++
1366
1360
  };
1367
- if (open === void 0 && __privateGet(this, _timeoutMs) !== null) {
1368
- pending.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address), __privateGet(this, _timeoutMs));
1369
- }
1370
1361
  __privateGet(this, _pendingContinuations).set(address, pending);
1362
+ armAfterInsert = true;
1371
1363
  } else if (!alreadyCharged) {
1372
1364
  pending.admissionSeq = __privateWrapper(this, _nextAdmissionSeq)._++;
1373
1365
  pending.startedAt = Date.now();
1374
1366
  __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1375
- __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
1367
+ armAfterInsert = true;
1376
1368
  }
1377
1369
  if (pending.fragments.has(fragment.fragmentCounter)) {
1378
1370
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "duplicate queued continuation counter would replace retained media");
1379
1371
  }
1380
1372
  pending.fragments.set(fragment.fragmentCounter, fragment);
1373
+ if (armAfterInsert) __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
1381
1374
  };
1382
1375
  drainPendingContinuations_fn = function(address, runKey) {
1383
1376
  while (true) {
@@ -1400,12 +1393,20 @@ drainPendingContinuations_fn = function(address, runKey) {
1400
1393
  }
1401
1394
  }
1402
1395
  };
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;
1396
+ /** Parked data units that hold a `maxBuffered` slot of their own. Membership
1397
+ * is `parkedRunHoldsASlot`, the same rule #evictLeastRecentlyAdmitted offers
1398
+ * as candidates, so nothing can be counted here that eviction cannot reclaim.
1399
+ *
1400
+ * One site, two callers — `#incompleteRunCount` and `pendingCount` — mirroring
1401
+ * Rust's `unopened_parked_run_count`, which `incomplete_run_count` and
1402
+ * `buffered_count` both delegate to. Both callers used to inline this loop
1403
+ * verbatim, so converging the *rule* moved one copy and left the other as the
1404
+ * divergence (Ally's review of #400). The rule can no longer drift now that
1405
+ * every site routes through `parkedRunHoldsASlot`; keeping the loop itself at
1406
+ * one site is what stops the scaffolding drifting the next time this question
1407
+ * grows an argument. */
1408
+ unopenedParkedRunCount_fn = function() {
1409
+ let count = 0;
1409
1410
  for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1410
1411
  if (parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1411
1412
  count++;
@@ -1413,6 +1414,14 @@ incompleteRunCount_fn = function() {
1413
1414
  }
1414
1415
  return count;
1415
1416
  };
1417
+ /** Every open run plus every headless parked data unit that holds a slot,
1418
+ * one slot each. This is the quantity maxBuffered bounds. The parked term is
1419
+ * `#unopenedParkedRunCount`, whose membership is `parkedRunHoldsASlot` — the
1420
+ * same rule #evictLeastRecentlyAdmitted offers as candidates, so nothing can
1421
+ * be counted here that eviction cannot reclaim. */
1422
+ incompleteRunCount_fn = function() {
1423
+ return __privateGet(this, _activeDataUnits).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
1424
+ };
1416
1425
  /**
1417
1426
  * Drop the incomplete data unit admitted longest ago so a newly arriving one
1418
1427
  * can take its slot. Selection is by monotonic admission ordinal, never by
@@ -1652,11 +1661,19 @@ clearPendingTimeout_fn = function(address) {
1652
1661
  /**
1653
1662
  * A queue whose run closed without completing is headless again and expires
1654
1663
  * from its own first arrival, exactly as it would had the head never come.
1664
+ *
1665
+ * An empty queue is not armed: it holds no data unit that could fail to
1666
+ * complete, so there is nothing for a deadline to expire. Every arming site
1667
+ * reaches this function, which takes that test through `parkedRunHoldsASlot`
1668
+ * rather than filtering on the open run alone, which is how this engine
1669
+ * reaches Rust's answer: its
1670
+ * `next_timeout_at` derives candidate deadlines from the queue's live
1671
+ * entries, so an empty queue yields none (BLO-32420).
1655
1672
  */
1656
1673
  armHeadlessPendingTimeout_fn = function(address) {
1657
1674
  const pending = __privateGet(this, _pendingContinuations).get(address);
1658
1675
  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;
1676
+ if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) return;
1660
1677
  pending.timeoutId = setTimeout(
1661
1678
  () => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address),
1662
1679
  Math.max(0, pending.startedAt + __privateGet(this, _timeoutMs) - Date.now())
@@ -1669,6 +1686,10 @@ deletePendingRun_fn = function(address) {
1669
1686
  onPendingTimeout_fn = function(address) {
1670
1687
  const pending = __privateGet(this, _pendingContinuations).get(address);
1671
1688
  if (pending === void 0) return;
1689
+ if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1690
+ __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1691
+ return;
1692
+ }
1672
1693
  this.stats.timedOutMFUs++;
1673
1694
  console.warn(
1674
1695
  `[MfuReassembler] timeout: run=${address} fragments=${pending.fragments.size} (continuations awaiting first fragment, discarded)`
@@ -5782,6 +5803,289 @@ function resolveMulticastAuthCatalog(catalog, playerMode) {
5782
5803
  };
5783
5804
  }
5784
5805
 
5806
+ // src/repair-layers.ts
5807
+ var REPAIR_PRIORITY_MIN = 192;
5808
+ var REPAIR_PRIORITY_MAX = 255;
5809
+ var DEFAULT_REPAIR_PRIORITY = 240;
5810
+ var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
5811
+ var MAX_REPAIR_SYMBOLS = 16777215;
5812
+ var MAX_ENCODING_SYMBOL_ID = 16777215;
5813
+ var RepairContractError = class extends Error {
5814
+ constructor(code, path, message) {
5815
+ super(`[repair-layers:${code}] ${path}: ${message}`);
5816
+ this.code = code;
5817
+ this.path = path;
5818
+ this.name = "RepairContractError";
5819
+ }
5820
+ };
5821
+ var throwRepairContractError = (code, path, message) => {
5822
+ throw new RepairContractError(code, path, message);
5823
+ };
5824
+ var REPAIR_FIELDS = ["depends", "repairLayer", "repairSymbols", "priority", "scope", "sourceSymbols"];
5825
+ var REPAIR_TRACK_GEOMETRY_KEYS = [
5826
+ "mmtpMode",
5827
+ "timescale",
5828
+ "groupDurationMs",
5829
+ "groupDurationTicks",
5830
+ "keyframeIntervalMs",
5831
+ "keyframeIntervalTicks",
5832
+ "fec",
5833
+ "symbolSize",
5834
+ "interleaveDepthMs"
5835
+ ];
5836
+ var REPAIR_TRACK_ONLY_KEYS = ["repairLayer", "repairSymbols", "sourceSymbols", "scope"];
5837
+ function rejectRepairTrackGeometry(path, fields, fail) {
5838
+ for (const key of REPAIR_TRACK_GEOMETRY_KEYS) {
5839
+ if (fields[key] !== void 0) {
5840
+ fail(
5841
+ "track_repair_geometry",
5842
+ `${path}.${key}`,
5843
+ "a repair track carries no block geometry; it is shared with the source track's fec object"
5844
+ );
5845
+ }
5846
+ }
5847
+ }
5848
+ function repairReachability(fecObjects) {
5849
+ let declaresFecSource = false;
5850
+ const layerZeroNames = /* @__PURE__ */ new Set();
5851
+ for (const candidate of fecObjects) {
5852
+ if (typeof candidate !== "object" || candidate === null || Array.isArray(candidate)) continue;
5853
+ const fec = candidate;
5854
+ if (fec["algorithm"] === "none") continue;
5855
+ declaresFecSource = true;
5856
+ const repairTrack = fec["repairTrack"];
5857
+ if (typeof repairTrack === "string" && repairTrack.length > 0) layerZeroNames.add(repairTrack);
5858
+ }
5859
+ return { declaresFecSource, layerZeroNames };
5860
+ }
5861
+ function assertRepairTrackReachable(descriptor, reachability, fail) {
5862
+ if (dependsTarget(descriptor) !== void 0) return;
5863
+ if (reachability.declaresFecSource && !reachability.layerZeroNames.has(descriptor.name)) {
5864
+ fail(
5865
+ "track_repair_depends",
5866
+ `${descriptor.path}.depends`,
5867
+ "no source names this repair track in fec.repairTrack and it declares no depends"
5868
+ );
5869
+ }
5870
+ }
5871
+ function rejectRepairFieldsOnMediaTrack(path, fields, fail) {
5872
+ for (const key of REPAIR_TRACK_ONLY_KEYS) {
5873
+ if (fields[key] !== void 0) {
5874
+ fail("track_repair_layer", `${path}.${key}`, `${key} is a repair track field`);
5875
+ }
5876
+ }
5877
+ }
5878
+ function describeRepairTrack(name, path, fields) {
5879
+ const descriptor = { name, path };
5880
+ for (const field of REPAIR_FIELDS) {
5881
+ if (field in fields) descriptor[field] = fields[field];
5882
+ }
5883
+ return descriptor;
5884
+ }
5885
+ function isSafeInteger(value) {
5886
+ return typeof value === "number" && Number.isSafeInteger(value);
5887
+ }
5888
+ function positiveInteger(value) {
5889
+ return isSafeInteger(value) && value > 0;
5890
+ }
5891
+ function dependsTarget(descriptor) {
5892
+ const depends = descriptor.depends;
5893
+ return Array.isArray(depends) && depends.length === 1 && typeof depends[0] === "string" && depends[0].length > 0 ? depends[0] : void 0;
5894
+ }
5895
+ function validateRepairTrackFields(descriptor, fail) {
5896
+ const { path } = descriptor;
5897
+ if (descriptor.depends !== void 0 && dependsTarget(descriptor) === void 0) {
5898
+ fail("track_repair_depends", `${path}.depends`, "must name exactly one source track");
5899
+ }
5900
+ if (descriptor.repairLayer !== void 0 && (!isSafeInteger(descriptor.repairLayer) || descriptor.repairLayer < 0)) {
5901
+ fail("track_repair_layer", `${path}.repairLayer`, "must be a non-negative integer");
5902
+ }
5903
+ if (descriptor.repairSymbols !== void 0 && (!positiveInteger(descriptor.repairSymbols) || descriptor.repairSymbols > MAX_REPAIR_SYMBOLS)) {
5904
+ fail("track_repair_layer", `${path}.repairSymbols`, `must be a positive integer at most ${MAX_REPAIR_SYMBOLS}`);
5905
+ }
5906
+ if (descriptor.priority !== void 0 && (!isSafeInteger(descriptor.priority) || descriptor.priority < REPAIR_PRIORITY_MIN || descriptor.priority > REPAIR_PRIORITY_MAX)) {
5907
+ fail(
5908
+ "track_repair_priority",
5909
+ `${path}.priority`,
5910
+ `must be an integer from ${REPAIR_PRIORITY_MIN} to ${REPAIR_PRIORITY_MAX} (MoQT scale, lower first)`
5911
+ );
5912
+ }
5913
+ if (descriptor.scope !== void 0) {
5914
+ if (descriptor.scope !== "keyframe") {
5915
+ fail("track_repair_overlay", `${path}.scope`, 'must be "keyframe"');
5916
+ }
5917
+ if (descriptor.repairLayer !== void 0) {
5918
+ fail("track_repair_overlay", `${path}.repairLayer`, "an overlay is a separate FEC instance and carries no repairLayer");
5919
+ }
5920
+ for (const field of ["depends", "sourceSymbols", "repairSymbols", "priority"]) {
5921
+ if (descriptor[field] === void 0) {
5922
+ fail("track_repair_overlay", `${path}.${field}`, `an overlay must declare ${field}`);
5923
+ }
5924
+ }
5925
+ }
5926
+ if (descriptor.sourceSymbols !== void 0) {
5927
+ if (descriptor.scope === void 0) {
5928
+ fail("track_repair_overlay", `${path}.sourceSymbols`, "only an overlay (scope: keyframe) declares its own sourceSymbols");
5929
+ }
5930
+ if (!positiveInteger(descriptor.sourceSymbols) || descriptor.sourceSymbols > MAX_RAPTORQ_SOURCE_SYMBOLS) {
5931
+ fail(
5932
+ "track_fec_bounds",
5933
+ `${path}.sourceSymbols`,
5934
+ `must be a positive integer at most ${MAX_RAPTORQ_SOURCE_SYMBOLS} (RFC 6330 source block limit)`
5935
+ );
5936
+ }
5937
+ }
5938
+ if (isSafeInteger(descriptor.repairLayer) && descriptor.repairLayer >= 1) {
5939
+ for (const field of ["depends", "repairSymbols", "priority"]) {
5940
+ if (descriptor[field] === void 0) {
5941
+ fail("track_repair_layer", `${path}.${field}`, `repair layer ${descriptor.repairLayer} must declare ${field}`);
5942
+ }
5943
+ }
5944
+ }
5945
+ }
5946
+ function assembleRepairLayers(source, descriptors, fail = throwRepairContractError, options = {}) {
5947
+ const layerZeroName = typeof source.repairTrack === "string" && source.repairTrack.length > 0 ? source.repairTrack : void 0;
5948
+ const layerZero = layerZeroName === void 0 ? void 0 : descriptors.find((d) => d.name === layerZeroName);
5949
+ if (layerZeroName !== void 0 && layerZero === void 0 && options.layerZeroMustBeDeclared) {
5950
+ fail("track_repair_track", `${source.path}.repairTrack`, `unknown FEC repair track ${JSON.stringify(layerZeroName)}`);
5951
+ }
5952
+ const dependents = descriptors.filter((d) => d.name !== layerZeroName && dependsTarget(d) === source.name);
5953
+ const k = positiveInteger(source.sourceSymbols) ? source.sourceSymbols : 0;
5954
+ if (source.algorithm === "raptorq" && k > MAX_RAPTORQ_SOURCE_SYMBOLS) {
5955
+ fail(
5956
+ "track_fec_bounds",
5957
+ `${source.path}.sourceSymbols`,
5958
+ `must be at most ${MAX_RAPTORQ_SOURCE_SYMBOLS} (RFC 6330 source block limit)`
5959
+ );
5960
+ }
5961
+ if (layerZeroName === void 0) {
5962
+ if (dependents.length === 0) return void 0;
5963
+ fail(
5964
+ "track_repair_layer",
5965
+ `${dependents[0].path}.depends`,
5966
+ `repair layers of ${JSON.stringify(source.name)} require a layer 0 (fec.repairTrack) on the source`
5967
+ );
5968
+ }
5969
+ const layered = dependents.length > 0;
5970
+ let layerZeroSymbols = 0;
5971
+ if (positiveInteger(source.repairSymbols)) {
5972
+ layerZeroSymbols = source.repairSymbols;
5973
+ } else if (layered) {
5974
+ fail("track_fec", `${source.path}.repairSymbols`, "layered or overlay repair needs a positive integer repairSymbols on layer 0");
5975
+ }
5976
+ if (layered && !positiveInteger(source.sourceSymbols)) {
5977
+ fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
5978
+ }
5979
+ if (layered && source.algorithm !== "raptorq") {
5980
+ fail(
5981
+ "track_fec",
5982
+ `${source.path}.algorithm`,
5983
+ "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"
5984
+ );
5985
+ }
5986
+ let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
5987
+ if (layerZero !== void 0) {
5988
+ if (layerZero.depends !== void 0 && dependsTarget(layerZero) !== source.name) {
5989
+ fail(
5990
+ "track_repair_depends",
5991
+ `${layerZero.path}.depends`,
5992
+ `layer 0 of ${JSON.stringify(source.name)} must depend on that source`
5993
+ );
5994
+ }
5995
+ if (layerZero.repairLayer !== void 0 && layerZero.repairLayer !== 0) {
5996
+ fail("track_repair_layer", `${layerZero.path}.repairLayer`, "the track named by fec.repairTrack is layer 0");
5997
+ }
5998
+ if (layerZero.scope !== void 0) {
5999
+ fail("track_repair_overlay", `${layerZero.path}.scope`, "the track named by fec.repairTrack is base layer 0, not an overlay");
6000
+ }
6001
+ if (layerZero.repairSymbols !== void 0 && layerZero.repairSymbols !== layerZeroSymbols) {
6002
+ fail(
6003
+ "track_repair_layer",
6004
+ `${layerZero.path}.repairSymbols`,
6005
+ `must agree with the source's fec.repairSymbols (${layerZeroSymbols})`
6006
+ );
6007
+ }
6008
+ if (typeof layerZero.priority === "number") layerZeroPriority = layerZero.priority;
6009
+ }
6010
+ const baseLayers = [
6011
+ { layer: 0, repairTrackName: layerZeroName, repairSymbols: layerZeroSymbols, rsIdOffset: 0, priority: layerZeroPriority }
6012
+ ];
6013
+ const overlays = [];
6014
+ for (const d of dependents) {
6015
+ if (d.scope === void 0 && d.repairLayer === void 0) {
6016
+ fail(
6017
+ "track_repair_layer",
6018
+ `${d.path}.repairLayer`,
6019
+ `a repair track that depends on ${JSON.stringify(source.name)} must declare repairLayer (1..n) or scope: "keyframe"`
6020
+ );
6021
+ }
6022
+ }
6023
+ const layerTracks = dependents.filter((d) => d.scope === void 0).sort((a, b) => a.repairLayer - b.repairLayer);
6024
+ for (const d of dependents) {
6025
+ if (d.scope !== "keyframe") continue;
6026
+ if (overlays.length === 1) {
6027
+ fail(
6028
+ "track_repair_overlay",
6029
+ `${d.path}.scope`,
6030
+ `${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`
6031
+ );
6032
+ }
6033
+ const sourceSymbols = d.sourceSymbols;
6034
+ const repairSymbols = d.repairSymbols;
6035
+ if (sourceSymbols + repairSymbols - 1 > MAX_ENCODING_SYMBOL_ID) {
6036
+ fail(
6037
+ "track_fec_bounds",
6038
+ `${d.path}.repairSymbols`,
6039
+ `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6040
+ );
6041
+ }
6042
+ overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
6043
+ }
6044
+ let offset = layerZeroSymbols;
6045
+ let previousPriority = layerZeroPriority;
6046
+ layerTracks.forEach((d, i) => {
6047
+ const expected = i + 1;
6048
+ if (d.repairLayer === 0) {
6049
+ fail("track_repair_layer", `${d.path}.repairLayer`, `layer 0 of ${JSON.stringify(source.name)} is ${JSON.stringify(layerZeroName)}, named by fec.repairTrack`);
6050
+ }
6051
+ if (d.repairLayer !== expected) {
6052
+ fail(
6053
+ "track_repair_layer",
6054
+ `${d.path}.repairLayer`,
6055
+ 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}`
6056
+ );
6057
+ }
6058
+ const priority = d.priority;
6059
+ if (priority < previousPriority) {
6060
+ fail(
6061
+ "track_repair_priority",
6062
+ `${d.path}.priority`,
6063
+ `must be at least ${previousPriority}, the priority of layer ${expected - 1}: priority is monotonic non-decreasing with layer index`
6064
+ );
6065
+ }
6066
+ previousPriority = priority;
6067
+ const repairSymbols = d.repairSymbols;
6068
+ baseLayers.push({ layer: expected, repairTrackName: d.name, repairSymbols, rsIdOffset: offset, priority });
6069
+ offset += repairSymbols;
6070
+ });
6071
+ const totalBaseRepairSymbols = offset;
6072
+ if (totalBaseRepairSymbols > MAX_REPAIR_SYMBOLS) {
6073
+ fail(
6074
+ "track_fec_bounds",
6075
+ `${layerTracks.length === 0 ? source.path : layerTracks[layerTracks.length - 1].path}.repairSymbols`,
6076
+ `total repair symbols across base layers exceeds the 24-bit RS_ID space (${MAX_REPAIR_SYMBOLS})`
6077
+ );
6078
+ }
6079
+ if (k + totalBaseRepairSymbols - 1 > MAX_ENCODING_SYMBOL_ID) {
6080
+ fail(
6081
+ "track_fec_bounds",
6082
+ `${source.path}.sourceSymbols`,
6083
+ `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
6084
+ );
6085
+ }
6086
+ return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
6087
+ }
6088
+
5785
6089
  // src/carp-catalog.ts
5786
6090
  var VALID_ROLE_SUFFIXES = /* @__PURE__ */ new Set(["base", "delta", "repair"]);
5787
6091
  function parseTrackRole(trackName) {
@@ -5908,7 +6212,7 @@ function validateCmsfMmtpCatalog(value) {
5908
6212
  const tracks = catalog["tracks"];
5909
6213
  const trackRecords = [];
5910
6214
  const effective = (track, field) => track[field] ?? common[field];
5911
- const positiveInteger = (input) => Number.isSafeInteger(input) && input > 0;
6215
+ const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
5912
6216
  const positiveNumber = (input) => typeof input === "number" && Number.isFinite(input) && input > 0;
5913
6217
  for (let index = 0; index < tracks.length; index++) {
5914
6218
  const raw = tracks[index];
@@ -5944,21 +6248,27 @@ function validateCmsfMmtpCatalog(value) {
5944
6248
  const groupDurationTicks = effective(track, "groupDurationTicks");
5945
6249
  const keyframeIntervalMs = effective(track, "keyframeIntervalMs");
5946
6250
  const keyframeIntervalTicks = effective(track, "keyframeIntervalTicks");
5947
- if (groupDurationMs !== void 0 && !positiveInteger(groupDurationMs)) {
6251
+ if (groupDurationMs !== void 0 && !positiveInteger2(groupDurationMs)) {
5948
6252
  catalogError("track_group_duration_ms", `${path}.groupDurationMs`, "must be a positive integer");
5949
6253
  }
5950
- if (groupDurationTicks !== void 0 && !positiveInteger(groupDurationTicks)) {
6254
+ if (groupDurationTicks !== void 0 && !positiveInteger2(groupDurationTicks)) {
5951
6255
  catalogError("track_group_duration_ticks", `${path}.groupDurationTicks`, "must be a positive integer");
5952
6256
  }
5953
- if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger(keyframeIntervalTicks)) {
6257
+ if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
5954
6258
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
5955
6259
  }
6260
+ if (packaging === "fec-repair") {
6261
+ rejectRepairTrackGeometry(path, track, catalogError);
6262
+ validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
6263
+ } else {
6264
+ rejectRepairFieldsOnMediaTrack(path, track, catalogError);
6265
+ }
5956
6266
  if (packaging === "mmtp") {
5957
6267
  const mmtpMode = effective(track, "mmtpMode");
5958
6268
  if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
5959
6269
  catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
5960
6270
  }
5961
- if (!positiveInteger(timescale)) {
6271
+ if (!positiveInteger2(timescale)) {
5962
6272
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
5963
6273
  }
5964
6274
  if (groupDurationMs === void 0 && groupDurationTicks === void 0) {
@@ -5985,12 +6295,19 @@ function validateCmsfMmtpCatalog(value) {
5985
6295
  if ("interleaveDepth" in config || "interleaveMs" in config) {
5986
6296
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
5987
6297
  }
5988
- if (config["interleaveDepthMs"] !== void 0 && !positiveInteger(config["interleaveDepthMs"])) {
6298
+ if ("enhancementRepair" in config) {
6299
+ catalogError(
6300
+ "track_fec",
6301
+ `${path}.fec.enhancementRepair`,
6302
+ "repair layers are self-describing fec-repair tracks (depends, repairLayer); fec.enhancementRepair is not supported"
6303
+ );
6304
+ }
6305
+ if (config["interleaveDepthMs"] !== void 0 && !positiveInteger2(config["interleaveDepthMs"])) {
5989
6306
  catalogError("track_fec", `${path}.fec.interleaveDepthMs`, "must be a positive integer");
5990
6307
  }
5991
6308
  if (algorithm !== "none") {
5992
6309
  for (const field of ["sourceSymbols", "repairSymbols", "symbolSize"]) {
5993
- if (!positiveInteger(config[field])) {
6310
+ if (!positiveInteger2(config[field])) {
5994
6311
  catalogError("track_fec", `${path}.fec.${field}`, "must be a positive integer");
5995
6312
  }
5996
6313
  }
@@ -6000,15 +6317,43 @@ function validateCmsfMmtpCatalog(value) {
6000
6317
  }
6001
6318
  }
6002
6319
  }
6320
+ const repairDescriptors = trackRecords.flatMap(
6321
+ (track, index) => effective(track, "packaging") === "fec-repair" ? [describeRepairTrack(track["name"], `$.tracks[${index}]`, track)] : []
6322
+ );
6323
+ const reachability = repairReachability(
6324
+ trackRecords.filter((track) => effective(track, "packaging") !== "fec-repair").map((track) => track["fec"])
6325
+ );
6326
+ for (const descriptor of repairDescriptors) {
6327
+ assertRepairTrackReachable(descriptor, reachability, catalogError);
6328
+ const target = dependsTarget(descriptor);
6329
+ if (target === void 0) continue;
6330
+ const source = trackRecords.find((candidate) => candidate["name"] === target);
6331
+ const sourceFec = source?.["fec"];
6332
+ if (!source || effective(source, "packaging") !== "mmtp" || !sourceFec || sourceFec["algorithm"] === "none") {
6333
+ catalogError(
6334
+ "track_repair_depends",
6335
+ `${descriptor.path}.depends`,
6336
+ `${JSON.stringify(target)} is not an mmtp track with FEC`
6337
+ );
6338
+ }
6339
+ }
6003
6340
  for (let index = 0; index < trackRecords.length; index++) {
6004
6341
  const track = trackRecords[index];
6005
6342
  const fec = track["fec"];
6006
6343
  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
- }
6344
+ assembleRepairLayers(
6345
+ {
6346
+ name: track["name"],
6347
+ path: `$.tracks[${index}].fec`,
6348
+ algorithm: fec["algorithm"],
6349
+ sourceSymbols: fec["sourceSymbols"],
6350
+ repairSymbols: fec["repairSymbols"],
6351
+ repairTrack: fec["repairTrack"]
6352
+ },
6353
+ repairDescriptors,
6354
+ catalogError,
6355
+ { layerZeroMustBeDeclared: true }
6356
+ );
6012
6357
  }
6013
6358
  const switchingSets = /* @__PURE__ */ new Map();
6014
6359
  for (let index = 0; index < trackRecords.length; index++) {
@@ -7432,6 +7777,7 @@ var MmtpToCmaf = class {
7432
7777
  const samplesPerFrame = __privateGet(this, _audioTimescale) !== 1e6 ? __privateGet(this, _aacFrameSamples) : sampleDuration;
7433
7778
  const scaledTs = __privateGet(this, _audioTimescale) !== 1e6 ? __privateGet(this, _audioSampleCount) * samplesPerFrame : timestamp - __privateGet(this, _audioBaseTs);
7434
7779
  __privateWrapper(this, _audioSampleCount)._++;
7780
+ const scaledCompositionTimeOffset = compositionTimeOffset === void 0 || __privateGet(this, _audioTimescale) === 1e6 ? compositionTimeOffset : Math.round(compositionTimeOffset * __privateGet(this, _audioTimescale) / 1e6);
7435
7781
  return encodeDataSegment(
7436
7782
  sampleData,
7437
7783
  scaledTs,
@@ -7439,7 +7785,7 @@ var MmtpToCmaf = class {
7439
7785
  true,
7440
7786
  __privateWrapper(this, _audioSeq)._++,
7441
7787
  1,
7442
- compositionTimeOffset
7788
+ scaledCompositionTimeOffset
7443
7789
  );
7444
7790
  }
7445
7791
  /** Convert an ordered audio batch using the caller-owned timeline. */
@@ -7710,7 +8056,7 @@ var CmafBlockAssembler = class {
7710
8056
  __privateWrapper(this, _addFrameCount)._++;
7711
8057
  __privateMethod(this, _CmafBlockAssembler_instances, startAggregateTimer_fn).call(this);
7712
8058
  if (!__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, timestamp);
7713
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, data, timestamp, __privateGet(this, _frameDuration2), keyframe, true, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber);
8059
+ __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, data, timestamp, __privateGet(this, _frameDuration2), keyframe, true, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, void 0);
7714
8060
  __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "addFrame-direct", [{ data, timestamp, keyframe }]);
7715
8061
  }
7716
8062
  /** Mark a block as complete (all K source symbols received or FEC recovery succeeded).
@@ -7757,7 +8103,7 @@ var CmafBlockAssembler = class {
7757
8103
  /** Emit a single frame immediately as a one-sample segment (for oversized packets bypassing FEC). */
7758
8104
  addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
7759
8105
  if (!__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, timestamp);
7760
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, data, timestamp, __privateGet(this, _frameDuration2), keyframe, true, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber);
8106
+ __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, data, timestamp, __privateGet(this, _frameDuration2), keyframe, true, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, void 0);
7761
8107
  }
7762
8108
  /** Build and emit init segment from catalog config. */
7763
8109
  emitInit() {
@@ -7907,7 +8253,7 @@ unwrapTimestamp_fn = function(timestamp) {
7907
8253
  if (reference < 0) return timestamp;
7908
8254
  return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod;
7909
8255
  };
7910
- emitSample_fn = function(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
8256
+ emitSample_fn = function(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic) {
7911
8257
  const scaledTiming = authoredTiming === void 0 ? null : scaleAuthoredTiming(authoredTiming, __privateGet(this, _config).timescale);
7912
8258
  if (authoredTiming !== void 0 && scaledTiming === null) return;
7913
8259
  const authoredTimestamp = scaledTiming?.timestamp ?? timestamp;
@@ -7945,7 +8291,8 @@ emitSample_fn = function(data, timestamp, duration, keyframe, advancesHorizon, c
7945
8291
  ...movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber },
7946
8292
  ...sampleNumber === void 0 ? {} : { sampleNumber },
7947
8293
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
7948
- ...deliveryProvenance === void 0 ? {} : { deliveryProvenance }
8294
+ ...deliveryProvenance === void 0 ? {} : { deliveryProvenance },
8295
+ ...synthetic === void 0 ? {} : { synthetic }
7949
8296
  });
7950
8297
  if (advancesHorizon && unwrappedTimestamp > __privateGet(this, _lastSourceTs)) {
7951
8298
  __privateSet(this, _lastSourceTs, unwrappedTimestamp);
@@ -8083,7 +8430,8 @@ emitAudioGapFillNowBefore_fn = function(timestamp) {
8083
8430
  data: __privateGet(this, _lastDecodableAudioFrame).slice(),
8084
8431
  timestamp: fillTs,
8085
8432
  duration: __privateGet(this, _frameDuration2),
8086
- keyframe: true
8433
+ keyframe: true,
8434
+ synthetic: true
8087
8435
  }, false);
8088
8436
  }
8089
8437
  };
@@ -8101,7 +8449,7 @@ emitPerSample_fn = function(frames, audioDurationOverride, advancesHorizon = fal
8101
8449
  duration = audioDurationOverride ?? __privateGet(this, _frameDuration2);
8102
8450
  }
8103
8451
  if (duration <= 0) duration = audioDurationOverride ?? __privateGet(this, _frameDuration2);
8104
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, f.data, f.timestamp, duration, f.keyframe, advancesHorizon, f.catalogTrackName, f.mpuSequenceNumber, f.packetSequenceNumber, f.packetSequenceNumbers, f.repairedPacketSequenceNumbers, f.authoredTiming, f.deliveryProvenance, f.mmtpTimestamp, f.movieFragmentSequenceNumber, f.sampleNumber);
8452
+ __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, f.data, f.timestamp, duration, f.keyframe, advancesHorizon, f.catalogTrackName, f.mpuSequenceNumber, f.packetSequenceNumber, f.packetSequenceNumbers, f.repairedPacketSequenceNumbers, f.authoredTiming, f.deliveryProvenance, f.mmtpTimestamp, f.movieFragmentSequenceNumber, f.sampleNumber, f.synthetic);
8105
8453
  }
8106
8454
  };
8107
8455
  _dumpCount = new WeakMap();
@@ -8176,7 +8524,7 @@ drainRecoveredUpTo_fn = function(horizonTs) {
8176
8524
  const ready = [...__privateGet(this, _pendingRecovered).values()].filter((frame) => frame.timestamp <= horizonTs).sort((a, b) => a.timestamp - b.timestamp);
8177
8525
  for (const frame of ready) {
8178
8526
  __privateGet(this, _pendingRecovered).delete(frame.timestamp);
8179
- __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, frame.data, frame.timestamp, __privateGet(this, _frameDuration2), frame.keyframe, false, frame.catalogTrackName, frame.mpuSequenceNumber, frame.packetSequenceNumber, frame.packetSequenceNumbers, frame.repairedPacketSequenceNumbers, frame.authoredTiming, frame.deliveryProvenance, frame.mmtpTimestamp, frame.movieFragmentSequenceNumber, frame.sampleNumber);
8527
+ __privateMethod(this, _CmafBlockAssembler_instances, emitSample_fn).call(this, frame.data, frame.timestamp, __privateGet(this, _frameDuration2), frame.keyframe, false, frame.catalogTrackName, frame.mpuSequenceNumber, frame.packetSequenceNumber, frame.packetSequenceNumbers, frame.repairedPacketSequenceNumbers, frame.authoredTiming, frame.deliveryProvenance, frame.mmtpTimestamp, frame.movieFragmentSequenceNumber, frame.sampleNumber, frame.synthetic);
8180
8528
  __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "recovered-drain", [frame]);
8181
8529
  }
8182
8530
  };
@@ -8225,7 +8573,8 @@ flushBlockWithFill_fn = function(sbn) {
8225
8573
  data: isVideo ? __privateGet(this, _fillFrame) : audioConcealmentFrame?.slice() ?? new Uint8Array(0),
8226
8574
  timestamp: interpolatedTs,
8227
8575
  // Video: first fill is keyframe (IDR). Audio: all fill marked keyframe.
8228
- keyframe: isVideo ? !block.has(0) && esi === 0 : true
8576
+ keyframe: isVideo ? !block.has(0) && esi === 0 : true,
8577
+ synthetic: true
8229
8578
  });
8230
8579
  }
8231
8580
  }
@@ -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);
@@ -14487,116 +14918,1430 @@ var ReedSolomonCodec = class {
14487
14918
  }
14488
14919
  };
14489
14920
 
14490
- // src/multicast-transport.ts
14491
- var MAX_TRACKED_DROPPED_PIDS = 16;
14492
- function getMulticastGlobals() {
14493
- return globalThis;
14494
- }
14495
- function hasMulticastGateway() {
14496
- return typeof getMulticastGlobals().multicast?.subscribe === "function";
14497
- }
14498
- function normalizeResolvedTransport(value) {
14499
- if (value === "native") return "native";
14500
- if (value === "amt") return "amt";
14501
- return void 0;
14502
- }
14503
- var _onPacket, _subscription2, _bytesListener, _transportListener, _resolvedTransport, _videoConfirmed, _audioConfirmed, _watchdog, _failbackWindowMs, _onTakeover, _onFailback, _disposed4, _stats3, _droppedPidCounts, _packetIds, _joinGeneration, _MulticastTransport_instances, releaseSubscription_fn, acceptPacket_fn, recordUnregisteredPidDrop_fn, checkTakeover_fn, resetWatchdog_fn;
14504
- var _MulticastTransport = class _MulticastTransport {
14505
- constructor(onPacket) {
14506
- __privateAdd(this, _MulticastTransport_instances);
14507
- __privateAdd(this, _onPacket);
14508
- __privateAdd(this, _subscription2, null);
14509
- __privateAdd(this, _bytesListener, null);
14510
- __privateAdd(this, _transportListener, null);
14511
- __privateAdd(this, _resolvedTransport);
14512
- __privateAdd(this, _videoConfirmed, false);
14513
- __privateAdd(this, _audioConfirmed, false);
14514
- __privateAdd(this, _watchdog, null);
14515
- __privateAdd(this, _failbackWindowMs, null);
14516
- __privateAdd(this, _onTakeover, null);
14517
- __privateAdd(this, _onFailback, null);
14518
- __privateAdd(this, _disposed4, false);
14519
- __privateAdd(this, _stats3, {
14520
- packetsReceived: 0,
14521
- bytesReceived: 0,
14522
- packetsDroppedUnregisteredPid: 0,
14523
- packetsDroppedUnparseable: 0
14524
- });
14525
- __privateAdd(this, _droppedPidCounts, /* @__PURE__ */ new Map());
14526
- __privateAdd(this, _packetIds, null);
14527
- __privateAdd(this, _joinGeneration, 0);
14528
- __privateSet(this, _onPacket, onPacket);
14529
- }
14530
- static isAvailable() {
14531
- return hasMulticastGateway();
14921
+ // node_modules/@blockcast/mmt-transport/dist/types.js
14922
+ var MoqFecAlgorithm;
14923
+ (function(MoqFecAlgorithm2) {
14924
+ MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
14925
+ MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
14926
+ MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
14927
+ })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
14928
+
14929
+ // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
14930
+ var DRIADDiscovery = class {
14931
+ constructor() {
14932
+ __publicField(this, "cache", /* @__PURE__ */ new Map());
14933
+ __publicField(this, "cacheExpiry", 3e5);
14532
14934
  }
14533
- async join(config, context) {
14534
- const generation = ++__privateWrapper(this, _joinGeneration)._;
14535
- __privateMethod(this, _MulticastTransport_instances, releaseSubscription_fn).call(this);
14536
- if (__privateGet(this, _disposed4)) return false;
14537
- if (!_MulticastTransport.isAvailable()) {
14538
- console.warn("[MulticastTransport] Multicast API not available");
14539
- return false;
14935
+ // 5 minutes
14936
+ /**
14937
+ * Discover AMT relays for a multicast source address (RFC 8777)
14938
+ *
14939
+ * @param source - The multicast source IP address (NOT the group!)
14940
+ * @returns Array of discovered AMT relays that can tunnel traffic from this source
14941
+ */
14942
+ async discoverRelays(source) {
14943
+ const cached = this.cache.get(source);
14944
+ if (cached) {
14945
+ return cached;
14540
14946
  }
14541
14947
  try {
14542
- const packetIds = config.packetIds?.length ? new Set(config.packetIds) : null;
14543
- console.log(
14544
- `[MulticastTransport] window.multicast.subscribe(${config.sourceAddress}, ${config.groupAddress}, ${config.port})`
14545
- );
14546
- const subscription = await getMulticastGlobals().multicast.subscribe({
14547
- source: config.sourceAddress,
14548
- group: config.groupAddress,
14549
- port: config.port,
14550
- consume: "bytes",
14551
- mode: config.mode,
14552
- amtRelay: config.amtRelay,
14553
- amtRelayPort: config.amtRelayPort,
14554
- packetIds: config.packetIds,
14555
- tracks: config.tracks?.map(({ name, packetId }) => ({ name, packetId }))
14556
- });
14557
- console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
14558
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) {
14559
- void subscription.unsubscribe();
14560
- return false;
14948
+ const reversedSource = source.split(".").reverse().join(".");
14949
+ const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
14950
+ console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
14951
+ const relays = await this.queryDRIADProxy(source);
14952
+ if (relays.length > 0) {
14953
+ this.cache.set(source, relays);
14954
+ setTimeout(() => this.cache.delete(source), this.cacheExpiry);
14561
14955
  }
14562
- if (typeof subscription.addEventListener !== "function") {
14563
- if (typeof subscription.unsubscribe === "function") {
14564
- void subscription.unsubscribe();
14956
+ return relays;
14957
+ } catch (error) {
14958
+ console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
14959
+ return [];
14960
+ }
14961
+ }
14962
+ /**
14963
+ * Query DRIAD proxy service (browser-compatible)
14964
+ */
14965
+ async queryDRIADProxy(source) {
14966
+ const proxyEndpoints = [
14967
+ "https://driad.amt.net/api/v1/relays",
14968
+ "https://multicast-gateway.cloudflare.com/driad"
14969
+ ];
14970
+ for (const endpoint of proxyEndpoints) {
14971
+ try {
14972
+ const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
14973
+ method: "GET",
14974
+ headers: { Accept: "application/json" },
14975
+ signal: AbortSignal.timeout(5e3)
14976
+ });
14977
+ if (response.ok) {
14978
+ const data = await response.json();
14979
+ return data.relays || [];
14565
14980
  }
14566
- throw new Error("window.multicast subscription does not support bytes events");
14981
+ } catch {
14567
14982
  }
14568
- const onBytes = (event) => {
14569
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return;
14570
- const detail = event.detail;
14571
- const packet = detail instanceof Uint8Array ? detail : new Uint8Array(detail);
14572
- if (!__privateMethod(this, _MulticastTransport_instances, acceptPacket_fn).call(this, packet)) return;
14573
- __privateGet(this, _stats3).packetsReceived++;
14574
- __privateGet(this, _stats3).bytesReceived += packet.byteLength;
14575
- __privateGet(this, _onPacket).call(this, packet, context);
14576
- __privateMethod(this, _MulticastTransport_instances, resetWatchdog_fn).call(this);
14577
- };
14578
- const onTransportChange = (event) => {
14579
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return;
14580
- const transport = normalizeResolvedTransport(event.detail);
14581
- if (transport) __privateSet(this, _resolvedTransport, transport);
14582
- };
14583
- __privateSet(this, _subscription2, subscription);
14584
- __privateSet(this, _bytesListener, onBytes);
14585
- __privateSet(this, _transportListener, onTransportChange);
14586
- __privateSet(this, _packetIds, packetIds);
14587
- __privateSet(this, _resolvedTransport, normalizeResolvedTransport(subscription.transport));
14588
- subscription.addEventListener("bytes", onBytes);
14589
- subscription.addEventListener("transportchange", onTransportChange);
14590
- __privateMethod(this, _MulticastTransport_instances, resetWatchdog_fn).call(this);
14591
- console.log(
14592
- `[MulticastTransport] Joined ${config.groupAddress}:${config.port}`
14593
- );
14594
- return true;
14595
- } catch (err) {
14596
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return false;
14597
- __privateMethod(this, _MulticastTransport_instances, releaseSubscription_fn).call(this);
14598
- console.error("[MulticastTransport] Failed to join SSM group:", err);
14599
- return false;
14983
+ }
14984
+ const dohRelay = await this.queryDNSOverHTTPS(source);
14985
+ if (dohRelay) {
14986
+ return [dohRelay];
14987
+ }
14988
+ return [];
14989
+ }
14990
+ /**
14991
+ * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
14992
+ */
14993
+ async queryDNSOverHTTPS(source) {
14994
+ try {
14995
+ const reversedSource = source.split(".").reverse().join(".");
14996
+ const queryName = `${reversedSource}.amt.in-addr.arpa`;
14997
+ const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
14998
+ const response = await fetch(dohUrl, {
14999
+ headers: { Accept: "application/dns-json" },
15000
+ signal: AbortSignal.timeout(3e3)
15001
+ });
15002
+ if (!response.ok) {
15003
+ return null;
15004
+ }
15005
+ const result = await response.json();
15006
+ if (result.Answer && result.Answer.length > 0) {
15007
+ return {
15008
+ host: result.Answer[0].data,
15009
+ port: 2268,
15010
+ priority: 10,
15011
+ weight: 100,
15012
+ asn: 0
15013
+ };
15014
+ }
15015
+ return null;
15016
+ } catch (error) {
15017
+ console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
15018
+ return null;
15019
+ }
15020
+ }
15021
+ /**
15022
+ * Select best relay based on RTT measurements
15023
+ */
15024
+ async selectBestRelay(relays) {
15025
+ if (relays.length === 0)
15026
+ return null;
15027
+ const measured = await Promise.all(relays.map(async (relay) => {
15028
+ const rtt = await this.measureRTT(relay.host, relay.port);
15029
+ return { ...relay, rtt };
15030
+ }));
15031
+ measured.sort((a, b) => {
15032
+ if (a.priority !== b.priority)
15033
+ return a.priority - b.priority;
15034
+ return (a.rtt || Infinity) - (b.rtt || Infinity);
15035
+ });
15036
+ console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
15037
+ return measured[0];
15038
+ }
15039
+ async measureRTT(host, _port) {
15040
+ const start = performance.now();
15041
+ try {
15042
+ await fetch(`https://${host}/health`, {
15043
+ method: "HEAD",
15044
+ signal: AbortSignal.timeout(2e3),
15045
+ mode: "no-cors"
15046
+ });
15047
+ return performance.now() - start;
15048
+ } catch {
15049
+ return Infinity;
15050
+ }
15051
+ }
15052
+ /**
15053
+ * Clear the relay cache
15054
+ */
15055
+ clearCache() {
15056
+ this.cache.clear();
15057
+ }
15058
+ /**
15059
+ * Get cached relays for a source address
15060
+ */
15061
+ getCached(source) {
15062
+ return this.cache.get(source);
15063
+ }
15064
+ };
15065
+ var driadDiscovery = new DRIADDiscovery();
15066
+
15067
+ // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
15068
+ function endpointKey(endpoint) {
15069
+ return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
15070
+ }
15071
+ function selectMulticastTier(endpoints, estimate) {
15072
+ if (endpoints.length <= 1)
15073
+ return endpoints[0];
15074
+ const ranked = endpoints.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > 0).sort((a, b) => a.bandwidth - b.bandwidth);
15075
+ if (ranked.length < 2)
15076
+ return endpoints[0];
15077
+ if (estimate === void 0)
15078
+ return ranked[0];
15079
+ const budget = estimate * 0.8;
15080
+ let selected;
15081
+ for (const endpoint of ranked) {
15082
+ if (endpoint.bandwidth <= budget)
15083
+ selected = endpoint;
15084
+ }
15085
+ return selected ?? ranked[0];
15086
+ }
15087
+
15088
+ // node_modules/@blockcast/mmt-transport/dist/abr-controller.js
15089
+ var QUALITY_LEVELS = [
15090
+ { name: "240p", bitrate: 3e5, width: 426, height: 240, fps: 15 },
15091
+ { name: "360p", bitrate: 5e5, width: 640, height: 360, fps: 24 },
15092
+ { name: "480p", bitrate: 1e6, width: 854, height: 480, fps: 30 },
15093
+ { name: "720p", bitrate: 25e5, width: 1280, height: 720, fps: 30 },
15094
+ { name: "1080p", bitrate: 5e6, width: 1920, height: 1080, fps: 30 },
15095
+ { name: "1440p", bitrate: 8e6, width: 2560, height: 1440, fps: 30 },
15096
+ { name: "4K", bitrate: 15e6, width: 3840, height: 2160, fps: 30 }
15097
+ ];
15098
+ var AdaptiveBitrateController = class {
15099
+ constructor(initialQuality) {
15100
+ __publicField(this, "currentQualityIndex");
15101
+ __publicField(this, "history", []);
15102
+ __publicField(this, "historyWindow", 1e4);
15103
+ // 10 second window
15104
+ __publicField(this, "upgradeThreshold", 0.8);
15105
+ // 80% of target bitrate sustained
15106
+ __publicField(this, "downgradeThreshold", 0.5);
15107
+ // 50% of target bitrate triggers downgrade
15108
+ __publicField(this, "stabilityPeriod", 5e3);
15109
+ // Wait 5s before upgrading
15110
+ __publicField(this, "lastQualityChange", 0);
15111
+ __publicField(this, "onQualityChange");
15112
+ // FEC stats for effective loss rate calculation
15113
+ __publicField(this, "fecStats", {
15114
+ rawLossRate: 0,
15115
+ effectiveLossRate: 0,
15116
+ recoveryRate: 1,
15117
+ fecEnabled: false
15118
+ });
15119
+ this.currentQualityIndex = initialQuality ? QUALITY_LEVELS.findIndex((q) => q.name === initialQuality.name) : 0;
15120
+ if (this.currentQualityIndex < 0)
15121
+ this.currentQualityIndex = 0;
15122
+ }
15123
+ setCallback(callback) {
15124
+ this.onQualityChange = callback;
15125
+ }
15126
+ getCurrentQuality() {
15127
+ return QUALITY_LEVELS[this.currentQualityIndex];
15128
+ }
15129
+ /** Selects the multicast (S,G) tier without replacing a player's unicast ABR manager. */
15130
+ selectMulticastTier(endpoints, estimate = this.getMetrics().measuredBitrate || void 0) {
15131
+ return selectMulticastTier(endpoints, estimate);
15132
+ }
15133
+ /**
15134
+ * Record network sample for bitrate adaptation
15135
+ *
15136
+ * @param bytesReceived - Bytes received in this sample
15137
+ * @param packetsLost - Packets lost (raw, before FEC recovery)
15138
+ */
15139
+ recordSample(bytesReceived, packetsLost) {
15140
+ const now = Date.now();
15141
+ this.history.push({ timestamp: now, bytesReceived, packetsLost });
15142
+ this.history = this.history.filter((s) => now - s.timestamp < this.historyWindow);
15143
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
15144
+ const currentQuality = this.getCurrentQuality();
15145
+ const effectiveLossRate = this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate;
15146
+ if (now - this.lastQualityChange < this.stabilityPeriod) {
15147
+ return;
15148
+ }
15149
+ if (effectiveLossRate > 0.05 || measuredBitrate < currentQuality.bitrate * this.downgradeThreshold) {
15150
+ this.downgrade();
15151
+ return;
15152
+ }
15153
+ if (measuredBitrate > currentQuality.bitrate * this.upgradeThreshold && effectiveLossRate < 0.01 && this.currentQualityIndex < QUALITY_LEVELS.length - 1) {
15154
+ this.upgrade();
15155
+ }
15156
+ }
15157
+ /**
15158
+ * Update FEC statistics for ABR decisions
15159
+ *
15160
+ * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
15161
+ * (after FEC recovery) rather than raw transport loss rate.
15162
+ *
15163
+ * @param stats - FEC statistics from the FEC decoder
15164
+ */
15165
+ setFecStats(stats) {
15166
+ this.fecStats = stats;
15167
+ }
15168
+ /**
15169
+ * Get current FEC statistics
15170
+ */
15171
+ getFecStats() {
15172
+ return { ...this.fecStats };
15173
+ }
15174
+ calculateMetrics() {
15175
+ if (this.history.length < 2) {
15176
+ return { measuredBitrate: 0, lossRate: 0 };
15177
+ }
15178
+ const totalBytes = this.history.reduce((sum, s) => sum + s.bytesReceived, 0);
15179
+ const totalLost = this.history.reduce((sum, s) => sum + s.packetsLost, 0);
15180
+ const duration = (this.history[this.history.length - 1].timestamp - this.history[0].timestamp) / 1e3;
15181
+ const measuredBitrate = duration > 0 ? totalBytes * 8 / duration : 0;
15182
+ const lossRate = totalLost / (this.history.length + totalLost);
15183
+ return { measuredBitrate, lossRate };
15184
+ }
15185
+ upgrade() {
15186
+ if (this.currentQualityIndex >= QUALITY_LEVELS.length - 1)
15187
+ return;
15188
+ this.currentQualityIndex++;
15189
+ this.lastQualityChange = Date.now();
15190
+ const newQuality = this.getCurrentQuality();
15191
+ console.log(`[ABR] Upgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
15192
+ this.onQualityChange?.(newQuality);
15193
+ }
15194
+ downgrade() {
15195
+ if (this.currentQualityIndex <= 0)
15196
+ return;
15197
+ this.currentQualityIndex--;
15198
+ this.lastQualityChange = Date.now();
15199
+ const newQuality = this.getCurrentQuality();
15200
+ console.log(`[ABR] Downgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
15201
+ this.onQualityChange?.(newQuality);
15202
+ }
15203
+ /**
15204
+ * Force quality level (for testing)
15205
+ */
15206
+ setQuality(name) {
15207
+ const index = QUALITY_LEVELS.findIndex((q) => q.name === name);
15208
+ if (index >= 0) {
15209
+ this.currentQualityIndex = index;
15210
+ this.lastQualityChange = Date.now();
15211
+ this.onQualityChange?.(this.getCurrentQuality());
15212
+ }
15213
+ }
15214
+ /**
15215
+ * Get current metrics including both raw and effective loss rates
15216
+ */
15217
+ getMetrics() {
15218
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
15219
+ return {
15220
+ measuredBitrate,
15221
+ rawLossRate,
15222
+ effectiveLossRate: this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate,
15223
+ fecEnabled: this.fecStats.fecEnabled,
15224
+ sampleCount: this.history.length
15225
+ };
15226
+ }
15227
+ /**
15228
+ * Reset history and start fresh
15229
+ */
15230
+ reset() {
15231
+ this.history = [];
15232
+ this.lastQualityChange = 0;
15233
+ }
15234
+ };
15235
+
15236
+ // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
15237
+ var DEFAULT_DWELL_MS = 3e3;
15238
+ var DEFAULT_JOIN_DEADLINE_MS = 5e3;
15239
+ var _state2, _current, _target, _estimate, _favored, _joinStartedAt, _lastCommittedTimestamp, _dwellMs, _joinDeadlineMs, _MulticastOrchestrator_instances, now_fn;
15240
+ var MulticastOrchestrator = class {
15241
+ constructor(options) {
15242
+ __privateAdd(this, _MulticastOrchestrator_instances);
15243
+ __publicField(this, "options");
15244
+ __privateAdd(this, _state2, "stable");
15245
+ __privateAdd(this, _current);
15246
+ __privateAdd(this, _target);
15247
+ __privateAdd(this, _estimate);
15248
+ __privateAdd(this, _favored);
15249
+ __privateAdd(this, _joinStartedAt, 0);
15250
+ __privateAdd(this, _lastCommittedTimestamp, Number.NEGATIVE_INFINITY);
15251
+ __privateAdd(this, _dwellMs);
15252
+ __privateAdd(this, _joinDeadlineMs);
15253
+ this.options = options;
15254
+ __privateSet(this, _dwellMs, options.dwellMs ?? DEFAULT_DWELL_MS);
15255
+ __privateSet(this, _joinDeadlineMs, options.joinDeadlineMs ?? DEFAULT_JOIN_DEADLINE_MS);
15256
+ if (!Number.isFinite(__privateGet(this, _dwellMs)) || !Number.isFinite(__privateGet(this, _joinDeadlineMs)) || __privateGet(this, _dwellMs) <= 0 || __privateGet(this, _joinDeadlineMs) <= 0) {
15257
+ throw new Error("Multicast dwell and join deadline must be positive");
15258
+ }
15259
+ }
15260
+ get state() {
15261
+ return __privateGet(this, _state2);
15262
+ }
15263
+ get current() {
15264
+ return __privateGet(this, _current);
15265
+ }
15266
+ get target() {
15267
+ return __privateGet(this, _target);
15268
+ }
15269
+ get estimate() {
15270
+ return __privateGet(this, _estimate);
15271
+ }
15272
+ start() {
15273
+ __privateGet(this, _current) ?? __privateSet(this, _current, this.options.initialEndpoint ?? selectMulticastTier(this.options.endpoints, void 0));
15274
+ return __privateGet(this, _current);
15275
+ }
15276
+ onGoodput(sample) {
15277
+ const bitrate = sample.bitrate;
15278
+ if (!__privateGet(this, _current) || this.options.adaptive === false)
15279
+ return void 0;
15280
+ if (__privateGet(this, _state2) === "joining")
15281
+ return this.poll();
15282
+ if (bitrate === void 0 || !Number.isFinite(bitrate))
15283
+ return void 0;
15284
+ __privateSet(this, _estimate, bitrate);
15285
+ const desired = selectMulticastTier(this.options.endpoints, bitrate);
15286
+ if (!desired)
15287
+ return void 0;
15288
+ const desiredKey = endpointKey(desired);
15289
+ if (desiredKey === endpointKey(__privateGet(this, _current))) {
15290
+ if (__privateGet(this, _favored)?.source === "goodput")
15291
+ __privateSet(this, _favored, void 0);
15292
+ return void 0;
15293
+ }
15294
+ if (typeof desired.bandwidth !== "number" || typeof __privateGet(this, _current).bandwidth !== "number" || desired.bandwidth >= __privateGet(this, _current).bandwidth) {
15295
+ if (__privateGet(this, _favored)?.source === "goodput")
15296
+ __privateSet(this, _favored, void 0);
15297
+ return void 0;
15298
+ }
15299
+ const now = __privateMethod(this, _MulticastOrchestrator_instances, now_fn).call(this);
15300
+ if (!__privateGet(this, _favored) || __privateGet(this, _favored).key !== desiredKey || __privateGet(this, _favored).source !== "goodput") {
15301
+ __privateSet(this, _favored, { key: desiredKey, since: now, source: "goodput" });
15302
+ return void 0;
15303
+ }
15304
+ if (now - __privateGet(this, _favored).since < __privateGet(this, _dwellMs))
15305
+ return void 0;
15306
+ __privateSet(this, _state2, "joining");
15307
+ __privateSet(this, _target, desired);
15308
+ __privateSet(this, _joinStartedAt, now);
15309
+ __privateSet(this, _favored, void 0);
15310
+ return { kind: "join-target", current: __privateGet(this, _current), target: desired };
15311
+ }
15312
+ onHeadroom(sample) {
15313
+ if (!__privateGet(this, _current) || this.options.adaptive === false || __privateGet(this, _state2) === "joining")
15314
+ return void 0;
15315
+ if (!sample.healthy) {
15316
+ if (__privateGet(this, _favored)?.source === "headroom")
15317
+ __privateSet(this, _favored, void 0);
15318
+ return void 0;
15319
+ }
15320
+ if (__privateGet(this, _favored)?.source === "goodput")
15321
+ return void 0;
15322
+ const currentBandwidth = __privateGet(this, _current).bandwidth;
15323
+ if (typeof currentBandwidth !== "number")
15324
+ return void 0;
15325
+ const desired = this.options.endpoints.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > currentBandwidth).sort((a, b) => a.bandwidth - b.bandwidth)[0];
15326
+ if (!desired) {
15327
+ __privateSet(this, _favored, void 0);
15328
+ return void 0;
15329
+ }
15330
+ const desiredKey = endpointKey(desired);
15331
+ if (desiredKey === endpointKey(__privateGet(this, _current))) {
15332
+ __privateSet(this, _favored, void 0);
15333
+ return void 0;
15334
+ }
15335
+ const now = __privateMethod(this, _MulticastOrchestrator_instances, now_fn).call(this);
15336
+ if (!__privateGet(this, _favored) || __privateGet(this, _favored).key !== desiredKey) {
15337
+ __privateSet(this, _favored, { key: desiredKey, since: now, source: "headroom" });
15338
+ return void 0;
15339
+ }
15340
+ if (now - __privateGet(this, _favored).since < __privateGet(this, _dwellMs))
15341
+ return void 0;
15342
+ __privateSet(this, _state2, "joining");
15343
+ __privateSet(this, _target, desired);
15344
+ __privateSet(this, _joinStartedAt, now);
15345
+ __privateSet(this, _favored, void 0);
15346
+ return { kind: "join-target", current: __privateGet(this, _current), target: desired };
15347
+ }
15348
+ onTierPacket(packet) {
15349
+ if (!__privateGet(this, _current))
15350
+ return void 0;
15351
+ if (packet.endpointKey === endpointKey(__privateGet(this, _current)) && Number.isFinite(packet.timestamp)) {
15352
+ __privateSet(this, _lastCommittedTimestamp, Math.max(__privateGet(this, _lastCommittedTimestamp), packet.timestamp));
15353
+ }
15354
+ if (__privateGet(this, _state2) !== "joining" || !__privateGet(this, _target))
15355
+ return void 0;
15356
+ const expired = this.poll();
15357
+ if (expired)
15358
+ return expired;
15359
+ if (packet.endpointKey !== endpointKey(__privateGet(this, _target)) || !packet.keyframe || !packet.hasValidCodecConfig || !Number.isFinite(packet.timestamp) || packet.timestamp < __privateGet(this, _lastCommittedTimestamp))
15360
+ return void 0;
15361
+ const command = {
15362
+ kind: "commit-swap",
15363
+ target: __privateGet(this, _target),
15364
+ old: __privateGet(this, _current)
15365
+ };
15366
+ __privateSet(this, _lastCommittedTimestamp, packet.timestamp);
15367
+ __privateSet(this, _current, __privateGet(this, _target));
15368
+ __privateSet(this, _target, void 0);
15369
+ __privateSet(this, _state2, "stable");
15370
+ return command;
15371
+ }
15372
+ poll() {
15373
+ if (__privateGet(this, _state2) !== "joining" || !__privateGet(this, _target) || !__privateGet(this, _current))
15374
+ return void 0;
15375
+ if (__privateMethod(this, _MulticastOrchestrator_instances, now_fn).call(this) - __privateGet(this, _joinStartedAt) < __privateGet(this, _joinDeadlineMs))
15376
+ return void 0;
15377
+ return this.cancel();
15378
+ }
15379
+ cancel() {
15380
+ if (__privateGet(this, _state2) !== "joining" || !__privateGet(this, _target) || !__privateGet(this, _current))
15381
+ return void 0;
15382
+ const command = {
15383
+ kind: "abandon-join",
15384
+ current: __privateGet(this, _current),
15385
+ target: __privateGet(this, _target)
15386
+ };
15387
+ __privateSet(this, _target, void 0);
15388
+ __privateSet(this, _state2, "stable");
15389
+ return command;
15390
+ }
15391
+ };
15392
+ _state2 = new WeakMap();
15393
+ _current = new WeakMap();
15394
+ _target = new WeakMap();
15395
+ _estimate = new WeakMap();
15396
+ _favored = new WeakMap();
15397
+ _joinStartedAt = new WeakMap();
15398
+ _lastCommittedTimestamp = new WeakMap();
15399
+ _dwellMs = new WeakMap();
15400
+ _joinDeadlineMs = new WeakMap();
15401
+ _MulticastOrchestrator_instances = new WeakSet();
15402
+ now_fn = function() {
15403
+ const now = this.options.now();
15404
+ if (!Number.isFinite(now))
15405
+ throw new Error("Multicast orchestrator clock must be finite");
15406
+ return now;
15407
+ };
15408
+
15409
+ // node_modules/@blockcast/mmt-transport/dist/endpoint-config.js
15410
+ function toWindowMulticastSubscribeConfig(input) {
15411
+ if (input.mode !== void 0 && !["auto", "native", "tunnel"].includes(input.mode)) {
15412
+ throw new TypeError(`Unsupported multicast mode: ${String(input.mode)}`);
15413
+ }
15414
+ const base = {
15415
+ group: input.group,
15416
+ port: input.port,
15417
+ ...input.source?.trim() ? { source: input.source.trim() } : {},
15418
+ consume: "bytes",
15419
+ ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
15420
+ };
15421
+ const relay = input.amtRelay?.trim();
15422
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
15423
+ if (!wantsAmt) {
15424
+ const native = {
15425
+ ...base,
15426
+ origin: "ip-multicast",
15427
+ ...input.tracks?.length ? { tracks: input.tracks.map(({ name, packetId }) => ({ name, packetId })) } : {}
15428
+ };
15429
+ return native;
15430
+ }
15431
+ const relayPort = input.amtRelayPort;
15432
+ if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
15433
+ throw new TypeError("AMT requires a resolved relay and a valid relay port");
15434
+ }
15435
+ return {
15436
+ ...base,
15437
+ origin: "amt",
15438
+ relay,
15439
+ relayPort
15440
+ };
15441
+ }
15442
+ function isValidMulticastGroupAddress(address) {
15443
+ const value = address?.trim().toLowerCase();
15444
+ if (!value)
15445
+ return false;
15446
+ if (value.startsWith("ff"))
15447
+ return isValidIpv6MulticastAddress(value);
15448
+ const parts = value.split(".");
15449
+ if (parts.length !== 4)
15450
+ return false;
15451
+ const octets = parts.map((part) => {
15452
+ if (!/^\d+$/.test(part))
15453
+ return Number.NaN;
15454
+ const octet = Number(part);
15455
+ return Number.isInteger(octet) && octet >= 0 && octet <= 255 ? octet : Number.NaN;
15456
+ });
15457
+ return octets.every(Number.isInteger) && octets[0] >= 224 && octets[0] <= 239;
15458
+ }
15459
+ function normalizeMulticastEndpoint(endpoint) {
15460
+ const groupAddress = endpoint.groupAddress.trim().toLowerCase();
15461
+ const sourceAddress = endpoint.sourceAddress?.trim().toLowerCase() || void 0;
15462
+ const amtRelay = endpoint.amtRelay?.trim().toLowerCase() || void 0;
15463
+ if (!isValidMulticastGroupAddress(groupAddress) || !isPositivePort(endpoint.port))
15464
+ return void 0;
15465
+ if (endpoint.mode && !["auto", "native", "tunnel"].includes(endpoint.mode))
15466
+ return void 0;
15467
+ if (endpoint.amtRelayPort !== void 0 && !isPositivePort(endpoint.amtRelayPort))
15468
+ return void 0;
15469
+ return {
15470
+ groupAddress,
15471
+ ...sourceAddress ? { sourceAddress } : {},
15472
+ port: endpoint.port,
15473
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
15474
+ ...amtRelay ? { amtRelay } : {},
15475
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
15476
+ };
15477
+ }
15478
+ function multicastEndpointKey(endpoint) {
15479
+ const normalized = normalizeMulticastEndpoint(endpoint);
15480
+ if (!normalized)
15481
+ throw new Error("Invalid multicast endpoint");
15482
+ return JSON.stringify([
15483
+ normalized.sourceAddress ?? "",
15484
+ normalized.groupAddress,
15485
+ normalized.port,
15486
+ normalized.mode ?? "auto",
15487
+ normalized.amtRelay ?? "",
15488
+ normalized.amtRelayPort ?? ""
15489
+ ]);
15490
+ }
15491
+ function isValidIpv6MulticastAddress(value) {
15492
+ if (!/^[0-9a-f:]+$/.test(value))
15493
+ return false;
15494
+ const compressed = value.includes("::");
15495
+ if (value.indexOf("::") !== value.lastIndexOf("::"))
15496
+ return false;
15497
+ const groups = value.split(":").filter(Boolean);
15498
+ if (groups.length === 0 || groups.length > 8)
15499
+ return false;
15500
+ if (!compressed && groups.length !== 8)
15501
+ return false;
15502
+ return groups.every((group) => /^[0-9a-f]{1,4}$/.test(group));
15503
+ }
15504
+ function isPositivePort(port) {
15505
+ return Number.isInteger(port) && port > 0 && port <= 65535;
15506
+ }
15507
+
15508
+ // node_modules/@blockcast/mmt-transport/dist/multicast-subscription-pool.js
15509
+ var _entries, _gatewayIds, _nextGatewayId, _MulticastSubscriptionPool_instances, createEntry_fn, gatewayId_fn, detach_fn, dispatch_fn;
15510
+ var MulticastSubscriptionPool = class {
15511
+ constructor() {
15512
+ __privateAdd(this, _MulticastSubscriptionPool_instances);
15513
+ __privateAdd(this, _entries, /* @__PURE__ */ new Map());
15514
+ __privateAdd(this, _gatewayIds, /* @__PURE__ */ new WeakMap());
15515
+ __privateAdd(this, _nextGatewayId, 1);
15516
+ }
15517
+ async acquire(gateway, config, consumer) {
15518
+ const endpoint = normalizeMulticastEndpoint({
15519
+ groupAddress: config.group,
15520
+ sourceAddress: config.source,
15521
+ port: config.port,
15522
+ mode: config.mode,
15523
+ amtRelay: config.amtRelay,
15524
+ amtRelayPort: config.amtRelayPort
15525
+ });
15526
+ if (!endpoint)
15527
+ throw new Error("Invalid multicast endpoint");
15528
+ if (typeof gateway.subscribe !== "function")
15529
+ throw new Error("window.multicast.subscribe unavailable");
15530
+ const key = multicastEndpointKey(endpoint);
15531
+ const internalKey = `${__privateMethod(this, _MulticastSubscriptionPool_instances, gatewayId_fn).call(this, gateway)}|${key}`;
15532
+ let record = __privateGet(this, _entries).get(internalKey);
15533
+ if (!record) {
15534
+ record = { claims: 0, entry: Promise.resolve(null) };
15535
+ const createdRecord = record;
15536
+ record.entry = __privateMethod(this, _MulticastSubscriptionPool_instances, createEntry_fn).call(this, gateway, endpoint, (entry2) => {
15537
+ if (__privateGet(this, _entries).get(internalKey) === createdRecord)
15538
+ __privateGet(this, _entries).delete(internalKey);
15539
+ __privateMethod(this, _MulticastSubscriptionPool_instances, detach_fn).call(this, entry2);
15540
+ }).catch((error) => {
15541
+ if (__privateGet(this, _entries).get(internalKey) === createdRecord)
15542
+ __privateGet(this, _entries).delete(internalKey);
15543
+ throw error;
15544
+ });
15545
+ __privateGet(this, _entries).set(internalKey, record);
15546
+ }
15547
+ record.claims++;
15548
+ let entry;
15549
+ try {
15550
+ entry = await record.entry;
15551
+ } catch (error) {
15552
+ record.claims--;
15553
+ throw error;
15554
+ }
15555
+ if (entry.closed) {
15556
+ record.claims--;
15557
+ return this.acquire(gateway, config, consumer);
15558
+ }
15559
+ const token = Symbol(key);
15560
+ entry.consumers.set(token, consumer);
15561
+ let released = false;
15562
+ return {
15563
+ key,
15564
+ release: async () => {
15565
+ if (released)
15566
+ return;
15567
+ released = true;
15568
+ entry.consumers.delete(token);
15569
+ record.claims--;
15570
+ if (record.claims > 0)
15571
+ return;
15572
+ if (__privateGet(this, _entries).get(internalKey) === record)
15573
+ __privateGet(this, _entries).delete(internalKey);
15574
+ __privateMethod(this, _MulticastSubscriptionPool_instances, detach_fn).call(this, entry);
15575
+ if (!entry.closed)
15576
+ await entry.subscription.unsubscribe();
15577
+ }
15578
+ };
15579
+ }
15580
+ get size() {
15581
+ return __privateGet(this, _entries).size;
15582
+ }
15583
+ };
15584
+ _entries = new WeakMap();
15585
+ _gatewayIds = new WeakMap();
15586
+ _nextGatewayId = new WeakMap();
15587
+ _MulticastSubscriptionPool_instances = new WeakSet();
15588
+ createEntry_fn = async function(gateway, endpoint, onClosed) {
15589
+ const subscription = await gateway.subscribe(toWindowMulticastSubscribeConfig({
15590
+ group: endpoint.groupAddress,
15591
+ ...endpoint.sourceAddress ? { source: endpoint.sourceAddress } : {},
15592
+ port: endpoint.port,
15593
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
15594
+ ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
15595
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
15596
+ }));
15597
+ const consumers = /* @__PURE__ */ new Map();
15598
+ let entry;
15599
+ const bytesListener = (event) => {
15600
+ __privateMethod(this, _MulticastSubscriptionPool_instances, dispatch_fn).call(this, consumers, (consumer) => consumer.onBytes(event.detail));
15601
+ };
15602
+ const stateListener = (event) => {
15603
+ __privateMethod(this, _MulticastSubscriptionPool_instances, dispatch_fn).call(this, consumers, (consumer) => consumer.onState?.(event.detail));
15604
+ if (event.detail === "closed" && !entry.closed) {
15605
+ entry.closed = true;
15606
+ onClosed(entry);
15607
+ }
15608
+ };
15609
+ const errorListener = (event) => {
15610
+ const error = event.detail instanceof Error ? event.detail : new Error(String(event.detail));
15611
+ __privateMethod(this, _MulticastSubscriptionPool_instances, dispatch_fn).call(this, consumers, (consumer) => consumer.onError?.(error));
15612
+ };
15613
+ entry = { subscription, consumers, bytesListener, stateListener, errorListener, closed: false };
15614
+ subscription.addEventListener("bytes", bytesListener);
15615
+ subscription.addEventListener("state", stateListener);
15616
+ subscription.addEventListener("error", errorListener);
15617
+ return entry;
15618
+ };
15619
+ gatewayId_fn = function(gateway) {
15620
+ const object = gateway;
15621
+ let id = __privateGet(this, _gatewayIds).get(object);
15622
+ if (!id) {
15623
+ id = __privateWrapper(this, _nextGatewayId)._++;
15624
+ __privateGet(this, _gatewayIds).set(object, id);
15625
+ }
15626
+ return id;
15627
+ };
15628
+ detach_fn = function(entry) {
15629
+ entry.subscription.removeEventListener("bytes", entry.bytesListener);
15630
+ entry.subscription.removeEventListener("state", entry.stateListener);
15631
+ entry.subscription.removeEventListener("error", entry.errorListener);
15632
+ };
15633
+ dispatch_fn = function(consumers, callback) {
15634
+ for (const consumer of consumers.values()) {
15635
+ try {
15636
+ callback(consumer);
15637
+ } catch (error) {
15638
+ console.error("[Transport] multicast consumer callback failed", error);
15639
+ }
15640
+ }
15641
+ };
15642
+ var multicastSubscriptionPool = new MulticastSubscriptionPool();
15643
+
15644
+ // node_modules/@blockcast/mmt-transport/dist/transport-manager.js
15645
+ var TransportManager = class {
15646
+ constructor() {
15647
+ __publicField(this, "state", {
15648
+ mode: "disconnected",
15649
+ connected: false,
15650
+ packetsReceived: 0,
15651
+ bytesReceived: 0,
15652
+ lastPacketTime: 0
15653
+ });
15654
+ __publicField(this, "capabilities", null);
15655
+ __publicField(this, "subscription", null);
15656
+ __publicField(this, "driad", new DRIADDiscovery());
15657
+ __publicField(this, "abr");
15658
+ __publicField(this, "multicastOrchestrator", null);
15659
+ __publicField(this, "onOrchestratorCommand");
15660
+ __publicField(this, "connectionGeneration", 0);
15661
+ __publicField(this, "onPacket");
15662
+ __publicField(this, "onError");
15663
+ __publicField(this, "onStateChange");
15664
+ this.abr = new AdaptiveBitrateController();
15665
+ }
15666
+ getWindow() {
15667
+ return typeof window === "undefined" ? void 0 : window;
15668
+ }
15669
+ getWindowMulticastGateway() {
15670
+ return this.getWindow()?.multicast;
15671
+ }
15672
+ async getGatewayCapabilities(gateway) {
15673
+ if (!gateway?.capabilities)
15674
+ return void 0;
15675
+ try {
15676
+ return typeof gateway.capabilities === "function" ? await gateway.capabilities() : gateway.capabilities;
15677
+ } catch (error) {
15678
+ console.warn("[Transport] window.multicast capabilities failed:", error);
15679
+ return void 0;
15680
+ }
15681
+ }
15682
+ async gatewaySupportsBytes(gateway) {
15683
+ if (typeof gateway?.subscribe !== "function")
15684
+ return false;
15685
+ if (!gateway.capabilities)
15686
+ return true;
15687
+ const capabilities = await this.getGatewayCapabilities(gateway);
15688
+ if (!capabilities)
15689
+ return false;
15690
+ const consumeModes = capabilities.consumeModes;
15691
+ return !consumeModes || consumeModes.includes("bytes");
15692
+ }
15693
+ /**
15694
+ * Detect available transport capabilities
15695
+ */
15696
+ async detectCapabilities() {
15697
+ if (this.capabilities)
15698
+ return this.capabilities;
15699
+ const gateway = this.getWindowMulticastGateway();
15700
+ const hasGatewayBytes = await this.gatewaySupportsBytes(gateway);
15701
+ const win = this.getWindow();
15702
+ this.capabilities = {
15703
+ nativeSSM: hasGatewayBytes,
15704
+ nativeIGMP: hasGatewayBytes,
15705
+ directSockets: typeof win?.UDPSocket !== "undefined",
15706
+ amt: false,
15707
+ driad: true,
15708
+ // DRIAD uses HTTP proxy, always available
15709
+ fecDecode: false
15710
+ };
15711
+ console.log("[Transport] Capabilities:", this.capabilities);
15712
+ return this.capabilities;
15713
+ }
15714
+ /**
15715
+ * Connect using best available transport
15716
+ *
15717
+ * Promotion hierarchy:
15718
+ * 1. window.multicast gateway bytes
15719
+ * 2. AMT proxy (specified or discovered via DRIAD)
15720
+ * 3. MOQ WebTransport (final fallback)
15721
+ */
15722
+ async connect(config) {
15723
+ const generation = ++this.connectionGeneration;
15724
+ this.subscription?.close();
15725
+ this.subscription = null;
15726
+ this.state = {
15727
+ mode: "disconnected",
15728
+ connected: false,
15729
+ packetsReceived: 0,
15730
+ bytesReceived: 0,
15731
+ lastPacketTime: 0
15732
+ };
15733
+ this.onStateChange?.(this.state);
15734
+ const endpoint = normalizeMulticastEndpoint({
15735
+ groupAddress: config.group,
15736
+ sourceAddress: config.source,
15737
+ port: config.port,
15738
+ mode: config.mode,
15739
+ amtRelay: config.amtRelay,
15740
+ amtRelayPort: config.amtRelayPort
15741
+ });
15742
+ if (!endpoint) {
15743
+ const error = new Error("Invalid multicast endpoint configuration");
15744
+ this.onError?.(error);
15745
+ return false;
15746
+ }
15747
+ config = {
15748
+ ...config,
15749
+ group: endpoint.groupAddress,
15750
+ source: endpoint.sourceAddress ?? "",
15751
+ mode: endpoint.mode,
15752
+ amtRelay: endpoint.amtRelay,
15753
+ amtRelayPort: endpoint.amtRelayPort
15754
+ };
15755
+ const caps = await this.detectCapabilities();
15756
+ if (generation !== this.connectionGeneration)
15757
+ return false;
15758
+ if (config.initialQuality) {
15759
+ this.abr = new AdaptiveBitrateController(config.initialQuality);
15760
+ }
15761
+ this.abr.setCallback((quality) => {
15762
+ this.state.quality = quality;
15763
+ this.subscription?.onqualitychange?.(quality);
15764
+ this.onStateChange?.(this.state);
15765
+ });
15766
+ let connected = false;
15767
+ if (caps.nativeSSM || caps.nativeIGMP) {
15768
+ console.log("[Transport] Attempting window.multicast...");
15769
+ connected = await this.connectWindowMulticast(config, generation);
15770
+ if (connected) {
15771
+ if (generation !== this.connectionGeneration)
15772
+ return false;
15773
+ this.state.mode = "multicast";
15774
+ return true;
15775
+ }
15776
+ }
15777
+ if (!connected) {
15778
+ console.log("[Transport] Attempting AMT tunnel...");
15779
+ connected = await this.connectAmt(config, generation);
15780
+ if (connected) {
15781
+ if (generation !== this.connectionGeneration)
15782
+ return false;
15783
+ this.state.mode = "amt";
15784
+ return true;
15785
+ }
15786
+ }
15787
+ console.log("[Transport] All multicast transports failed, falling back to MOQ");
15788
+ return false;
15789
+ }
15790
+ /**
15791
+ * Connect via the lowercase window.multicast bytes gateway.
15792
+ */
15793
+ async connectWindowMulticast(config, generation) {
15794
+ try {
15795
+ const gateway = this.getWindowMulticastGateway();
15796
+ if (typeof gateway?.subscribe !== "function")
15797
+ return false;
15798
+ const lease = await multicastSubscriptionPool.acquire(gateway, config, {
15799
+ onBytes: (data) => {
15800
+ if (generation === this.connectionGeneration)
15801
+ this.handlePacket(data);
15802
+ },
15803
+ onState: (state) => {
15804
+ if (generation !== this.connectionGeneration)
15805
+ return;
15806
+ this.state.connected = state !== "closed";
15807
+ this.onStateChange?.(this.state);
15808
+ },
15809
+ onError: (error) => {
15810
+ if (generation !== this.connectionGeneration)
15811
+ return;
15812
+ console.error("[Transport] window.multicast error:", error);
15813
+ this.onError?.(error);
15814
+ }
15815
+ });
15816
+ if (generation !== this.connectionGeneration) {
15817
+ await lease.release();
15818
+ return false;
15819
+ }
15820
+ this.subscription = {
15821
+ id: lease.key,
15822
+ config,
15823
+ close: () => {
15824
+ void lease.release();
15825
+ }
15826
+ };
15827
+ this.state = {
15828
+ mode: "multicast",
15829
+ connected: true,
15830
+ group: config.group,
15831
+ source: config.source,
15832
+ quality: this.abr.getCurrentQuality(),
15833
+ packetsReceived: 0,
15834
+ bytesReceived: 0,
15835
+ lastPacketTime: 0
15836
+ };
15837
+ console.log(`[Transport] Connected via window.multicast: (${config.source}, ${config.group})`);
15838
+ this.onStateChange?.(this.state);
15839
+ return true;
15840
+ } catch (error) {
15841
+ console.warn("[Transport] window.multicast failed:", error);
15842
+ return false;
15843
+ }
15844
+ }
15845
+ /**
15846
+ * Connect via AMT proxy (with optional DRIAD discovery)
15847
+ */
15848
+ async connectAmt(config, generation) {
15849
+ try {
15850
+ let amtRelay = config.amtRelay;
15851
+ if (!amtRelay && config.driadEnabled !== false && config.source) {
15852
+ console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
15853
+ const relays = await this.driad.discoverRelays(config.source);
15854
+ if (generation !== this.connectionGeneration)
15855
+ return false;
15856
+ const bestRelay = await this.driad.selectBestRelay(relays);
15857
+ if (generation !== this.connectionGeneration)
15858
+ return false;
15859
+ if (bestRelay) {
15860
+ amtRelay = bestRelay.host;
15861
+ this.state.amtRelay = amtRelay;
15862
+ }
15863
+ }
15864
+ if (!amtRelay) {
15865
+ console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
15866
+ return false;
15867
+ }
15868
+ return await this.connectAmtProxy(config, amtRelay, generation);
15869
+ } catch (error) {
15870
+ console.warn("[Transport] AMT connection failed:", error);
15871
+ return false;
15872
+ }
15873
+ }
15874
+ /**
15875
+ * Connect via WebSocket-based AMT proxy (browser fallback)
15876
+ */
15877
+ async connectAmtProxy(config, amtRelay, generation) {
15878
+ try {
15879
+ const relayHost = amtRelay.includes(":") && !amtRelay.startsWith("[") ? `[${amtRelay}]` : amtRelay;
15880
+ const relayAuthority = config.amtRelayPort ? `${relayHost}:${config.amtRelayPort}` : relayHost;
15881
+ const wsUrl = new URL(`wss://${relayAuthority}/amt-proxy`);
15882
+ wsUrl.searchParams.set("group", config.group);
15883
+ wsUrl.searchParams.set("source", config.source || "");
15884
+ wsUrl.searchParams.set("port", String(config.port));
15885
+ const ws = new WebSocket(wsUrl);
15886
+ return new Promise((resolve, reject) => {
15887
+ ws.binaryType = "arraybuffer";
15888
+ const timeout = setTimeout(() => {
15889
+ ws.close();
15890
+ reject(new Error("AMT proxy connection timeout"));
15891
+ }, 1e4);
15892
+ ws.onopen = () => {
15893
+ clearTimeout(timeout);
15894
+ if (generation !== this.connectionGeneration) {
15895
+ ws.close();
15896
+ resolve(false);
15897
+ return;
15898
+ }
15899
+ console.log(`[Transport] Connected to AMT proxy: ${amtRelay}`);
15900
+ this.subscription = {
15901
+ id: `amt-proxy-${Date.now()}`,
15902
+ config,
15903
+ close: () => ws.close()
15904
+ };
15905
+ this.state = {
15906
+ mode: "amt",
15907
+ connected: true,
15908
+ group: config.group,
15909
+ source: config.source,
15910
+ amtRelay,
15911
+ quality: this.abr.getCurrentQuality(),
15912
+ packetsReceived: 0,
15913
+ bytesReceived: 0,
15914
+ lastPacketTime: 0
15915
+ };
15916
+ this.onStateChange?.(this.state);
15917
+ resolve(true);
15918
+ };
15919
+ ws.onmessage = (event) => {
15920
+ if (generation === this.connectionGeneration && event.data instanceof ArrayBuffer) {
15921
+ this.handlePacket(event.data);
15922
+ }
15923
+ };
15924
+ ws.onerror = (error) => {
15925
+ clearTimeout(timeout);
15926
+ if (generation !== this.connectionGeneration) {
15927
+ resolve(false);
15928
+ return;
15929
+ }
15930
+ console.error("[Transport] AMT proxy error:", error);
15931
+ reject(error);
15932
+ };
15933
+ ws.onclose = () => {
15934
+ clearTimeout(timeout);
15935
+ if (generation !== this.connectionGeneration) {
15936
+ resolve(false);
15937
+ return;
15938
+ }
15939
+ this.state.connected = false;
15940
+ this.onStateChange?.(this.state);
15941
+ resolve(false);
15942
+ };
15943
+ });
15944
+ } catch (error) {
15945
+ console.warn("[Transport] AMT proxy failed:", error);
15946
+ return false;
15947
+ }
15948
+ }
15949
+ /**
15950
+ * Handle received packet
15951
+ */
15952
+ handlePacket(data) {
15953
+ this.state.packetsReceived++;
15954
+ this.state.bytesReceived += data.byteLength;
15955
+ this.state.lastPacketTime = Date.now();
15956
+ this.abr.recordSample(data.byteLength, 0);
15957
+ this.onPacket?.(data);
15958
+ }
15959
+ /**
15960
+ * Get current transport state
15961
+ */
15962
+ getState() {
15963
+ return { ...this.state };
15964
+ }
15965
+ /**
15966
+ * Get current quality level
15967
+ */
15968
+ getQuality() {
15969
+ return this.abr.getCurrentQuality();
15970
+ }
15971
+ /**
15972
+ * Force quality level
15973
+ */
15974
+ setQuality(name) {
15975
+ this.abr.setQuality(name);
15976
+ }
15977
+ /** Configures multicast-only ABR while leaving the caller's MoQ ABR untouched. */
15978
+ configureMulticastTiers(options, onCommand) {
15979
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
15980
+ this.multicastOrchestrator = new MulticastOrchestrator(options);
15981
+ this.onOrchestratorCommand = onCommand;
15982
+ return this.multicastOrchestrator.start();
15983
+ }
15984
+ recordMulticastGoodput(bitrate) {
15985
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onGoodput({ bitrate }));
15986
+ }
15987
+ recordMulticastHeadroom(healthy) {
15988
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onHeadroom({ healthy }));
15989
+ }
15990
+ recordMulticastTierPacket(packet) {
15991
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onTierPacket(packet));
15992
+ }
15993
+ pollMulticastTierSwitch() {
15994
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.poll());
15995
+ }
15996
+ /**
15997
+ * Set packet callback
15998
+ */
15999
+ setPacketCallback(callback) {
16000
+ this.onPacket = callback;
16001
+ }
16002
+ /**
16003
+ * Set error callback
16004
+ */
16005
+ setErrorCallback(callback) {
16006
+ this.onError = callback;
16007
+ }
16008
+ /**
16009
+ * Set state change callback
16010
+ */
16011
+ setStateCallback(callback) {
16012
+ this.onStateChange = callback;
16013
+ }
16014
+ /**
16015
+ * Disconnect
16016
+ */
16017
+ disconnect() {
16018
+ this.connectionGeneration++;
16019
+ this.subscription?.close();
16020
+ this.subscription = null;
16021
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
16022
+ this.multicastOrchestrator = null;
16023
+ this.onOrchestratorCommand = void 0;
16024
+ this.state = {
16025
+ mode: "disconnected",
16026
+ connected: false,
16027
+ packetsReceived: 0,
16028
+ bytesReceived: 0,
16029
+ lastPacketTime: 0
16030
+ };
16031
+ this.onStateChange?.(this.state);
16032
+ }
16033
+ dispatchOrchestratorCommand(command) {
16034
+ if (command)
16035
+ this.onOrchestratorCommand?.(command);
16036
+ return command;
16037
+ }
16038
+ };
16039
+ var transportManager = new TransportManager();
16040
+
16041
+ // node_modules/@blockcast/mmt-transport/dist/moqt-priority.js
16042
+ var MAX_MOQT_PRIORITY = 255;
16043
+ function moqtPriority(value, field) {
16044
+ if (!Number.isInteger(value) || value < 0 || value > MAX_MOQT_PRIORITY) {
16045
+ throw new RangeError(`${field} must be an integer in [0, ${MAX_MOQT_PRIORITY}], got ${value}`);
16046
+ }
16047
+ return value;
16048
+ }
16049
+ function moqtSubscriberPriority(value) {
16050
+ return moqtPriority(value, "MOQT subscriber priority");
16051
+ }
16052
+ function moqtPublisherPriority(value) {
16053
+ return moqtPriority(value, "MOQT publisher priority");
16054
+ }
16055
+ var MOQT_SUBSCRIBER_PRIORITY = Object.freeze({
16056
+ catalog: moqtSubscriberPriority(0),
16057
+ deadlineRepair: moqtSubscriberPriority(0),
16058
+ audio: moqtSubscriberPriority(1),
16059
+ video: moqtSubscriberPriority(2),
16060
+ backgroundRepair: moqtSubscriberPriority(3)
16061
+ });
16062
+ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
16063
+ catalog: moqtPublisherPriority(32),
16064
+ source: moqtPublisherPriority(128),
16065
+ repair: moqtPublisherPriority(240)
16066
+ });
16067
+
16068
+ // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
16069
+ var DEFAULT_AMT_PORT = 2268;
16070
+ var AMTGatewayManager = class {
16071
+ constructor() {
16072
+ __publicField(this, "subscriptions", /* @__PURE__ */ new Map());
16073
+ __publicField(this, "messageHandler");
16074
+ __publicField(this, "pendingPackets", /* @__PURE__ */ new Map());
16075
+ __publicField(this, "driad", new DRIADDiscovery());
16076
+ this.messageHandler = (event) => {
16077
+ const data = event.data;
16078
+ console.log(`[AMT] SW message received:`, data.type);
16079
+ if (data.type === "UDP_PACKET") {
16080
+ this.handlePacket(data);
16081
+ } else if (data.type === "SOCKET_ERROR") {
16082
+ this.handleSocketError(data);
16083
+ } else if (data.type === "DEBUG_LOG") {
16084
+ console.log(`[AMT SW Debug] ${data.message}`);
16085
+ }
16086
+ };
16087
+ if (typeof navigator !== "undefined" && navigator.serviceWorker) {
16088
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
16089
+ console.log("[AMT] Registered service worker message handler");
16090
+ } else {
16091
+ console.warn("[AMT] Service worker not available");
16092
+ }
16093
+ }
16094
+ /**
16095
+ * Subscribe via AMT tunnel
16096
+ */
16097
+ async subscribe(config) {
16098
+ const { key } = config;
16099
+ const keyStr = this.getKeyString(key);
16100
+ if (this.subscriptions.has(keyStr)) {
16101
+ console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
16102
+ return keyStr;
16103
+ }
16104
+ try {
16105
+ let relayAddress;
16106
+ let discoveryMethod;
16107
+ const relayPort = config.relayPort || DEFAULT_AMT_PORT;
16108
+ if (config.relayAddress) {
16109
+ relayAddress = config.relayAddress;
16110
+ discoveryMethod = "manual";
16111
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16112
+ } else if (key.source) {
16113
+ console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
16114
+ const relays = await this.driad.discoverRelays(key.source);
16115
+ const bestRelay = await this.driad.selectBestRelay(relays);
16116
+ if (!bestRelay) {
16117
+ throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
16118
+ }
16119
+ relayAddress = bestRelay.host;
16120
+ discoveryMethod = "driad";
16121
+ console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
16122
+ } else {
16123
+ throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
16124
+ }
16125
+ const subscriptionId = keyStr;
16126
+ this.pendingPackets.set(subscriptionId, []);
16127
+ const subscription = {
16128
+ key,
16129
+ subscriptionId,
16130
+ config,
16131
+ handshakeComplete: false,
16132
+ relay: {
16133
+ address: relayAddress,
16134
+ port: relayPort,
16135
+ discoveryMethod,
16136
+ discoveredAt: Date.now()
16137
+ }
16138
+ };
16139
+ this.subscriptions.set(keyStr, subscription);
16140
+ console.log(`[AMT] Subscription created for ${keyStr} via ${relayAddress}:${relayPort}`);
16141
+ return keyStr;
16142
+ } catch (error) {
16143
+ const subscription = this.subscriptions.get(keyStr);
16144
+ if (subscription) {
16145
+ this.subscriptions.delete(keyStr);
16146
+ this.pendingPackets.delete(subscription.subscriptionId);
16147
+ }
16148
+ throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
16149
+ }
16150
+ }
16151
+ /**
16152
+ * Unsubscribe from AMT tunnel
16153
+ */
16154
+ async unsubscribe(handle) {
16155
+ const subscription = this.subscriptions.get(handle);
16156
+ if (!subscription) {
16157
+ throw new Error(`Subscription ${handle} not found`);
16158
+ }
16159
+ try {
16160
+ if (subscription.keepAliveTimer) {
16161
+ clearInterval(subscription.keepAliveTimer);
16162
+ }
16163
+ console.log(`[AMT] Unsubscribed from ${handle}`);
16164
+ } catch (error) {
16165
+ console.error("[AMT] Error during unsubscribe:", error);
16166
+ } finally {
16167
+ this.subscriptions.delete(handle);
16168
+ this.pendingPackets.delete(subscription.subscriptionId);
16169
+ }
16170
+ }
16171
+ /**
16172
+ * Get list of active subscriptions
16173
+ */
16174
+ getSubscriptions() {
16175
+ return Array.from(this.subscriptions.keys());
16176
+ }
16177
+ /**
16178
+ * Handle packet from service worker
16179
+ */
16180
+ handlePacket(message) {
16181
+ const { subscriptionId, data } = message;
16182
+ if (!subscriptionId)
16183
+ return;
16184
+ const subscription = this.subscriptions.get(subscriptionId);
16185
+ if (!subscription) {
16186
+ console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
16187
+ return;
16188
+ }
16189
+ if (!subscription.handshakeComplete) {
16190
+ const queue = this.pendingPackets.get(subscriptionId);
16191
+ const packetData2 = data;
16192
+ if (queue) {
16193
+ queue.push({
16194
+ data: packetData2.data,
16195
+ remoteAddress: packetData2.remoteAddress,
16196
+ remotePort: packetData2.remotePort
16197
+ });
16198
+ }
16199
+ return;
16200
+ }
16201
+ const packetData = data;
16202
+ const metadata = {
16203
+ sourceAddress: subscription.relay?.address || "unknown",
16204
+ sourcePort: subscription.relay?.port || 0,
16205
+ transport: "tunnel",
16206
+ timestamp: performance.now()
16207
+ };
16208
+ subscription.config.onPacket(packetData.data, metadata);
16209
+ }
16210
+ /**
16211
+ * Handle socket error from service worker
16212
+ */
16213
+ handleSocketError(message) {
16214
+ const { subscriptionId, error } = message;
16215
+ if (!subscriptionId)
16216
+ return;
16217
+ const subscription = this.subscriptions.get(subscriptionId);
16218
+ if (!subscription) {
16219
+ console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
16220
+ return;
16221
+ }
16222
+ subscription.config.onError(new Error(error || "Unknown error"));
16223
+ }
16224
+ /**
16225
+ * Cleanup on destroy
16226
+ */
16227
+ destroy() {
16228
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
16229
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
16230
+ }
16231
+ const handles = Array.from(this.subscriptions.keys());
16232
+ for (const handle of handles) {
16233
+ this.unsubscribe(handle).catch((err) => {
16234
+ console.error(`[AMT] Error unsubscribing ${handle}:`, err);
16235
+ });
16236
+ }
16237
+ }
16238
+ /**
16239
+ * Get key string for HashMap
16240
+ */
16241
+ getKeyString(key) {
16242
+ const source = key.source ? `@${key.source}` : "";
16243
+ return `${key.group}:${key.port}${source}`;
16244
+ }
16245
+ };
16246
+ var amtGatewayManager = new AMTGatewayManager();
16247
+
16248
+ // src/multicast-transport.ts
16249
+ var MAX_TRACKED_DROPPED_PIDS = 16;
16250
+ function getMulticastGlobals() {
16251
+ return globalThis;
16252
+ }
16253
+ function hasMulticastGateway() {
16254
+ return typeof getMulticastGlobals().multicast?.subscribe === "function";
16255
+ }
16256
+ var _onPacket, _subscription2, _bytesListener, _resolvedTransport, _videoConfirmed, _audioConfirmed, _watchdog, _failbackWindowMs, _onTakeover, _onFailback, _disposed4, _stats3, _droppedPidCounts, _packetIds, _joinGeneration, _MulticastTransport_instances, releaseSubscription_fn, acceptPacket_fn, recordUnregisteredPidDrop_fn, checkTakeover_fn, resetWatchdog_fn;
16257
+ var _MulticastTransport = class _MulticastTransport {
16258
+ constructor(onPacket) {
16259
+ __privateAdd(this, _MulticastTransport_instances);
16260
+ __privateAdd(this, _onPacket);
16261
+ __privateAdd(this, _subscription2, null);
16262
+ __privateAdd(this, _bytesListener, null);
16263
+ __privateAdd(this, _resolvedTransport);
16264
+ __privateAdd(this, _videoConfirmed, false);
16265
+ __privateAdd(this, _audioConfirmed, false);
16266
+ __privateAdd(this, _watchdog, null);
16267
+ __privateAdd(this, _failbackWindowMs, null);
16268
+ __privateAdd(this, _onTakeover, null);
16269
+ __privateAdd(this, _onFailback, null);
16270
+ __privateAdd(this, _disposed4, false);
16271
+ __privateAdd(this, _stats3, {
16272
+ packetsReceived: 0,
16273
+ bytesReceived: 0,
16274
+ packetsDroppedUnregisteredPid: 0,
16275
+ packetsDroppedUnparseable: 0
16276
+ });
16277
+ __privateAdd(this, _droppedPidCounts, /* @__PURE__ */ new Map());
16278
+ __privateAdd(this, _packetIds, null);
16279
+ __privateAdd(this, _joinGeneration, 0);
16280
+ __privateSet(this, _onPacket, onPacket);
16281
+ }
16282
+ static isAvailable() {
16283
+ return hasMulticastGateway();
16284
+ }
16285
+ async join(config, context) {
16286
+ const generation = ++__privateWrapper(this, _joinGeneration)._;
16287
+ __privateMethod(this, _MulticastTransport_instances, releaseSubscription_fn).call(this);
16288
+ if (__privateGet(this, _disposed4)) return false;
16289
+ if (!_MulticastTransport.isAvailable()) {
16290
+ console.warn("[MulticastTransport] Multicast API not available");
16291
+ return false;
16292
+ }
16293
+ try {
16294
+ const packetIds = config.packetIds?.length ? new Set(config.packetIds) : null;
16295
+ console.log(
16296
+ `[MulticastTransport] window.multicast.subscribe(${config.sourceAddress}, ${config.groupAddress}, ${config.port})`
16297
+ );
16298
+ const subscribeConfig = toWindowMulticastSubscribeConfig({
16299
+ source: config.sourceAddress,
16300
+ group: config.groupAddress,
16301
+ port: config.port,
16302
+ mode: config.mode,
16303
+ amtRelay: config.amtRelay,
16304
+ amtRelayPort: config.amtRelayPort,
16305
+ packetIds: config.packetIds,
16306
+ tracks: config.tracks
16307
+ });
16308
+ const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
16309
+ console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
16310
+ if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) {
16311
+ void subscription.unsubscribe();
16312
+ return false;
16313
+ }
16314
+ if (typeof subscription.addEventListener !== "function") {
16315
+ if (typeof subscription.unsubscribe === "function") {
16316
+ void subscription.unsubscribe();
16317
+ }
16318
+ throw new Error("window.multicast subscription does not support bytes events");
16319
+ }
16320
+ const onBytes = (event) => {
16321
+ if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return;
16322
+ const detail = event.detail;
16323
+ const packet = detail instanceof Uint8Array ? detail : new Uint8Array(detail);
16324
+ if (!__privateMethod(this, _MulticastTransport_instances, acceptPacket_fn).call(this, packet)) return;
16325
+ __privateGet(this, _stats3).packetsReceived++;
16326
+ __privateGet(this, _stats3).bytesReceived += packet.byteLength;
16327
+ __privateGet(this, _onPacket).call(this, packet, context);
16328
+ __privateMethod(this, _MulticastTransport_instances, resetWatchdog_fn).call(this);
16329
+ };
16330
+ __privateSet(this, _subscription2, subscription);
16331
+ __privateSet(this, _bytesListener, onBytes);
16332
+ __privateSet(this, _packetIds, packetIds);
16333
+ __privateSet(this, _resolvedTransport, subscribeConfig.origin === "amt" ? "amt" : "native");
16334
+ subscription.addEventListener("bytes", onBytes);
16335
+ __privateMethod(this, _MulticastTransport_instances, resetWatchdog_fn).call(this);
16336
+ console.log(
16337
+ `[MulticastTransport] Joined ${config.groupAddress}:${config.port}`
16338
+ );
16339
+ return true;
16340
+ } catch (err) {
16341
+ if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return false;
16342
+ __privateMethod(this, _MulticastTransport_instances, releaseSubscription_fn).call(this);
16343
+ console.error("[MulticastTransport] Failed to join SSM group:", err);
16344
+ return false;
14600
16345
  }
14601
16346
  }
14602
16347
  /** Feed a raw packet from an external source (e.g., AMT tunnel or ASM subscription). */
@@ -14654,7 +16399,6 @@ var _MulticastTransport = class _MulticastTransport {
14654
16399
  _onPacket = new WeakMap();
14655
16400
  _subscription2 = new WeakMap();
14656
16401
  _bytesListener = new WeakMap();
14657
- _transportListener = new WeakMap();
14658
16402
  _resolvedTransport = new WeakMap();
14659
16403
  _videoConfirmed = new WeakMap();
14660
16404
  _audioConfirmed = new WeakMap();
@@ -14675,14 +16419,10 @@ releaseSubscription_fn = function() {
14675
16419
  if (__privateGet(this, _bytesListener)) {
14676
16420
  __privateGet(this, _subscription2).removeEventListener("bytes", __privateGet(this, _bytesListener));
14677
16421
  }
14678
- if (__privateGet(this, _transportListener)) {
14679
- __privateGet(this, _subscription2).removeEventListener("transportchange", __privateGet(this, _transportListener));
14680
- }
14681
16422
  void __privateGet(this, _subscription2).unsubscribe();
14682
16423
  }
14683
16424
  __privateSet(this, _subscription2, null);
14684
16425
  __privateSet(this, _bytesListener, null);
14685
- __privateSet(this, _transportListener, null);
14686
16426
  __privateSet(this, _resolvedTransport, void 0);
14687
16427
  __privateSet(this, _packetIds, null);
14688
16428
  };
@@ -16658,7 +18398,7 @@ _readIndex = new WeakMap();
16658
18398
  _stalled = new WeakMap();
16659
18399
 
16660
18400
  // src/mmtp-decode-pipeline.ts
16661
- var _parser2, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _gateDropped, _gateEmitted, _fedObjects, _warnedNoParser, _feedOutcomes, _MmtpDecodePipeline_instances, gatedEmit_fn;
18401
+ var _parser2, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _trackType, _gateDropped, _gateEmitted, _fedObjects, _warnedNoParser, _feedOutcomes, _MmtpDecodePipeline_instances, tag_fn, gatedEmit_fn;
16662
18402
  var MmtpDecodePipeline = class {
16663
18403
  constructor() {
16664
18404
  __privateAdd(this, _MmtpDecodePipeline_instances);
@@ -16667,7 +18407,11 @@ var MmtpDecodePipeline = class {
16667
18407
  __privateAdd(this, _frameCb2, null);
16668
18408
  __privateAdd(this, _initCb2, null);
16669
18409
  __privateAdd(this, _needsKeyframe, false);
16670
- __privateAdd(this, _codec, "");
18410
+ __privateAdd(this, _codec, null);
18411
+ /** Set together with #codec at configure(). Also the diagnostic label: a
18412
+ * player builds one pipeline per track, and codec alone does not say which
18413
+ * role a line belongs to at a glance. */
18414
+ __privateAdd(this, _trackType, null);
16671
18415
  /** Diagnostic counters. The keyframe gate drops silently, so a parser that
16672
18416
  * never marks a frame as a keyframe stalls the whole pipeline with no
16673
18417
  * output anywhere: frames are fed, frames are parsed, and nothing is
@@ -16696,6 +18440,7 @@ var MmtpDecodePipeline = class {
16696
18440
  __privateSet(this, _warnedNoParser, false);
16697
18441
  __privateSet(this, _codec, config.codec);
16698
18442
  const trackType = isVideoCodec(config.codec) ? "video" : "audio";
18443
+ __privateSet(this, _trackType, trackType);
16699
18444
  const trackInfo = {
16700
18445
  type: trackType,
16701
18446
  codec: config.codec,
@@ -16739,6 +18484,24 @@ var MmtpDecodePipeline = class {
16739
18484
  get reorderStats() {
16740
18485
  return __privateGet(this, _parser2)?.reorderStats ?? null;
16741
18486
  }
18487
+ /**
18488
+ * Feed tallies for this track. A fresh snapshot per call, not a live view.
18489
+ *
18490
+ * Unlike reorderStats this never returns null: the counters belong to the
18491
+ * pipeline rather than the parser, so they survive dispose(). That is
18492
+ * deliberate — a wedged pipeline is usually read after teardown, which is
18493
+ * exactly when the parser is already gone.
18494
+ */
18495
+ get feedStats() {
18496
+ return {
18497
+ trackType: __privateGet(this, _trackType),
18498
+ codec: __privateGet(this, _codec),
18499
+ fedObjects: __privateGet(this, _fedObjects),
18500
+ emitted: __privateGet(this, _gateEmitted),
18501
+ gateDropped: __privateGet(this, _gateDropped),
18502
+ outcomes: Object.fromEntries(__privateGet(this, _feedOutcomes))
18503
+ };
18504
+ }
16742
18505
  /**
16743
18506
  * Feed a raw MoQ object payload (one MMTP packet per MoQ object).
16744
18507
  * Optionally feeds source symbols to FEC client before parsing.
@@ -16747,33 +18510,37 @@ var MmtpDecodePipeline = class {
16747
18510
  if (!__privateGet(this, _parser2)) {
16748
18511
  if (!__privateGet(this, _warnedNoParser)) {
16749
18512
  __privateSet(this, _warnedNoParser, true);
16750
- console.warn("[mmtp-pipeline] feedMoqObject called with NO PARSER configured \u2014 packet dropped");
18513
+ console.warn(`[mmtp-pipeline] feedMoqObject called with NO PARSER configured ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} \u2014 packet dropped`);
16751
18514
  }
16752
18515
  return;
16753
18516
  }
16754
18517
  __privateSet(this, _fedObjects, __privateGet(this, _fedObjects) + 1);
16755
18518
  if (__privateGet(this, _fedObjects) === 1) {
16756
- console.log(`[mmtp-pipeline] first object fed codec=${__privateGet(this, _codec)} bytes=${packet.length}`);
18519
+ console.log(`[mmtp-pipeline] first object fed ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${packet.length}`);
16757
18520
  }
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);
18521
+ let outcomeKind = "threw";
18522
+ try {
18523
+ if (__privateGet(this, _fecClient)?.addSourceSymbol) {
18524
+ const info = __privateGet(this, _parser2).parseHeader(packet);
18525
+ if (info?.fecPayloadId) {
18526
+ __privateGet(this, _fecClient).addSourceSymbol(info.fecPayloadId.ssId, packet);
18527
+ }
18528
+ }
18529
+ const record = __privateGet(this, _parser2).feed(packet);
18530
+ outcomeKind = record?.kind ?? "null(parse-or-extract-failed)";
18531
+ } finally {
18532
+ const seen = (__privateGet(this, _feedOutcomes).get(outcomeKind) ?? 0) + 1;
18533
+ __privateGet(this, _feedOutcomes).set(outcomeKind, seen);
18534
+ if (seen === 1) {
18535
+ console.log(
18536
+ `[mmtp-pipeline] feed outcome FIRST '${outcomeKind}' ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} at object #${__privateGet(this, _fedObjects)} bytes=${packet.length}`
18537
+ );
16762
18538
  }
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
18539
  }
16773
18540
  if (__privateGet(this, _fedObjects) % 200 === 0) {
16774
18541
  const hist = [...__privateGet(this, _feedOutcomes)].map(([k, v]) => `${k}=${v}`).join(" ");
16775
18542
  console.log(
16776
- `[mmtp-pipeline] feed histogram @${__privateGet(this, _fedObjects)}: ${hist} | emitted=${__privateGet(this, _gateEmitted)} gateDropped=${__privateGet(this, _gateDropped)}`
18543
+ `[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
18544
  );
16778
18545
  }
16779
18546
  }
@@ -16793,7 +18560,10 @@ var MmtpDecodePipeline = class {
16793
18560
  ...meta.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: meta.mmtpTimestamp },
16794
18561
  keyframe: meta.keyframe,
16795
18562
  packetId: meta.packetId,
16796
- trackType: isVideoCodec(__privateGet(this, _codec)) ? "video" : "audio",
18563
+ // Same derivation as configure(), read from the field it set rather than
18564
+ // recomputed. Pre-configure the parser is null and routeFrame below is a
18565
+ // no-op, so the fallback is unreachable in practice.
18566
+ trackType: __privateGet(this, _trackType) ?? "audio",
16797
18567
  packetSequenceNumber: meta.packetSequenceNumber
16798
18568
  };
16799
18569
  if (meta.sourceDiscontinuity) frameMeta.sourceDiscontinuity = true;
@@ -16819,7 +18589,7 @@ var MmtpDecodePipeline = class {
16819
18589
  const droppedFrames = (__privateGet(this, _parser2)?.reorderStats.droppedOnLiveDispose ?? droppedBefore) - droppedBefore;
16820
18590
  if (droppedFrames > 0) {
16821
18591
  console.warn(
16822
- `[MmtpDecodePipeline] live dispose dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
18592
+ `[MmtpDecodePipeline] live dispose ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
16823
18593
  );
16824
18594
  }
16825
18595
  __privateSet(this, _parser2, null);
@@ -16834,12 +18604,19 @@ _frameCb2 = new WeakMap();
16834
18604
  _initCb2 = new WeakMap();
16835
18605
  _needsKeyframe = new WeakMap();
16836
18606
  _codec = new WeakMap();
18607
+ _trackType = new WeakMap();
16837
18608
  _gateDropped = new WeakMap();
16838
18609
  _gateEmitted = new WeakMap();
16839
18610
  _fedObjects = new WeakMap();
16840
18611
  _warnedNoParser = new WeakMap();
16841
18612
  _feedOutcomes = new WeakMap();
16842
18613
  _MmtpDecodePipeline_instances = new WeakSet();
18614
+ /** Identity prefix for diagnostics: one pipeline per track means two
18615
+ * instances write to the same console, and unlabelled lines interleave into
18616
+ * a single unreadable stream. */
18617
+ tag_fn = function() {
18618
+ return `track=${__privateGet(this, _trackType) ?? "unconfigured"} codec=${__privateGet(this, _codec) ?? "none"}`;
18619
+ };
16843
18620
  gatedEmit_fn = function(data, meta) {
16844
18621
  var _a;
16845
18622
  let sourceDiscontinuity = false;
@@ -16848,7 +18625,7 @@ gatedEmit_fn = function(data, meta) {
16848
18625
  __privateSet(this, _gateDropped, __privateGet(this, _gateDropped) + 1);
16849
18626
  if (__privateGet(this, _gateDropped) <= 3 || __privateGet(this, _gateDropped) % 200 === 0) {
16850
18627
  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)}`
18628
+ `[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
18629
  );
16853
18630
  }
16854
18631
  return;
@@ -16856,12 +18633,12 @@ gatedEmit_fn = function(data, meta) {
16856
18633
  __privateSet(this, _needsKeyframe, false);
16857
18634
  sourceDiscontinuity = true;
16858
18635
  console.log(
16859
- `[mmtp-pipeline] keyframe gate OPENED codec=${__privateGet(this, _codec)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects)}`
18636
+ `[mmtp-pipeline] keyframe gate OPENED ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects)}`
16860
18637
  );
16861
18638
  }
16862
18639
  __privateSet(this, _gateEmitted, __privateGet(this, _gateEmitted) + 1);
16863
18640
  if (__privateGet(this, _gateEmitted) === 1) {
16864
- console.log(`[mmtp-pipeline] first frame emitted codec=${__privateGet(this, _codec)} bytes=${data.length}`);
18641
+ console.log(`[mmtp-pipeline] first frame emitted ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length}`);
16865
18642
  }
16866
18643
  const outMeta = sourceDiscontinuity ? { ...meta, sourceDiscontinuity: true } : meta;
16867
18644
  (_a = __privateGet(this, _frameCb2)) == null ? void 0 : _a.call(this, data, outMeta);
@@ -17535,12 +19312,140 @@ emit_fn = function(params) {
17535
19312
  };
17536
19313
 
17537
19314
  // src/catalog-fec-params.ts
19315
+ var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
19316
+ function timescaleHz(value) {
19317
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
19318
+ }
19319
+ function catalogGroupDurationMs(rendition) {
19320
+ if (!rendition) return void 0;
19321
+ const ticks = numericField(rendition.groupDurationTicks);
19322
+ const ms = numericField(rendition.groupDurationMs);
19323
+ const timescale = timescaleHz(rendition.container?.kind === "mmtp" ? rendition.container.timescale : void 0) ?? timescaleHz(rendition.timescale);
19324
+ if (ticks !== void 0 && timescale !== void 0 && Number.isSafeInteger(ticks) && ticks <= timescale * MAX_SAFE_TICKS_PER_HZ) {
19325
+ return resolveGroupDurationMs({ groupDurationTicks: ticks }, timescale);
19326
+ }
19327
+ return ms;
19328
+ }
19329
+ function resolveCatalogTrackGroupDurationMs(catalog, track) {
19330
+ const renditions = track.type === "audio" ? catalog?.audio?.renditions : catalog?.video?.renditions;
19331
+ return catalogGroupDurationMs(renditions?.[track.name]);
19332
+ }
17538
19333
  var NO_FEC = {
17539
19334
  fecK: 0,
17540
19335
  fecRepairCount: 0,
19336
+ fecTotalRepairCount: 0,
17541
19337
  fecSymbolSize: 0,
17542
19338
  fecInterleaveMs: 0
17543
19339
  };
19340
+ function recordOf(value) {
19341
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
19342
+ }
19343
+ function msfTracks(catalog) {
19344
+ const raw = catalog.tracks;
19345
+ if (!Array.isArray(raw)) return void 0;
19346
+ const common = recordOf(catalog.commonTrackFields) ?? {};
19347
+ return { tracks: raw.map((t) => recordOf(t) ?? {}), common };
19348
+ }
19349
+ function resolveRepairLayers(catalog, source) {
19350
+ if (!catalog) return void 0;
19351
+ const sourceName = typeof source === "string" ? source : source.name;
19352
+ const hang = catalog;
19353
+ const roles = typeof source === "string" ? ["video", "audio"] : source.type === "audio" ? ["audio"] : source.type === "video" ? ["video"] : ["video", "audio"];
19354
+ const role = roles.find((r) => recordOf(hang[r]?.renditions?.[sourceName]) !== void 0);
19355
+ if (role !== void 0) {
19356
+ const renditionPath = `$.${role}.renditions[${JSON.stringify(sourceName)}]`;
19357
+ const rendition = recordOf(hang[role].renditions[sourceName]);
19358
+ rejectRepairFieldsOnMediaTrack(renditionPath, rendition, throwRepairContractError);
19359
+ const repairRenditions = recordOf(hang.repair?.renditions) ?? {};
19360
+ const descriptors2 = Object.entries(repairRenditions).map(([name, entry]) => {
19361
+ const path = `$.repair.renditions[${JSON.stringify(name)}]`;
19362
+ const fields = recordOf(entry);
19363
+ if (fields === void 0) {
19364
+ throwRepairContractError("track_repair_layer", path, "a repair rendition must be an object");
19365
+ }
19366
+ rejectRepairTrackGeometry(path, fields, throwRepairContractError);
19367
+ return describeRepairTrack(name, path, fields);
19368
+ });
19369
+ const fecOfRendition = (entry) => {
19370
+ const fec2 = recordOf(recordOf(entry)?.["fec"]);
19371
+ return fec2 !== void 0 && fec2["algorithm"] !== "none" ? fec2 : void 0;
19372
+ };
19373
+ const mediaRenditions = [
19374
+ ...Object.values(recordOf(hang.video?.renditions) ?? {}),
19375
+ ...Object.values(recordOf(hang.audio?.renditions) ?? {})
19376
+ ];
19377
+ const reachability2 = repairReachability(mediaRenditions.map((entry) => recordOf(entry)?.["fec"]));
19378
+ for (const d of descriptors2) {
19379
+ validateRepairTrackFields(d, throwRepairContractError);
19380
+ assertRepairTrackReachable(d, reachability2, throwRepairContractError);
19381
+ const target = dependsTarget(d);
19382
+ if (target === void 0) continue;
19383
+ const targetFec = fecOfRendition(hang.video?.renditions?.[target]) ?? fecOfRendition(hang.audio?.renditions?.[target]);
19384
+ if (targetFec === void 0) {
19385
+ throwRepairContractError(
19386
+ "track_repair_depends",
19387
+ `${d.path}.depends`,
19388
+ `${JSON.stringify(target)} is not a video or audio rendition with FEC`
19389
+ );
19390
+ }
19391
+ }
19392
+ return assembleRepairLayers(
19393
+ geometryOf(sourceName, `${renditionPath}.fec`, recordOf(rendition["fec"])),
19394
+ descriptors2,
19395
+ throwRepairContractError
19396
+ );
19397
+ }
19398
+ const msf = msfTracks(catalog);
19399
+ const msfIndex = msf ? msf.tracks.findIndex((t) => t["name"] === sourceName) : -1;
19400
+ if (!msf || msfIndex < 0) return void 0;
19401
+ const track = msf.tracks[msfIndex];
19402
+ const fec = recordOf(track["fec"]);
19403
+ const packagingOf = (t) => t["packaging"] ?? msf.common["packaging"];
19404
+ const fecOfTrack = (t) => {
19405
+ const trackFec = recordOf(t?.["fec"]);
19406
+ return trackFec !== void 0 && trackFec["algorithm"] !== "none" ? trackFec : void 0;
19407
+ };
19408
+ const descriptors = [];
19409
+ const mediaTracks = [];
19410
+ msf.tracks.forEach((t, i) => {
19411
+ const path = `$.tracks[${i}]`;
19412
+ if (packagingOf(t) === "fec-repair") {
19413
+ rejectRepairTrackGeometry(path, t, throwRepairContractError);
19414
+ if (typeof t["name"] === "string") descriptors.push(describeRepairTrack(t["name"], path, t));
19415
+ return;
19416
+ }
19417
+ rejectRepairFieldsOnMediaTrack(path, t, throwRepairContractError);
19418
+ mediaTracks.push(t);
19419
+ });
19420
+ const reachability = repairReachability(mediaTracks.map((t) => t["fec"]));
19421
+ for (const d of descriptors) {
19422
+ validateRepairTrackFields(d, throwRepairContractError);
19423
+ assertRepairTrackReachable(d, reachability, throwRepairContractError);
19424
+ const target = dependsTarget(d);
19425
+ if (target === void 0) continue;
19426
+ const targetTrack = msf.tracks.find((t) => t["name"] === target);
19427
+ if (targetTrack === void 0 || packagingOf(targetTrack) !== "mmtp" || fecOfTrack(targetTrack) === void 0) {
19428
+ throwRepairContractError(
19429
+ "track_repair_depends",
19430
+ `${d.path}.depends`,
19431
+ `${JSON.stringify(target)} is not an mmtp track with FEC`
19432
+ );
19433
+ }
19434
+ }
19435
+ return assembleRepairLayers(geometryOf(sourceName, `$.tracks[${msfIndex}].fec`, fec), descriptors, throwRepairContractError, {
19436
+ layerZeroMustBeDeclared: true
19437
+ });
19438
+ }
19439
+ function geometryOf(name, path, fec) {
19440
+ return {
19441
+ name,
19442
+ path,
19443
+ algorithm: fec?.["algorithm"],
19444
+ sourceSymbols: fec?.["sourceSymbols"],
19445
+ repairSymbols: fec?.["repairSymbols"],
19446
+ repairTrack: fec?.["repairTrack"]
19447
+ };
19448
+ }
17544
19449
  function numericField(value) {
17545
19450
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
17546
19451
  return Number.isFinite(n) && n > 0 ? n : void 0;
@@ -17549,13 +19454,16 @@ function nonNegativeField(value) {
17549
19454
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
17550
19455
  return Number.isFinite(n) && n >= 0 ? n : void 0;
17551
19456
  }
17552
- function fecParams(rendition, fps, sampleRate) {
19457
+ function fecParams(catalog, track, rendition, fps, sampleRate) {
17553
19458
  const mediaRate = sampleRate === void 0 ? { fps } : { fps, sampleRate };
17554
19459
  const fec = rendition?.fec;
17555
19460
  if (!fec) return { ...NO_FEC, ...mediaRate };
19461
+ const repair = track ? resolveRepairLayers(catalog, track) : void 0;
17556
19462
  return {
17557
19463
  fecK: fec.sourceSymbols ?? 0,
17558
19464
  fecRepairCount: fec.repairSymbols ?? 0,
19465
+ // The wire RSB_length: every base layer's packets carry the base total (§7.1).
19466
+ fecTotalRepairCount: repair?.totalBaseRepairSymbols ?? fec.repairSymbols ?? 0,
17559
19467
  fecSymbolSize: fec.symbolSize ?? 0,
17560
19468
  // interleaveDepthMs is the FEC block span in MILLISECONDS (§5.1) — the
17561
19469
  // only interleave key the catalog carries post-BLO-14526. Receivers
@@ -17567,6 +19475,8 @@ function fecParams(rendition, fps, sampleRate) {
17567
19475
  // so it cannot be reused here — a declared 0 is a legitimate value.
17568
19476
  fecReorderToleranceMs: nonNegativeField(fec.reorderToleranceMs),
17569
19477
  repairTrackName: fec.repairTrack,
19478
+ repairLayers: repair?.baseLayers,
19479
+ repairOverlays: repair?.overlays,
17570
19480
  ...mediaRate
17571
19481
  };
17572
19482
  }
@@ -17580,8 +19490,14 @@ function resolveCatalogTrackFec(catalog, tracks) {
17580
19490
  const catalogFps = numericField(video?.framerate);
17581
19491
  const sampleRate = numericField(audio?.sampleRate ?? audio?.samplerate);
17582
19492
  const audioFps = sampleRate ? sampleRate / 1024 : void 0;
17583
- const videoParams = fecParams(video, catalogFps);
17584
- const audioParams = fecParams(audio, audioFps, sampleRate);
19493
+ const videoParams = fecParams(catalog, videoTrackName ? { name: videoTrackName, type: "video" } : void 0, video, catalogFps);
19494
+ const audioParams = fecParams(
19495
+ catalog,
19496
+ audioTrackName ? { name: audioTrackName, type: "audio" } : void 0,
19497
+ audio,
19498
+ audioFps,
19499
+ sampleRate
19500
+ );
17585
19501
  return {
17586
19502
  videoTrackName,
17587
19503
  audioTrackName,
@@ -17744,6 +19660,7 @@ export {
17744
19660
  CmafGroupBatcher,
17745
19661
  CmcdProducer,
17746
19662
  CmsfCatalogValidationError,
19663
+ DEFAULT_REPAIR_PRIORITY,
17747
19664
  FECManager,
17748
19665
  FEC_ESI_MAX,
17749
19666
  FEC_SBN_MAX,
@@ -17751,6 +19668,10 @@ export {
17751
19668
  FecStarvationDetector,
17752
19669
  KEYFRAME_LOST_TIMEOUT_SLACK,
17753
19670
  LOCHeaderExtensionId,
19671
+ MAX_ENCODING_SYMBOL_ID,
19672
+ MAX_RAPTORQ_SOURCE_SYMBOLS,
19673
+ MAX_REPAIR_SYMBOLS,
19674
+ MAX_TAKEOVER_DEADLINE_MS,
17754
19675
  MFUReassembler,
17755
19676
  MediaRouter,
17756
19677
  MfuReassemblyError,
@@ -17765,7 +19686,12 @@ export {
17765
19686
  NoneCodec,
17766
19687
  REPAIR_LIFECYCLE_EVENT_TYPE,
17767
19688
  REPAIR_LIFECYCLE_LOG_PREFIX,
19689
+ REPAIR_PRIORITY_MAX,
19690
+ REPAIR_PRIORITY_MIN,
19691
+ REPAIR_TRACK_GEOMETRY_KEYS,
19692
+ REPAIR_TRACK_ONLY_KEYS,
17768
19693
  ReedSolomonCodec,
19694
+ RepairContractError,
17769
19695
  SampleCombineError,
17770
19696
  SampleCombiner,
17771
19697
  SessionManager,
@@ -17776,11 +19702,14 @@ export {
17776
19702
  WasmMfuReassembler,
17777
19703
  annexBToAvcc,
17778
19704
  asSeconds,
19705
+ assembleRepairLayers,
19706
+ assertRepairTrackReachable,
17779
19707
  avccToAnnexB,
17780
19708
  buildAudioInitSegment,
17781
19709
  buildVideoInitSegment,
17782
19710
  catalogAmtNetworkSource,
17783
19711
  catalogFecInterleaveMs,
19712
+ catalogGroupDurationMs,
17784
19713
  classifyH264Keyframe,
17785
19714
  classifyPacket,
17786
19715
  codecStringFromAvcC,
@@ -17795,6 +19724,8 @@ export {
17795
19724
  decodeLocHeader,
17796
19725
  decodeLocTimestamp,
17797
19726
  decodeTimestamp,
19727
+ dependsTarget,
19728
+ describeRepairTrack,
17798
19729
  detectH264Keyframe,
17799
19730
  driftCheck,
17800
19731
  encodeDataSegment,
@@ -17848,12 +19779,17 @@ export {
17848
19779
  parseAacSampleRate,
17849
19780
  parseOpusFrameSamples,
17850
19781
  processMMTPWithReassembly,
19782
+ rejectRepairFieldsOnMediaTrack,
19783
+ rejectRepairTrackGeometry,
17851
19784
  reliableMoqMfuReassembly,
17852
19785
  removeEmulationPrevention,
19786
+ repairReachability,
17853
19787
  resolveCatalogTrackFec,
19788
+ resolveCatalogTrackGroupDurationMs,
17854
19789
  resolveGlobalMmtWasmBindings,
17855
19790
  resolveGroupDurationMs,
17856
19791
  resolveGroupDurationTicks,
19792
+ resolveRepairLayers,
17857
19793
  secondsFromTicks,
17858
19794
  setupFecWorkerForTrack,
17859
19795
  setupTrackPipeline,
@@ -17863,6 +19799,7 @@ export {
17863
19799
  unwrapMulticastPacket,
17864
19800
  validateCmsfMmtpCatalog,
17865
19801
  validateMulticastContainerContract,
19802
+ validateRepairTrackFields,
17866
19803
  validateSwitchingSetTiming,
17867
19804
  wireRepairFetch,
17868
19805
  wrapAdtsFrame