@blockcast/mmt-container 0.1.0-main.dc6b2132f53c → 0.1.0-main.f2d8d03d6809

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 (120) hide show
  1. package/dist/browser-runtime.js +2954 -540
  2. package/dist/browser-runtime.js.map +4 -4
  3. package/dist/carp-catalog.d.ts +7 -7
  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 +13 -9
  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.d.ts +46 -1
  17. package/dist/fec-manager.d.ts.map +1 -1
  18. package/dist/fec-manager.js +129 -34
  19. package/dist/fec-manager.js.map +3 -3
  20. package/dist/fec-worker-setup.d.ts +6 -2
  21. package/dist/fec-worker-setup.d.ts.map +1 -1
  22. package/dist/fec-worker-setup.js +45 -36
  23. package/dist/fec-worker-setup.js.map +3 -3
  24. package/dist/index.d.ts +6 -6
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +43 -1
  27. package/dist/index.js.map +2 -2
  28. package/dist/iso-bmff-timing.d.ts +12 -6
  29. package/dist/iso-bmff-timing.d.ts.map +1 -1
  30. package/dist/iso-bmff-timing.js +40 -8
  31. package/dist/iso-bmff-timing.js.map +2 -2
  32. package/dist/media-router.d.ts +12 -0
  33. package/dist/media-router.d.ts.map +1 -1
  34. package/dist/media-router.js +5 -19
  35. package/dist/media-router.js.map +2 -2
  36. package/dist/mfu-reassembler.d.ts +112 -1
  37. package/dist/mfu-reassembler.d.ts.map +1 -1
  38. package/dist/mfu-reassembler.js +219 -61
  39. package/dist/mfu-reassembler.js.map +2 -2
  40. package/dist/mmtp-container-parser.d.ts +101 -0
  41. package/dist/mmtp-container-parser.d.ts.map +1 -1
  42. package/dist/mmtp-container-parser.js +538 -260
  43. package/dist/mmtp-container-parser.js.map +2 -2
  44. package/dist/mmtp-container-parser.no-modules.js +877 -274
  45. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  46. package/dist/mmtp-decode-pipeline.d.ts +34 -0
  47. package/dist/mmtp-decode-pipeline.d.ts.map +1 -1
  48. package/dist/mmtp-decode-pipeline.js +609 -294
  49. package/dist/mmtp-decode-pipeline.js.map +3 -3
  50. package/dist/mmtp-router.d.ts.map +1 -1
  51. package/dist/mmtp-router.js +581 -275
  52. package/dist/mmtp-router.js.map +3 -3
  53. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  54. package/dist/mmtp-to-cmaf.js +2 -1
  55. package/dist/mmtp-to-cmaf.js.map +2 -2
  56. package/dist/multicast-manager.d.ts +30 -3
  57. package/dist/multicast-manager.d.ts.map +1 -1
  58. package/dist/multicast-manager.js +2177 -410
  59. package/dist/multicast-manager.js.map +4 -4
  60. package/dist/multicast-transport.d.ts +1 -2
  61. package/dist/multicast-transport.d.ts.map +1 -1
  62. package/dist/multicast-transport.js +1347 -24
  63. package/dist/multicast-transport.js.map +4 -4
  64. package/dist/no-modules.js +877 -274
  65. package/dist/no-modules.js.map +4 -4
  66. package/dist/repair-fetch.d.ts.map +1 -1
  67. package/dist/repair-fetch.js +10 -0
  68. package/dist/repair-fetch.js.map +2 -2
  69. package/dist/repair-layers.d.ts +141 -0
  70. package/dist/repair-layers.d.ts.map +1 -0
  71. package/dist/repair-layers.js +303 -0
  72. package/dist/repair-layers.js.map +7 -0
  73. package/dist/track-session.d.ts +64 -24
  74. package/dist/track-session.d.ts.map +1 -1
  75. package/dist/track-session.js +138 -65
  76. package/dist/track-session.js.map +2 -2
  77. package/dist/wasm-mfu-reassembler.d.ts +11 -0
  78. package/dist/wasm-mfu-reassembler.d.ts.map +1 -1
  79. package/dist/wasm-mfu-reassembler.js +42 -27
  80. package/dist/wasm-mfu-reassembler.js.map +2 -2
  81. package/dist/wasm-mmtp-container-parser.js +539 -261
  82. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  83. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +7 -0
  84. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -1
  85. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +14 -5
  86. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -1
  87. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +15 -5
  88. package/package.json +6 -6
  89. package/schemas/catalog.schema.json +82 -5
  90. package/src/carp-catalog.ts +80 -11
  91. package/src/catalog-fec-params.ts +342 -2
  92. package/src/cmaf-block-assembler.ts +23 -1
  93. package/src/fec-manager.ts +168 -18
  94. package/src/fec-worker-setup.ts +37 -11
  95. package/src/index.ts +41 -0
  96. package/src/iso-bmff-timing.ts +62 -7
  97. package/src/media-router.ts +13 -6
  98. package/src/mfu-reassembler.ts +431 -81
  99. package/src/mmtp-container-parser.ts +284 -48
  100. package/src/mmtp-decode-pipeline.ts +93 -24
  101. package/src/mmtp-router.ts +55 -4
  102. package/src/mmtp-to-cmaf.ts +33 -1
  103. package/src/multicast-manager.ts +139 -46
  104. package/src/multicast-transport.ts +30 -29
  105. package/src/repair-fetch.ts +21 -0
  106. package/src/repair-layers.ts +490 -0
  107. package/src/track-session.ts +201 -119
  108. package/src/wasm-mfu-reassembler.ts +18 -1
  109. package/test-vectors/catalog/README.md +16 -1
  110. package/test-vectors/catalog/negative/fec-enhancement-repair-removed.json +27 -0
  111. package/test-vectors/catalog/negative/fec-repair-layer-geometry.json +32 -0
  112. package/test-vectors/catalog/negative/fec-repair-layer-missing-symbols.json +30 -0
  113. package/test-vectors/catalog/negative/fec-repair-multiple-depends.json +31 -0
  114. package/test-vectors/catalog/negative/fec-repair-overlay-with-layer.json +33 -0
  115. package/test-vectors/catalog/negative/fec-repair-priority-out-of-band.json +23 -0
  116. package/test-vectors/catalog/negative/fec-repair-source-symbols-without-scope.json +32 -0
  117. package/test-vectors/catalog/negative/media-track-repair-layer.json +16 -0
  118. package/test-vectors/catalog/negative/raptorq-source-symbols-over-max.json +23 -0
  119. package/test-vectors/catalog/negative/repair-track-legacy-shape.json +2 -1
  120. package/test-vectors/catalog/positive/fec-layered-repair.json +104 -0
@@ -126,7 +126,7 @@ var init_fec_worker_client = __esm({
126
126
  */
127
127
  feedSource(ssId, data, ts, alta) {
128
128
  if (__privateGet(this, _disposed5))
129
- return;
129
+ throw new Error("[FecWorkerClient] feedSource on a disposed client");
130
130
  const cmd = alta ? {
131
131
  type: "feedSource",
132
132
  ssId,
@@ -149,7 +149,7 @@ var init_fec_worker_client = __esm({
149
149
  */
150
150
  feedRepair(ssStart, ssbLength, rsId, data, ts) {
151
151
  if (__privateGet(this, _disposed5))
152
- return;
152
+ throw new Error("[FecWorkerClient] feedRepair on a disposed client");
153
153
  __privateGet(this, _worker).postMessage({
154
154
  type: "feedRepair",
155
155
  ssStart,
@@ -164,7 +164,7 @@ var init_fec_worker_client = __esm({
164
164
  */
165
165
  relayBlockSig(sbn, sig, hash) {
166
166
  if (__privateGet(this, _disposed5))
167
- return;
167
+ throw new Error("[FecWorkerClient] relayBlockSig on a disposed client");
168
168
  __privateGet(this, _worker).postMessage({ type: "relayBlockSig", sbn, sig, hash }, [sig, hash]);
169
169
  }
170
170
  /**
@@ -175,7 +175,7 @@ var init_fec_worker_client = __esm({
175
175
  */
176
176
  cleanup(currentSbn) {
177
177
  if (__privateGet(this, _disposed5))
178
- return;
178
+ throw new Error("[FecWorkerClient] cleanup on a disposed client");
179
179
  if (!Number.isInteger(currentSbn) || currentSbn < 0 || currentSbn > 4294967295) {
180
180
  throw new Error("[FecWorkerClient] cleanup: SBN must be a uint32");
181
181
  }
@@ -188,7 +188,7 @@ var init_fec_worker_client = __esm({
188
188
  /** Reset this track's decoder epoch while preserving Worker configuration. */
189
189
  reset() {
190
190
  if (__privateGet(this, _disposed5))
191
- return;
191
+ throw new Error("[FecWorkerClient] reset on a disposed client");
192
192
  __privateWrapper(this, _pendingResets)._++;
193
193
  __privateSet(this, _cleanupInFlight, null);
194
194
  __privateGet(this, _queuedCleanupSbns).clear();
@@ -218,6 +218,15 @@ var init_fec_worker_client = __esm({
218
218
  onError(cb) {
219
219
  __privateSet(this, _onError, cb);
220
220
  }
221
+ /**
222
+ * True once dispose() ran. A disposed client cannot decode, fill, or
223
+ * acknowledge anything, so routing symbols to it discards them; every
224
+ * command method (feedSource, feedRepair, relayBlockSig, cleanup, reset)
225
+ * throws rather than pretend otherwise. Callers check this first.
226
+ */
227
+ get disposed() {
228
+ return __privateGet(this, _disposed5);
229
+ }
221
230
  /**
222
231
  * Dispose the Worker. Sends dispose command then terminates.
223
232
  * Idempotent — safe to call multiple times.
@@ -1020,7 +1029,10 @@ function checkedSampleEnd(offset, byteLength) {
1020
1029
  return Number.isSafeInteger(end) && end <= 4294967295 ? end : null;
1021
1030
  }
1022
1031
  var COMPLETED_ADDRESS_WINDOW_MULTIPLE = 2;
1023
- var _buffers, _timeouts, _activeDataUnits, _pendingContinuations, _emitted, _emittedOrder, _completed, _completedOrder, _timeoutMs, _maxBuffered, _MFUReassembler_instances, addAssociatedFragment_fn, parkContinuation_fn, drainPendingContinuations_fn, incompleteRunCount_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;
1032
+ function parkedRunHoldsASlot(hasOpenRun, fragmentCount) {
1033
+ return !hasOpenRun && fragmentCount > 0;
1034
+ }
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;
1024
1036
  var MFUReassembler = class {
1025
1037
  constructor(options) {
1026
1038
  __privateAdd(this, _MFUReassembler_instances);
@@ -1048,6 +1060,11 @@ var MFUReassembler = class {
1048
1060
  __privateAdd(this, _completedOrder, []);
1049
1061
  __privateAdd(this, _timeoutMs);
1050
1062
  __privateAdd(this, _maxBuffered);
1063
+ /**
1064
+ * Monotonic admission ordinal. Counts slot admissions, never reads a clock,
1065
+ * so eviction order survives on hosts that run `timeoutMs: null`.
1066
+ */
1067
+ __privateAdd(this, _nextAdmissionSeq, 0);
1051
1068
  /** Statistics for debugging */
1052
1069
  this.stats = {
1053
1070
  totalFragments: 0,
@@ -1081,12 +1098,9 @@ var MFUReassembler = class {
1081
1098
  state.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onTimeout_fn).call(this, bufferKey), Math.max(0, state.startedAt + ms - now));
1082
1099
  }
1083
1100
  }
1084
- for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1085
- if (pending.timeoutId !== void 0) clearTimeout(pending.timeoutId);
1086
- delete pending.timeoutId;
1087
- if (ms !== null && __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) === void 0) {
1088
- pending.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address), Math.max(0, pending.startedAt + ms - now));
1089
- }
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);
1090
1104
  }
1091
1105
  }
1092
1106
  get timeoutMs() {
@@ -1250,14 +1264,26 @@ var MFUReassembler = class {
1250
1264
  this.stats.outOfOrderFragments = 0;
1251
1265
  }
1252
1266
  /**
1253
- * Get number of pending MFUs
1267
+ * Get number of pending MFUs: engine buffers plus every headless parked data
1268
+ * unit that holds a slot.
1269
+ *
1270
+ * This is not one of the four charging sites, but it shares their second term,
1271
+ * so it takes the same rule — by delegating to `#unopenedParkedRunCount`, the
1272
+ * one site that applies it. Rust's public `buffered_count()` is
1273
+ * `inner.buffered_count() + unopened_parked_run_count()`, and that count is
1274
+ * `parked_run_holds_a_slot` — so filtering here on the open run alone would
1275
+ * report a phantom slot for an empty published queue in TypeScript and not in
1276
+ * Rust, out of a *host-observable* counter (`getStatus().bufferedMFUs`). Same
1277
+ * state, two numbers, decided by which engine the host loaded: the divergence
1278
+ * class this file exists to close, so the public counters have to agree too.
1279
+ *
1280
+ * Distinct from `#incompleteRunCount`, which sums `#activeDataUnits` rather
1281
+ * than `#buffers`. Those are different quantities by design and are not being
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.
1254
1284
  */
1255
1285
  get pendingCount() {
1256
- let count = __privateGet(this, _buffers).size;
1257
- for (const address of __privateGet(this, _pendingContinuations).keys()) {
1258
- if (__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) === void 0) count++;
1259
- }
1260
- return count;
1286
+ return __privateGet(this, _buffers).size + __privateMethod(this, _MFUReassembler_instances, unopenedParkedRunCount_fn).call(this);
1261
1287
  }
1262
1288
  /**
1263
1289
  * Get current buffer status
@@ -1288,6 +1314,7 @@ _completed = new WeakMap();
1288
1314
  _completedOrder = new WeakMap();
1289
1315
  _timeoutMs = new WeakMap();
1290
1316
  _maxBuffered = new WeakMap();
1317
+ _nextAdmissionSeq = new WeakMap();
1291
1318
  _MFUReassembler_instances = new WeakSet();
1292
1319
  addAssociatedFragment_fn = function(fragment, runKey, address, startedAt) {
1293
1320
  const association = __privateMethod(this, _MFUReassembler_instances, associateDataUnit_fn).call(this, fragment, runKey, address);
@@ -1317,22 +1344,33 @@ addAssociatedFragment_fn = function(fragment, runKey, address, startedAt) {
1317
1344
  };
1318
1345
  parkContinuation_fn = function(address, fragment) {
1319
1346
  let pending = __privateGet(this, _pendingContinuations).get(address);
1320
- if (pending === void 0) {
1321
- const awaitingFirst = __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) === void 0;
1322
- if (awaitingFirst && __privateMethod(this, _MFUReassembler_instances, incompleteRunCount_fn).call(this) >= __privateGet(this, _maxBuffered)) {
1347
+ const open = __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address);
1348
+ const alreadyCharged = open !== void 0 || parkedRunHoldsASlot(open !== void 0, pending?.fragments.size ?? 0);
1349
+ if (!alreadyCharged && __privateMethod(this, _MFUReassembler_instances, incompleteRunCount_fn).call(this) >= __privateGet(this, _maxBuffered)) {
1350
+ if (!__privateMethod(this, _MFUReassembler_instances, evictLeastRecentlyAdmitted_fn).call(this)) {
1323
1351
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
1324
1352
  }
1325
- const startedAt = Date.now();
1326
- pending = { fragments: /* @__PURE__ */ new Map(), startedAt };
1327
- if (awaitingFirst && __privateGet(this, _timeoutMs) !== null) {
1328
- pending.timeoutId = setTimeout(() => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address), __privateGet(this, _timeoutMs));
1329
- }
1353
+ }
1354
+ let armAfterInsert = false;
1355
+ if (pending === void 0) {
1356
+ pending = {
1357
+ fragments: /* @__PURE__ */ new Map(),
1358
+ startedAt: Date.now(),
1359
+ admissionSeq: open !== void 0 ? open[1].admissionSeq : __privateWrapper(this, _nextAdmissionSeq)._++
1360
+ };
1330
1361
  __privateGet(this, _pendingContinuations).set(address, pending);
1362
+ armAfterInsert = true;
1363
+ } else if (!alreadyCharged) {
1364
+ pending.admissionSeq = __privateWrapper(this, _nextAdmissionSeq)._++;
1365
+ pending.startedAt = Date.now();
1366
+ __privateMethod(this, _MFUReassembler_instances, clearPendingTimeout_fn).call(this, address);
1367
+ armAfterInsert = true;
1331
1368
  }
1332
1369
  if (pending.fragments.has(fragment.fragmentCounter)) {
1333
1370
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "fragment-counter-mismatch", "duplicate queued continuation counter would replace retained media");
1334
1371
  }
1335
1372
  pending.fragments.set(fragment.fragmentCounter, fragment);
1373
+ if (armAfterInsert) __privateMethod(this, _MFUReassembler_instances, armHeadlessPendingTimeout_fn).call(this, address);
1336
1374
  };
1337
1375
  drainPendingContinuations_fn = function(address, runKey) {
1338
1376
  while (true) {
@@ -1355,15 +1393,92 @@ drainPendingContinuations_fn = function(address, runKey) {
1355
1393
  }
1356
1394
  }
1357
1395
  };
1358
- /** Every open run plus every headless parked data unit, one slot each.
1359
- * This is the quantity maxBuffered bounds. */
1360
- incompleteRunCount_fn = function() {
1361
- let count = __privateGet(this, _activeDataUnits).size;
1362
- for (const address of __privateGet(this, _pendingContinuations).keys()) {
1363
- if (__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) === void 0) count++;
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;
1410
+ for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1411
+ if (parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1412
+ count++;
1413
+ }
1364
1414
  }
1365
1415
  return count;
1366
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
+ };
1425
+ /**
1426
+ * Drop the incomplete data unit admitted longest ago so a newly arriving one
1427
+ * can take its slot. Selection is by monotonic admission ordinal, never by
1428
+ * wall clock, so this is a bounded-capacity replacement policy and not a
1429
+ * timeout: it behaves identically on hosts that never drive `cleanup_timeouts`
1430
+ * (`timeoutMs: null`). Only incomplete data units are candidates — a data
1431
+ * unit that completed has already left both maps.
1432
+ *
1433
+ * Returns false only if no slot is charged, which cannot happen at the bound
1434
+ * (`maxBuffered` is a positive integer); admission then falls back to the
1435
+ * fail-closed `active-data-unit-limit` reject, which stays a stable host code.
1436
+ * That holds because the candidate set here is built from the same
1437
+ * `parkedRunHoldsASlot` rule `#incompleteRunCount` counts by, so reaching the
1438
+ * bound implies at least one candidate. Filtering one and not the other would
1439
+ * make the claim false: a queue counted but not offered charges a slot no
1440
+ * eviction can reclaim, and the receiver refuses every later data unit
1441
+ * permanently.
1442
+ */
1443
+ evictLeastRecentlyAdmitted_fn = function() {
1444
+ let victimAddress;
1445
+ let victimSeq = Number.POSITIVE_INFINITY;
1446
+ for (const [, active] of __privateGet(this, _activeDataUnits)) {
1447
+ if (active.admissionSeq < victimSeq) {
1448
+ victimSeq = active.admissionSeq;
1449
+ victimAddress = active.address;
1450
+ }
1451
+ }
1452
+ for (const [address, pending] of __privateGet(this, _pendingContinuations)) {
1453
+ if (!parkedRunHoldsASlot(__privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0, pending.fragments.size)) {
1454
+ continue;
1455
+ }
1456
+ if (pending.admissionSeq < victimSeq) {
1457
+ victimSeq = pending.admissionSeq;
1458
+ victimAddress = address;
1459
+ }
1460
+ }
1461
+ if (victimAddress === void 0) return false;
1462
+ __privateMethod(this, _MFUReassembler_instances, releaseSlot_fn).call(this, victimAddress);
1463
+ this.stats.evictedMemoryLimit++;
1464
+ return true;
1465
+ };
1466
+ /**
1467
+ * Release every form of state one address holds: its open run, that run's
1468
+ * buffered fragments and deadline, and its continuation queue. The address is
1469
+ * deliberately not marked completed — the data unit never emitted, so a later
1470
+ * fragment of it may open a fresh slot rather than being rejected as stale.
1471
+ */
1472
+ releaseSlot_fn = function(address) {
1473
+ const open = __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address);
1474
+ if (open !== void 0) {
1475
+ const [runKey, active] = open;
1476
+ __privateGet(this, _activeDataUnits).delete(runKey);
1477
+ __privateMethod(this, _MFUReassembler_instances, clearTimeout_fn).call(this, active.bufferKey);
1478
+ __privateGet(this, _buffers).delete(active.bufferKey);
1479
+ }
1480
+ __privateMethod(this, _MFUReassembler_instances, deletePendingRun_fn).call(this, address);
1481
+ };
1367
1482
  reject_fn = function(code, message) {
1368
1483
  this.stats.rejectedFragments++;
1369
1484
  throw new MfuReassemblyError(code, message);
@@ -1371,10 +1486,11 @@ reject_fn = function(code, message) {
1371
1486
  associateDataUnit_fn = function(fragment, runKey, address) {
1372
1487
  const fi = fragment.fragmentationIndicator;
1373
1488
  if (fi === 1) {
1374
- const inheritsParkedSlot = (__privateGet(this, _pendingContinuations).get(address)?.fragments.size ?? 0) > 0;
1375
- if (!inheritsParkedSlot && __privateMethod(this, _MFUReassembler_instances, incompleteRunCount_fn).call(this) >= __privateGet(this, _maxBuffered)) {
1376
- __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
1377
- }
1489
+ const parked = __privateGet(this, _pendingContinuations).get(address);
1490
+ const inheritsParkedSlot = parkedRunHoldsASlot(
1491
+ __privateMethod(this, _MFUReassembler_instances, openRunAt_fn).call(this, address) !== void 0,
1492
+ parked?.fragments.size ?? 0
1493
+ );
1378
1494
  const sampleIdentity = hasSampleIdentity(fragment);
1379
1495
  const hasSampleFields = hasAnySampleIdentityField(fragment);
1380
1496
  const hasItemIdentity = fragment.itemId !== void 0;
@@ -1394,18 +1510,28 @@ associateDataUnit_fn = function(fragment, runKey, address) {
1394
1510
  if (__privateGet(this, _buffers).has(bufferKey)) {
1395
1511
  __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "overlapping-data-unit", "intrinsic data-unit buffer already exists");
1396
1512
  }
1513
+ let sampleEnd = null;
1514
+ if (sampleIdentity) {
1515
+ sampleEnd = checkedSampleEnd(fragment.sampleOffset, fragment.data.byteLength);
1516
+ if (sampleEnd === null) __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "offset-overflow", "sample byte offset overflow");
1517
+ }
1518
+ if (!inheritsParkedSlot && __privateMethod(this, _MFUReassembler_instances, incompleteRunCount_fn).call(this) >= __privateGet(this, _maxBuffered)) {
1519
+ if (!__privateMethod(this, _MFUReassembler_instances, evictLeastRecentlyAdmitted_fn).call(this)) {
1520
+ __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "active-data-unit-limit", "active MFU data-unit limit reached");
1521
+ }
1522
+ }
1523
+ const admissionSeq = inheritsParkedSlot ? parked.admissionSeq : __privateWrapper(this, _nextAdmissionSeq)._++;
1397
1524
  let active2;
1398
1525
  if (sampleIdentity) {
1399
- const nextOffset = checkedSampleEnd(fragment.sampleOffset, fragment.data.byteLength);
1400
- if (nextOffset === null) __privateMethod(this, _MFUReassembler_instances, reject_fn).call(this, "offset-overflow", "sample byte offset overflow");
1401
1526
  active2 = {
1402
1527
  address,
1403
1528
  kind: "sample",
1404
1529
  bufferKey,
1405
1530
  nextFragmentCounter: fragment.fragmentCounter - 1,
1531
+ admissionSeq,
1406
1532
  movieFragmentSequenceNumber: fragment.movieFragmentSequenceNumber,
1407
1533
  sampleNumber: fragment.sampleNumber,
1408
- nextOffset,
1534
+ nextOffset: sampleEnd,
1409
1535
  ...fragment.catalogTrackName === void 0 ? {} : { catalogTrackName: fragment.catalogTrackName }
1410
1536
  };
1411
1537
  } else {
@@ -1414,6 +1540,7 @@ associateDataUnit_fn = function(fragment, runKey, address) {
1414
1540
  kind: "item",
1415
1541
  bufferKey,
1416
1542
  nextFragmentCounter: fragment.fragmentCounter - 1,
1543
+ admissionSeq,
1417
1544
  itemId: fragment.itemId,
1418
1545
  ...fragment.catalogTrackName === void 0 ? {} : { catalogTrackName: fragment.catalogTrackName }
1419
1546
  };
@@ -1534,11 +1661,19 @@ clearPendingTimeout_fn = function(address) {
1534
1661
  /**
1535
1662
  * A queue whose run closed without completing is headless again and expires
1536
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).
1537
1672
  */
1538
1673
  armHeadlessPendingTimeout_fn = function(address) {
1539
1674
  const pending = __privateGet(this, _pendingContinuations).get(address);
1540
1675
  if (pending === void 0 || pending.timeoutId !== void 0 || __privateGet(this, _timeoutMs) === null) return;
1541
- 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;
1542
1677
  pending.timeoutId = setTimeout(
1543
1678
  () => __privateMethod(this, _MFUReassembler_instances, onPendingTimeout_fn).call(this, address),
1544
1679
  Math.max(0, pending.startedAt + __privateGet(this, _timeoutMs) - Date.now())
@@ -1551,6 +1686,10 @@ deletePendingRun_fn = function(address) {
1551
1686
  onPendingTimeout_fn = function(address) {
1552
1687
  const pending = __privateGet(this, _pendingContinuations).get(address);
1553
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
+ }
1554
1693
  this.stats.timedOutMFUs++;
1555
1694
  console.warn(
1556
1695
  `[MfuReassembler] timeout: run=${address} fragments=${pending.fragments.size} (continuations awaiting first fragment, discarded)`
@@ -2815,8 +2954,9 @@ if (void 0) {
2815
2954
  packetSequenceNumber: testPacketSequence(1, 0)
2816
2955
  })
2817
2956
  ).toBeNull();
2818
- expectRejection(
2819
- () => reassembler.addFragment({
2957
+ expect(reassembler.pendingCount).toBe(1);
2958
+ expect(
2959
+ reassembler.addFragment({
2820
2960
  fragmentationIndicator: 3,
2821
2961
  mpuSequenceNumber: 2,
2822
2962
  fragmentCounter: 0,
@@ -2824,24 +2964,24 @@ if (void 0) {
2824
2964
  timestamp: 1000n,
2825
2965
  rapFlag: false,
2826
2966
  packetSequenceNumber: testPacketSequence(2, 0)
2827
- }),
2828
- "active-data-unit-limit"
2829
- );
2830
- expectRejection(
2831
- () => reassembler.addFragment({
2832
- fragmentationIndicator: 1,
2833
- mpuSequenceNumber: 2,
2834
- fragmentCounter: 1,
2835
- itemId: 2,
2836
- data: new Uint8Array([2]),
2837
- timestamp: 1000n,
2838
- rapFlag: true,
2839
- packetSequenceNumber: testPacketSequence(2, 1)
2840
- }),
2841
- "active-data-unit-limit"
2842
- );
2967
+ })
2968
+ ).toBeNull();
2843
2969
  expect(reassembler.pendingCount).toBe(1);
2844
2970
  expect(reassembler.getStatus().pendingFragments).toBe(1);
2971
+ expect(reassembler.stats.evictedMemoryLimit).toBe(1);
2972
+ const completed = reassembler.addFragment({
2973
+ fragmentationIndicator: 1,
2974
+ mpuSequenceNumber: 2,
2975
+ fragmentCounter: 1,
2976
+ itemId: 2,
2977
+ data: new Uint8Array([4]),
2978
+ timestamp: 1000n,
2979
+ rapFlag: true,
2980
+ packetSequenceNumber: testPacketSequence(2, 1)
2981
+ });
2982
+ expect(completed?.data).toEqual(new Uint8Array([4, 2]));
2983
+ expect(reassembler.stats.evictedMemoryLimit).toBe(1);
2984
+ expect(reassembler.pendingCount).toBe(0);
2845
2985
  const result = reassembler.addFragment({
2846
2986
  fragmentationIndicator: 1,
2847
2987
  mpuSequenceNumber: 1,
@@ -2852,7 +2992,8 @@ if (void 0) {
2852
2992
  rapFlag: true,
2853
2993
  packetSequenceNumber: testPacketSequence(1, 1)
2854
2994
  });
2855
- expect(result?.data).toEqual(new Uint8Array([3, 1]));
2995
+ expect(result).toBeNull();
2996
+ expect(reassembler.pendingCount).toBe(1);
2856
2997
  });
2857
2998
  test("expires a continuation that never receives its first fragment", () => {
2858
2999
  vi.useFakeTimers();
@@ -2917,7 +3058,7 @@ if (void 0) {
2917
3058
  vi.useRealTimers();
2918
3059
  }
2919
3060
  });
2920
- test("bounds active data units and rejects a new first at maxBuffered", () => {
3061
+ test("bounds active data units by evicting the oldest at maxBuffered", () => {
2921
3062
  const reassembler = new MFUReassembler({
2922
3063
  timeoutMs: 1e3,
2923
3064
  maxBuffered: 2
@@ -2934,8 +3075,8 @@ if (void 0) {
2934
3075
  packetSequenceNumber: testPacketSequence(i, 1)
2935
3076
  });
2936
3077
  }
2937
- expectRejection(
2938
- () => reassembler.addFragment({
3078
+ expect(
3079
+ reassembler.addFragment({
2939
3080
  fragmentationIndicator: 1,
2940
3081
  mpuSequenceNumber: 2,
2941
3082
  fragmentCounter: 1,
@@ -2944,12 +3085,25 @@ if (void 0) {
2944
3085
  timestamp: 200n,
2945
3086
  rapFlag: false,
2946
3087
  packetSequenceNumber: testPacketSequence(2, 1)
2947
- }),
2948
- "active-data-unit-limit"
2949
- );
3088
+ })
3089
+ ).toBeNull();
3090
+ expect(reassembler.pendingCount).toBe(2);
3091
+ expect(reassembler.stats.timedOutMFUs).toBe(0);
3092
+ expect(reassembler.stats.evictedMemoryLimit).toBe(1);
3093
+ expect(
3094
+ reassembler.addFragment({
3095
+ fragmentationIndicator: 3,
3096
+ mpuSequenceNumber: 0,
3097
+ fragmentCounter: 0,
3098
+ data: new Uint8Array([9]),
3099
+ timestamp: 300n,
3100
+ rapFlag: false,
3101
+ packetSequenceNumber: testPacketSequence(0, 0)
3102
+ })
3103
+ ).toBeNull();
2950
3104
  expect(reassembler.pendingCount).toBe(2);
3105
+ expect(reassembler.stats.evictedMemoryLimit).toBe(2);
2951
3106
  expect(reassembler.stats.timedOutMFUs).toBe(0);
2952
- expect(reassembler.stats.evictedMemoryLimit).toBe(0);
2953
3107
  });
2954
3108
  test("should report stats correctly", () => {
2955
3109
  const reassembler = new MFUReassembler({ timeoutMs: 1e3 });
@@ -5649,6 +5803,289 @@ function resolveMulticastAuthCatalog(catalog, playerMode) {
5649
5803
  };
5650
5804
  }
5651
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
+
5652
6089
  // src/carp-catalog.ts
5653
6090
  var VALID_ROLE_SUFFIXES = /* @__PURE__ */ new Set(["base", "delta", "repair"]);
5654
6091
  function parseTrackRole(trackName) {
@@ -5775,7 +6212,7 @@ function validateCmsfMmtpCatalog(value) {
5775
6212
  const tracks = catalog["tracks"];
5776
6213
  const trackRecords = [];
5777
6214
  const effective = (track, field) => track[field] ?? common[field];
5778
- const positiveInteger = (input) => Number.isSafeInteger(input) && input > 0;
6215
+ const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
5779
6216
  const positiveNumber = (input) => typeof input === "number" && Number.isFinite(input) && input > 0;
5780
6217
  for (let index = 0; index < tracks.length; index++) {
5781
6218
  const raw = tracks[index];
@@ -5811,21 +6248,27 @@ function validateCmsfMmtpCatalog(value) {
5811
6248
  const groupDurationTicks = effective(track, "groupDurationTicks");
5812
6249
  const keyframeIntervalMs = effective(track, "keyframeIntervalMs");
5813
6250
  const keyframeIntervalTicks = effective(track, "keyframeIntervalTicks");
5814
- if (groupDurationMs !== void 0 && !positiveInteger(groupDurationMs)) {
6251
+ if (groupDurationMs !== void 0 && !positiveInteger2(groupDurationMs)) {
5815
6252
  catalogError("track_group_duration_ms", `${path}.groupDurationMs`, "must be a positive integer");
5816
6253
  }
5817
- if (groupDurationTicks !== void 0 && !positiveInteger(groupDurationTicks)) {
6254
+ if (groupDurationTicks !== void 0 && !positiveInteger2(groupDurationTicks)) {
5818
6255
  catalogError("track_group_duration_ticks", `${path}.groupDurationTicks`, "must be a positive integer");
5819
6256
  }
5820
- if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger(keyframeIntervalTicks)) {
6257
+ if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
5821
6258
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
5822
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
+ }
5823
6266
  if (packaging === "mmtp") {
5824
6267
  const mmtpMode = effective(track, "mmtpMode");
5825
6268
  if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
5826
6269
  catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
5827
6270
  }
5828
- if (!positiveInteger(timescale)) {
6271
+ if (!positiveInteger2(timescale)) {
5829
6272
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
5830
6273
  }
5831
6274
  if (groupDurationMs === void 0 && groupDurationTicks === void 0) {
@@ -5852,12 +6295,19 @@ function validateCmsfMmtpCatalog(value) {
5852
6295
  if ("interleaveDepth" in config || "interleaveMs" in config) {
5853
6296
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
5854
6297
  }
5855
- 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"])) {
5856
6306
  catalogError("track_fec", `${path}.fec.interleaveDepthMs`, "must be a positive integer");
5857
6307
  }
5858
6308
  if (algorithm !== "none") {
5859
6309
  for (const field of ["sourceSymbols", "repairSymbols", "symbolSize"]) {
5860
- if (!positiveInteger(config[field])) {
6310
+ if (!positiveInteger2(config[field])) {
5861
6311
  catalogError("track_fec", `${path}.fec.${field}`, "must be a positive integer");
5862
6312
  }
5863
6313
  }
@@ -5867,15 +6317,43 @@ function validateCmsfMmtpCatalog(value) {
5867
6317
  }
5868
6318
  }
5869
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
+ }
5870
6340
  for (let index = 0; index < trackRecords.length; index++) {
5871
6341
  const track = trackRecords[index];
5872
6342
  const fec = track["fec"];
5873
6343
  if (!fec || fec["algorithm"] === "none") continue;
5874
- const repairTrack = fec["repairTrack"];
5875
- const target = trackRecords.find((candidate) => candidate["name"] === repairTrack);
5876
- if (!target || effective(target, "packaging") !== "fec-repair") {
5877
- catalogError("track_repair_track", `$.tracks[${index}].fec.repairTrack`, `unknown FEC repair track ${JSON.stringify(repairTrack)}`);
5878
- }
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
+ );
5879
6357
  }
5880
6358
  const switchingSets = /* @__PURE__ */ new Map();
5881
6359
  for (let index = 0; index < trackRecords.length; index++) {
@@ -7299,6 +7777,7 @@ var MmtpToCmaf = class {
7299
7777
  const samplesPerFrame = __privateGet(this, _audioTimescale) !== 1e6 ? __privateGet(this, _aacFrameSamples) : sampleDuration;
7300
7778
  const scaledTs = __privateGet(this, _audioTimescale) !== 1e6 ? __privateGet(this, _audioSampleCount) * samplesPerFrame : timestamp - __privateGet(this, _audioBaseTs);
7301
7779
  __privateWrapper(this, _audioSampleCount)._++;
7780
+ const scaledCompositionTimeOffset = compositionTimeOffset === void 0 || __privateGet(this, _audioTimescale) === 1e6 ? compositionTimeOffset : Math.round(compositionTimeOffset * __privateGet(this, _audioTimescale) / 1e6);
7302
7781
  return encodeDataSegment(
7303
7782
  sampleData,
7304
7783
  scaledTs,
@@ -7306,7 +7785,7 @@ var MmtpToCmaf = class {
7306
7785
  true,
7307
7786
  __privateWrapper(this, _audioSeq)._++,
7308
7787
  1,
7309
- compositionTimeOffset
7788
+ scaledCompositionTimeOffset
7310
7789
  );
7311
7790
  }
7312
7791
  /** Convert an ordered audio batch using the caller-owned timeline. */
@@ -7577,7 +8056,7 @@ var CmafBlockAssembler = class {
7577
8056
  __privateWrapper(this, _addFrameCount)._++;
7578
8057
  __privateMethod(this, _CmafBlockAssembler_instances, startAggregateTimer_fn).call(this);
7579
8058
  if (!__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, timestamp);
7580
- __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);
7581
8060
  __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "addFrame-direct", [{ data, timestamp, keyframe }]);
7582
8061
  }
7583
8062
  /** Mark a block as complete (all K source symbols received or FEC recovery succeeded).
@@ -7624,7 +8103,7 @@ var CmafBlockAssembler = class {
7624
8103
  /** Emit a single frame immediately as a one-sample segment (for oversized packets bypassing FEC). */
7625
8104
  addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
7626
8105
  if (!__privateMethod(this, _CmafBlockAssembler_instances, ordersSamples_fn).call(this)) __privateMethod(this, _CmafBlockAssembler_instances, drainRecoveredUpTo_fn).call(this, timestamp);
7627
- __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);
7628
8107
  }
7629
8108
  /** Build and emit init segment from catalog config. */
7630
8109
  emitInit() {
@@ -7774,7 +8253,7 @@ unwrapTimestamp_fn = function(timestamp) {
7774
8253
  if (reference < 0) return timestamp;
7775
8254
  return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod;
7776
8255
  };
7777
- 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) {
7778
8257
  const scaledTiming = authoredTiming === void 0 ? null : scaleAuthoredTiming(authoredTiming, __privateGet(this, _config).timescale);
7779
8258
  if (authoredTiming !== void 0 && scaledTiming === null) return;
7780
8259
  const authoredTimestamp = scaledTiming?.timestamp ?? timestamp;
@@ -7812,7 +8291,8 @@ emitSample_fn = function(data, timestamp, duration, keyframe, advancesHorizon, c
7812
8291
  ...movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber },
7813
8292
  ...sampleNumber === void 0 ? {} : { sampleNumber },
7814
8293
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
7815
- ...deliveryProvenance === void 0 ? {} : { deliveryProvenance }
8294
+ ...deliveryProvenance === void 0 ? {} : { deliveryProvenance },
8295
+ ...synthetic === void 0 ? {} : { synthetic }
7816
8296
  });
7817
8297
  if (advancesHorizon && unwrappedTimestamp > __privateGet(this, _lastSourceTs)) {
7818
8298
  __privateSet(this, _lastSourceTs, unwrappedTimestamp);
@@ -7950,7 +8430,8 @@ emitAudioGapFillNowBefore_fn = function(timestamp) {
7950
8430
  data: __privateGet(this, _lastDecodableAudioFrame).slice(),
7951
8431
  timestamp: fillTs,
7952
8432
  duration: __privateGet(this, _frameDuration2),
7953
- keyframe: true
8433
+ keyframe: true,
8434
+ synthetic: true
7954
8435
  }, false);
7955
8436
  }
7956
8437
  };
@@ -7968,7 +8449,7 @@ emitPerSample_fn = function(frames, audioDurationOverride, advancesHorizon = fal
7968
8449
  duration = audioDurationOverride ?? __privateGet(this, _frameDuration2);
7969
8450
  }
7970
8451
  if (duration <= 0) duration = audioDurationOverride ?? __privateGet(this, _frameDuration2);
7971
- __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);
7972
8453
  }
7973
8454
  };
7974
8455
  _dumpCount = new WeakMap();
@@ -7983,8 +8464,9 @@ _aggregateTimer = new WeakMap();
7983
8464
  startAggregateTimer_fn = function() {
7984
8465
  if (__privateGet(this, _aggregateTimer)) return;
7985
8466
  __privateSet(this, _aggregateTimer, setInterval(() => {
8467
+ const order = __privateGet(this, _sampleOrderStats);
7986
8468
  console.log(
7987
- `[L4-AGG-${__privateGet(this, _config).trackType}] emits=${__privateGet(this, _emitCount)} samples=${__privateGet(this, _sampleCount)} kf=${__privateGet(this, _keyframeCount)} addFrame=${__privateGet(this, _addFrameCount)} recovered=${__privateGet(this, _recoveredBlockCount)} complete=${__privateGet(this, _completeBlockCount)} fail=${__privateGet(this, _failBlockCount)} pendingBlocks=${__privateGet(this, _blocks).size} pendingFlushes=${__privateGet(this, _pendingFlush).size} armedVideo=${__privateGet(this, _armedVideo)}`
8469
+ `[L4-AGG-${__privateGet(this, _config).trackType}] emits=${__privateGet(this, _emitCount)} samples=${__privateGet(this, _sampleCount)} kf=${__privateGet(this, _keyframeCount)} addFrame=${__privateGet(this, _addFrameCount)} recovered=${__privateGet(this, _recoveredBlockCount)} complete=${__privateGet(this, _completeBlockCount)} fail=${__privateGet(this, _failBlockCount)} pendingBlocks=${__privateGet(this, _blocks).size} pendingFlushes=${__privateGet(this, _pendingFlush).size} armedVideo=${__privateGet(this, _armedVideo)} forced=${order.forcedReleases} stale=${order.staleSamples} dup=${order.duplicateSamples} preRap=${order.preRapDeadlineDrops} noRap=${order.noRapFlushDrops}`
7988
8470
  );
7989
8471
  __privateSet(this, _emitCount, 0);
7990
8472
  __privateSet(this, _sampleCount, 0);
@@ -8042,7 +8524,7 @@ drainRecoveredUpTo_fn = function(horizonTs) {
8042
8524
  const ready = [...__privateGet(this, _pendingRecovered).values()].filter((frame) => frame.timestamp <= horizonTs).sort((a, b) => a.timestamp - b.timestamp);
8043
8525
  for (const frame of ready) {
8044
8526
  __privateGet(this, _pendingRecovered).delete(frame.timestamp);
8045
- __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);
8046
8528
  __privateMethod(this, _CmafBlockAssembler_instances, dumpEmit_fn).call(this, "recovered-drain", [frame]);
8047
8529
  }
8048
8530
  };
@@ -8091,7 +8573,8 @@ flushBlockWithFill_fn = function(sbn) {
8091
8573
  data: isVideo ? __privateGet(this, _fillFrame) : audioConcealmentFrame?.slice() ?? new Uint8Array(0),
8092
8574
  timestamp: interpolatedTs,
8093
8575
  // Video: first fill is keyframe (IDR). Audio: all fill marked keyframe.
8094
- keyframe: isVideo ? !block.has(0) && esi === 0 : true
8576
+ keyframe: isVideo ? !block.has(0) && esi === 0 : true,
8577
+ synthetic: true
8095
8578
  });
8096
8579
  }
8097
8580
  }
@@ -8414,6 +8897,15 @@ function deriveFecInterleaveDepth(interleaveDepthMs, mediaUnitDurationMs) {
8414
8897
  }
8415
8898
  return Math.max(1, Math.floor(interleaveDepthMs / mediaUnitDurationMs + 0.5));
8416
8899
  }
8900
+ function fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs) {
8901
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0)) {
8902
+ throw new Error(`[FEC] interleaveDepthMs must be a finite value > 0 (got ${interleaveDepthMs}ms). Fix encoder config.`);
8903
+ }
8904
+ if (!(reorderToleranceMs >= 0) || !Number.isFinite(reorderToleranceMs)) {
8905
+ throw new Error(`[FEC] reorderToleranceMs must be a finite value >= 0 (got ${reorderToleranceMs}ms). It is a catalog value (fec.reorderToleranceMs), not a local default.`);
8906
+ }
8907
+ return Math.ceil(interleaveDepthMs + reorderToleranceMs);
8908
+ }
8417
8909
  function parseRepairPacket(packet) {
8418
8910
  const parsed = parseMoqRepairFrame(packet);
8419
8911
  if (!parsed)
@@ -8515,32 +9007,18 @@ function computeFecLossWindowMs(fecInterleaveMs, fecK, jitterBufferMs) {
8515
9007
  function computeFecDeliveryWindowMs(config) {
8516
9008
  const fecInterleaveMs = config.interleaveDepthMs;
8517
9009
  const fecK = config.sourceSymbols;
8518
- if (fecInterleaveMs <= 0) {
9010
+ if (!Number.isFinite(fecInterleaveMs) || fecInterleaveMs <= 0) {
8519
9011
  throw new Error(
8520
9012
  `[TrackSession] fecInterleaveMs=${fecInterleaveMs}. Derive a positive FEC interleave window from the stream catalog.`
8521
9013
  );
8522
9014
  }
8523
- if (fecK <= 0) {
9015
+ if (!Number.isFinite(fecK) || fecK <= 0) {
8524
9016
  throw new Error(
8525
9017
  `[TrackSession] fecK=${fecK}. Derive a positive FEC source-symbol count from the stream catalog.`
8526
9018
  );
8527
9019
  }
8528
- const spansMs = [fecInterleaveMs];
8529
- if (config.mediaUnitsPerSecond && config.mediaUnitsPerSecond > 0) {
8530
- const mediaUnitMs = 1e3 / config.mediaUnitsPerSecond;
8531
- const interleaveUnits = deriveFecInterleaveDepth(fecInterleaveMs, mediaUnitMs);
8532
- const deliverySymbols = fecK + Math.max(0, config.repairSymbols ?? 0);
8533
- spansMs.push(deliverySymbols * interleaveUnits * mediaUnitMs);
8534
- }
8535
- if (config.symbolSize && config.symbolSize > 0 && config.bandwidthBps && config.bandwidthBps > 0) {
8536
- const repairSymbols = Math.max(0, config.repairSymbols ?? 0);
8537
- spansMs.push(
8538
- (fecK + repairSymbols) * config.symbolSize * 8 * 1e3 / config.bandwidthBps
8539
- );
8540
- }
8541
- const coreMs = Math.max(...spansMs);
8542
- const marginMs = config.jitterBufferMs !== void 0 && config.jitterBufferMs >= 0 ? config.jitterBufferMs : fecInterleaveMs;
8543
- return Math.ceil(coreMs) + Math.ceil(marginMs);
9020
+ if (config.jitterBufferMs === void 0) return Math.ceil(fecInterleaveMs);
9021
+ return fecBlockBudgetMs(fecInterleaveMs, config.jitterBufferMs);
8544
9022
  }
8545
9023
  function computeFecDeliveryWindowMediaUnits(config, timestampTimescale) {
8546
9024
  if (!Number.isFinite(timestampTimescale) || timestampTimescale <= 0) {
@@ -8556,7 +9034,7 @@ function computeFecDeliveryWindowMediaUnits(config, timestampTimescale) {
8556
9034
  }
8557
9035
  return deliveryWindow;
8558
9036
  }
8559
- 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;
8560
9038
  var TrackSession = class {
8561
9039
  constructor(config, manager) {
8562
9040
  __privateAdd(this, _TrackSession_instances);
@@ -8573,6 +9051,12 @@ var TrackSession = class {
8573
9051
  // from `failing` (exactly where a starving track sits) was re-subscribed to
8574
9052
  // unicast with the host's media still muted: MoQ playing into a dead sink.
8575
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);
8576
9060
  this.config = config;
8577
9061
  __privateSet(this, _manager, manager);
8578
9062
  }
@@ -8647,7 +9131,7 @@ var TrackSession = class {
8647
9131
  joinStarted() {
8648
9132
  if (__privateGet(this, _state) !== "unicast") return;
8649
9133
  __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "joining");
8650
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-setup" }, this.config);
9134
+ __privateMethod(this, _TrackSession_instances, armFec_fn).call(this);
8651
9135
  }
8652
9136
  /**
8653
9137
  * any non-fallback state → unicast-fallback. Used when the SSM bridge is
@@ -8668,7 +9152,7 @@ var TrackSession = class {
8668
9152
  __privateMethod(this, _TrackSession_instances, clearHysteresis_fn).call(this);
8669
9153
  __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast-fallback");
8670
9154
  __privateMethod(this, _TrackSession_instances, suppress_fn).call(this);
8671
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-setup" }, this.config);
9155
+ __privateMethod(this, _TrackSession_instances, armFec_fn).call(this);
8672
9156
  }
8673
9157
  /**
8674
9158
  * unicast-fallback → unicast. Called when the SSM bridge appears mid-session
@@ -8699,7 +9183,11 @@ var TrackSession = class {
8699
9183
  if (__privateGet(this, _state) !== "multicast" && __privateGet(this, _state) !== "amt") return;
8700
9184
  __privateSet(this, _previousPrimary, __privateGet(this, _state));
8701
9185
  __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "failing");
8702
- const hysteresisMs = computeFecLossWindowMs(this.config.fecInterleaveMs, this.config.fecK);
9186
+ const hysteresisMs = computeFecLossWindowMs(
9187
+ this.config.fecInterleaveMs,
9188
+ this.config.fecK,
9189
+ this.config.fecReorderToleranceMs
9190
+ );
8703
9191
  __privateSet(this, _hysteresisTimer, setTimeout(() => {
8704
9192
  this.hysteresisExpired();
8705
9193
  }, hysteresisMs));
@@ -8723,23 +9211,19 @@ var TrackSession = class {
8723
9211
  const prefs = this.config.preferredTransports;
8724
9212
  const currentIdx = current ? prefs.indexOf(current) : -1;
8725
9213
  const nextMode = prefs[currentIdx + 1];
8726
- if (nextMode) {
8727
- if (nextMode === "moq") {
8728
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast");
8729
- __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
8730
- if (this.config.trackType === "audio") {
8731
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "reset" }, this.config);
8732
- }
8733
- } else {
8734
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "joining");
8735
- __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
8736
- }
8737
- } else {
8738
- __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");
8739
9217
  __privateMethod(this, _TrackSession_instances, unsuppress_fn).call(this);
8740
- if (this.config.trackType === "audio") {
8741
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "reset" }, this.config);
8742
- }
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);
8743
9227
  }
8744
9228
  }
8745
9229
  /** Hysteresis expired → failback to next transport (Claim 9g). */
@@ -8763,11 +9247,20 @@ var TrackSession = class {
8763
9247
  get isUnicastFallback() {
8764
9248
  return __privateGet(this, _state) === "unicast-fallback";
8765
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
+ }
8766
9258
  dispose() {
8767
9259
  __privateMethod(this, _TrackSession_instances, clearHysteresis_fn).call(this);
8768
9260
  __privateMethod(this, _TrackSession_instances, clearJoinDeadline_fn).call(this);
8769
9261
  __privateSet(this, _state, "idle");
8770
9262
  __privateSet(this, _subscription, null);
9263
+ __privateMethod(this, _TrackSession_instances, disarmFec_fn).call(this);
8771
9264
  }
8772
9265
  };
8773
9266
  _state = new WeakMap();
@@ -8777,20 +9270,20 @@ _joinDeadlineTimer = new WeakMap();
8777
9270
  _previousPrimary = new WeakMap();
8778
9271
  _manager = new WeakMap();
8779
9272
  _suppressFired = new WeakMap();
9273
+ _fecArmed = new WeakMap();
8780
9274
  _TrackSession_instances = new WeakSet();
8781
9275
  // -----------------------------------------------------------------------
8782
9276
  // Internal
8783
9277
  // -----------------------------------------------------------------------
8784
- transition_fn = function(to) {
9278
+ transition_fn = function(to, opts) {
8785
9279
  const from = __privateGet(this, _state);
8786
9280
  if (from === to) return;
9281
+ const joinDeadlineMs = to === "joining" ? __privateGet(this, _manager).takeoverDeadlineMs : void 0;
8787
9282
  __privateSet(this, _state, to);
8788
9283
  if (from === "joining") __privateMethod(this, _TrackSession_instances, clearJoinDeadline_fn).call(this);
8789
- 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);
8790
9285
  const fecActive = (s) => s === "joining" || s === "multicast" || s === "amt" || s === "failing" || s === "unicast-fallback";
8791
- if (fecActive(from) && !fecActive(to)) {
8792
- __privateGet(this, _manager).mmtp?.onTrackEvent?.(this.config.trackName, { type: "fec-teardown" }, this.config);
8793
- }
9286
+ if (!fecActive(to) && !opts?.retainFec) __privateMethod(this, _TrackSession_instances, disarmFec_fn).call(this);
8794
9287
  __privateGet(this, _manager).callbacks?.onStateChange?.(this.config.trackName, from, to);
8795
9288
  };
8796
9289
  clearHysteresis_fn = function() {
@@ -8799,14 +9292,13 @@ clearHysteresis_fn = function() {
8799
9292
  __privateSet(this, _hysteresisTimer, null);
8800
9293
  }
8801
9294
  };
8802
- armJoinDeadline_fn = function() {
9295
+ armJoinDeadline_fn = function(deadlineMs) {
8803
9296
  __privateMethod(this, _TrackSession_instances, clearJoinDeadline_fn).call(this);
8804
- const deadlineMs = __privateGet(this, _manager).takeoverDeadlineMs;
8805
- if (deadlineMs <= 0) return;
9297
+ if (deadlineMs === 0) return;
8806
9298
  __privateSet(this, _joinDeadlineTimer, setTimeout(() => {
8807
9299
  __privateSet(this, _joinDeadlineTimer, null);
8808
9300
  if (__privateGet(this, _state) !== "joining") return;
8809
- __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast");
9301
+ __privateMethod(this, _TrackSession_instances, transition_fn).call(this, "unicast", { retainFec: true });
8810
9302
  __privateGet(this, _manager).callbacks?.onTakeoverTimeout?.(this.config.trackName);
8811
9303
  }, deadlineMs));
8812
9304
  };
@@ -8816,6 +9308,18 @@ clearJoinDeadline_fn = function() {
8816
9308
  __privateSet(this, _joinDeadlineTimer, null);
8817
9309
  }
8818
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
+ };
8819
9323
  /** Fire onSuppress(true) exactly once per suppression epoch. */
8820
9324
  suppress_fn = function() {
8821
9325
  if (__privateGet(this, _suppressFired)) return;
@@ -8828,18 +9332,14 @@ unsuppress_fn = function() {
8828
9332
  __privateSet(this, _suppressFired, false);
8829
9333
  __privateGet(this, _manager).callbacks?.onSuppress?.(this.config.trackName, false);
8830
9334
  };
9335
+ var MAX_TAKEOVER_DEADLINE_MS = 2147483647;
9336
+ var _takeoverDeadlineMs, _SessionManager_instances, requireTakeoverDeadlineMs_fn;
8831
9337
  var SessionManager = class {
8832
9338
  constructor(poolOptions) {
9339
+ __privateAdd(this, _SessionManager_instances);
8833
9340
  this.sessions = /* @__PURE__ */ new Map();
8834
9341
  this.callbacks = null;
8835
- /**
8836
- * Takeover deadline (BLO-9413/D9): max time a session may sit in `joining`
8837
- * without a RAP before returning to `unicast` and firing onTakeoverTimeout.
8838
- * MoQ is never suppressed during `joining`, so expiry is a silent abandon —
8839
- * playback never glitches. Hosts tune per stream (e.g. GOP length); 0
8840
- * disables.
8841
- */
8842
- this.takeoverDeadlineMs = 5e3;
9342
+ __privateAdd(this, _takeoverDeadlineMs);
8843
9343
  this.pool = new TransportPool(poolOptions);
8844
9344
  this.pool.onSubscriptionFailed((sub) => {
8845
9345
  for (const trackName of sub.consumers) {
@@ -8848,18 +9348,56 @@ var SessionManager = class {
8848
9348
  }
8849
9349
  });
8850
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
+ }
8851
9391
  /** Narrow to MMTP callbacks (onTrackEvent). Safe — optional chaining handles PIM-only consumers. */
8852
9392
  get mmtp() {
8853
9393
  return this.callbacks;
8854
9394
  }
8855
- // -----------------------------------------------------------------------
8856
- // Track management
8857
- // -----------------------------------------------------------------------
8858
9395
  /** Add a track session from catalog config. */
8859
9396
  addTrack(config) {
8860
9397
  if (this.sessions.has(config.trackName)) {
8861
9398
  throw new Error(`[SessionManager] Track "${config.trackName}" already exists`);
8862
9399
  }
9400
+ __privateMethod(this, _SessionManager_instances, requireTakeoverDeadlineMs_fn).call(this);
8863
9401
  const session = new TrackSession(config, this);
8864
9402
  this.sessions.set(config.trackName, session);
8865
9403
  return session;
@@ -8883,8 +9421,9 @@ var SessionManager = class {
8883
9421
  * Prevents split-brain between video and audio.
8884
9422
  *
8885
9423
  * A takeover deadline can return a track from `joining` to `unicast` while
8886
- * the multicast socket keeps delivering packets. If a valid RAP arrives
8887
- * 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.
8888
9427
  */
8889
9428
  activateMulticast() {
8890
9429
  for (const [, session] of this.sessions) {
@@ -8916,13 +9455,17 @@ var SessionManager = class {
8916
9455
  * and they must drain uninterrupted across transport-state events.
8917
9456
  *
8918
9457
  * Coherence invariant (BLO-9413): after this returns, every non-fallback
8919
- * session is `unicast` (or `idle`) AND unsuppressed — unsubscribe() unwinds
8920
- * any outstanding suppression regardless of the state it tears down from
8921
- * (`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).
8922
9464
  */
8923
9465
  failbackAll() {
8924
9466
  for (const [, session] of this.sessions) {
8925
- 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") {
8926
9469
  session.unsubscribe();
8927
9470
  session.subscribe();
8928
9471
  }
@@ -9006,6 +9549,27 @@ var SessionManager = class {
9006
9549
  this.callbacks = null;
9007
9550
  }
9008
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
+ };
9009
9573
 
9010
9574
  // src/fec-manager.ts
9011
9575
  var MIN_INTERLEAVE_DEPTH_MS = 33;
@@ -9024,7 +9588,7 @@ function newFecCounters() {
9024
9588
  greenFillFrames: 0
9025
9589
  };
9026
9590
  }
9027
- var _fecDecoders, _workerClients, _syncDecoderBlockOwners, _decoderBlockOwners, _fecK, _fecSymbolSize, _fecTimeoutMs, _trackConfigs, _fecStats, _fecTrackStats, _fecWorkerStats, _fecStatsObservers, _activeBlocks, _activeBlockDeadlinesMs, _activeBlockTimeoutOwners, _lifecycleTrace, _pendingWorkerCleanups, _pendingWorkerCleanupClients, _blockSourceCounts, _blockSourceEsis, _blockRepairRsIds, _completedBlocks, _seenSymbols, _blockPathCounts, _blockCatalogTrackNames, _startupAlignedPackets, _startupPartialBlocks, _startupRequireRepairReady, _startupRepairReadyPackets, _startupRepairBoundaryCounts, _startupRepairFailOpenPackets, _cleanlyCompletedBlocks, _repairRequestedBlocks, _repairDeadlines, _workerRecoveredBlocks, _fpsDetected, _fecFps, _fecInterleaveDepthMs, _workerErrorCounts, _repairSymbolSizeMismatchCount, _FECManager_instances, streamKey_fn, belongsToPacket_fn, belongsToStream_fn, packetIdsForStreamKeys_fn, blockKey_fn, parseBlockKey_fn, decoderForPacket_fn, workerForPacket_fn, claimDecoderBlock_fn, decoderBlockCatalogTrackName_fn, resetDecoderBlockOwners_fn, discardFecDecoderClient_fn, assertExclusiveDecoderClient_fn, statsForPacket_fn, markPathBlockComplete_fn, clearRepairDeadline_fn, requestRepair_fn, traceLifecycle_fn, defaultTrackConfig_fn, resolveTrackConfig_fn, computeTimeout_fn, repairDeadlineMs_fn, repairGraceMs_fn, armBlockTimeout_fn, upsertTrackConfig_fn, normalizeSymbolData_fn, blockKeysFor_fn, observeBlockCatalogTrackName_fn, markStartupPartial_fn, routeSyncCleanup_fn, failBlock_fn;
9591
+ var _fecDecoders, _workerClients, _syncDecoderBlockOwners, _decoderBlockOwners, _fecK, _fecSymbolSize, _fecTimeoutMs, _trackConfigs, _fecStats, _fecTrackStats, _fecWorkerStats, _fecStatsObservers, _activeBlocks, _activeBlockDeadlinesMs, _activeBlockTimeoutOwners, _lifecycleTrace, _pendingWorkerCleanups, _pendingWorkerCleanupClients, _blockSourceCounts, _blockSourceEsis, _blockRepairRsIds, _completedBlocks, _seenSymbols, _blockPathCounts, _blockCatalogTrackNames, _startupAlignedPackets, _startupPartialBlocks, _startupRequireRepairReady, _startupRepairReadyPackets, _startupRepairBoundaryCounts, _startupRepairFailOpenPackets, _cleanlyCompletedBlocks, _repairRequestedBlocks, _repairDeadlines, _workerRecoveredBlocks, _fpsDetected, _fecFps, _fecInterleaveDepthMs, _workerErrorCounts, _decoderUnavailableEvents, _repairSymbolSizeMismatchCount, _FECManager_instances, streamKey_fn, belongsToPacket_fn, belongsToStream_fn, packetIdsForStreamKeys_fn, parseStreamKey_fn, blockKey_fn, parseBlockKey_fn, decoderForPacket_fn, workerForPacket_fn, routableWorkerForPacket_fn, claimDecoderBlock_fn, decoderBlockCatalogTrackName_fn, resetDecoderBlockOwners_fn, discardFecDecoderClient_fn, assertExclusiveDecoderClient_fn, statsForPacket_fn, markPathBlockComplete_fn, clearRepairDeadline_fn, requestRepair_fn, traceLifecycle_fn, defaultTrackConfig_fn, resolveTrackConfig_fn, computeTimeout_fn, repairDeadlineMs_fn, repairGraceMs_fn, armBlockTimeout_fn, upsertTrackConfig_fn, normalizeSymbolData_fn, blockKeysFor_fn, observeBlockCatalogTrackName_fn, markStartupPartial_fn, retireWorker_fn, releaseWorkerClient_fn, settleOwedCleanup_fn, evictDisposedWorker_fn, routeSyncCleanup_fn, failBlock_fn;
9028
9592
  var FECManager = class {
9029
9593
  constructor() {
9030
9594
  __privateAdd(this, _FECManager_instances);
@@ -9128,6 +9692,7 @@ var FECManager = class {
9128
9692
  // validation harness — which caps headless warnings at 500 — fails even
9129
9693
  // though the errors are duplicates of a single underlying event.
9130
9694
  __privateAdd(this, _workerErrorCounts, /* @__PURE__ */ new Map());
9695
+ __privateAdd(this, _decoderUnavailableEvents, 0);
9131
9696
  __privateAdd(this, _repairSymbolSizeMismatchCount, 0);
9132
9697
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
9133
9698
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
@@ -9136,6 +9701,17 @@ var FECManager = class {
9136
9701
  this.onBlockStarted = null;
9137
9702
  this.onBlockComplete = null;
9138
9703
  this.onBlockFailed = null;
9704
+ /**
9705
+ * Fired once per stream when its Worker decoder stops being routable.
9706
+ * `reason` is 'cleared' when clearFecWorker() removed it and 'disposed' when
9707
+ * a symbol or reset found the registered client already disposed and
9708
+ * evicted it. `fallbackDecoder` is 'sync' when a synchronous WASM decoder
9709
+ * registered for the same stream keeps decoding its symbols, and 'none'
9710
+ * when nothing does. Only 'none' leaves the stream unprotected: the host
9711
+ * must then register a decoder again or leave the stream, because counting
9712
+ * its symbols as handled would hide the loss.
9713
+ */
9714
+ this.onDecoderUnavailable = null;
9139
9715
  // D-28 on-demand repair callbacks. When onRepairNeeded is registered, each
9140
9716
  // block arms a one-shot repair deadline after the derived K-symbol source
9141
9717
  // horizon; a block still short of K when it fires requests a per-SBN MoQ
@@ -9169,6 +9745,7 @@ var FECManager = class {
9169
9745
  startupRepairReadyPackets: __privateMethod(this, _FECManager_instances, packetIdsForStreamKeys_fn).call(this, __privateGet(this, _startupRepairReadyPackets)),
9170
9746
  startupRepairFailOpenPackets: __privateMethod(this, _FECManager_instances, packetIdsForStreamKeys_fn).call(this, __privateGet(this, _startupRepairFailOpenPackets)),
9171
9747
  pendingWorkerCleanups: __privateGet(this, _pendingWorkerCleanups).size,
9748
+ decoderUnavailableEvents: __privateGet(this, _decoderUnavailableEvents),
9172
9749
  repairTrackedBlocks: __privateGet(this, _blockRepairRsIds).size,
9173
9750
  lifecycleTrace: __privateGet(this, _lifecycleTrace).map((entry) => ({ ...entry }))
9174
9751
  };
@@ -9303,8 +9880,12 @@ var FECManager = class {
9303
9880
  __privateMethod(this, _FECManager_instances, discardFecDecoderClient_fn).call(this, client);
9304
9881
  }
9305
9882
  }
9306
- for (const [key, client] of __privateGet(this, _workerClients)) {
9883
+ for (const [key, client] of [...__privateGet(this, _workerClients)]) {
9307
9884
  if (!__privateMethod(this, _FECManager_instances, belongsToStream_fn).call(this, key, packetId, catalogTrackName)) continue;
9885
+ if (client.disposed === true) {
9886
+ __privateMethod(this, _FECManager_instances, evictDisposedWorker_fn).call(this, client);
9887
+ continue;
9888
+ }
9308
9889
  client.reset();
9309
9890
  clients.add(client);
9310
9891
  }
@@ -9524,6 +10105,12 @@ var FECManager = class {
9524
10105
  }
9525
10106
  const streamKey = __privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName);
9526
10107
  __privateMethod(this, _FECManager_instances, assertExclusiveDecoderClient_fn).call(this, streamKey, client, __privateGet(this, _workerClients), "worker");
10108
+ const incumbent = __privateGet(this, _workerClients).get(streamKey);
10109
+ if (incumbent !== void 0 && incumbent !== client) {
10110
+ throw new Error(
10111
+ `[FECManager] stream ${streamKey} already routes to a Worker; call clearFecWorker before registering another`
10112
+ );
10113
+ }
9527
10114
  if (config) __privateMethod(this, _FECManager_instances, upsertTrackConfig_fn).call(this, packetId, config);
9528
10115
  const workerK = __privateMethod(this, _FECManager_instances, resolveTrackConfig_fn).call(this, packetId).k;
9529
10116
  __privateGet(this, _workerClients).set(streamKey, client);
@@ -9610,14 +10197,7 @@ var FECManager = class {
9610
10197
  const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
9611
10198
  return block.packetId === packetId && block.sbn === sbn && __privateGet(this, _pendingWorkerCleanupClients).get(key) === client;
9612
10199
  });
9613
- for (const key of cleanupKeys) {
9614
- __privateGet(this, _pendingWorkerCleanups).delete(key);
9615
- __privateGet(this, _pendingWorkerCleanupClients).delete(key);
9616
- if (__privateGet(this, _completedBlocks).has(key)) continue;
9617
- const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
9618
- __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "cleanup-ack", sbn, packetId, block.catalogTrackName);
9619
- __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, sbn, packetId, false, block.catalogTrackName);
9620
- }
10200
+ for (const key of cleanupKeys) __privateMethod(this, _FECManager_instances, settleOwedCleanup_fn).call(this, key, "cleanup-ack");
9621
10201
  });
9622
10202
  client.onError((msg, code) => {
9623
10203
  const requestedKind = code ?? msg;
@@ -9633,7 +10213,26 @@ var FECManager = class {
9633
10213
  }
9634
10214
  });
9635
10215
  }
9636
- /** Called by player when framerate is known (from decoder output). Refines FEC block timeout. */
10216
+ /**
10217
+ * Remove a stream's Worker decoder from routing.
10218
+ *
10219
+ * Returns false when no Worker is registered under that exact stream key.
10220
+ * On success every cleanup acknowledgement still owed by the client is
10221
+ * resolved by failing its block now (a Worker that is going away cannot
10222
+ * post it), the client's block ownership is released, and
10223
+ * onDecoderUnavailable fires once with reason 'cleared' and the decoder
10224
+ * that remains for the stream ('sync' or 'none'). Call this before
10225
+ * disposing the client; a client disposed while still registered is
10226
+ * evicted on its next symbol or reset with reason 'disposed'.
10227
+ */
10228
+ clearFecWorker(packetId, catalogTrackName) {
10229
+ const streamKey = __privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName);
10230
+ const client = __privateGet(this, _workerClients).get(streamKey);
10231
+ if (!client) return false;
10232
+ __privateMethod(this, _FECManager_instances, retireWorker_fn).call(this, streamKey, client, "cleared");
10233
+ return true;
10234
+ }
10235
+ /** Called by player when framerate is known (from decoder output). Refines FEC block timeout. */
9637
10236
  setFramerate(fps) {
9638
10237
  if (__privateGet(this, _fpsDetected) || fps <= 0) return;
9639
10238
  __privateSet(this, _fpsDetected, true);
@@ -9683,7 +10282,7 @@ var FECManager = class {
9683
10282
  const sbn = Math.floor(ssId / this.kForPacket(packetId));
9684
10283
  const blockKey = __privateMethod(this, _FECManager_instances, blockKey_fn).call(this, sbn, packetId, catalogTrackName);
9685
10284
  const syncBlockOwner = __privateGet(this, _syncDecoderBlockOwners).get(blockKey);
9686
- const workerClient = __privateMethod(this, _FECManager_instances, workerForPacket_fn).call(this, packetId, catalogTrackName);
10285
+ const workerClient = __privateMethod(this, _FECManager_instances, routableWorkerForPacket_fn).call(this, packetId, catalogTrackName);
9687
10286
  if (workerClient && !syncBlockOwner) {
9688
10287
  if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, workerClient, sbn, catalogTrackName)) return null;
9689
10288
  const buf = fecData.buffer.slice(
@@ -9760,7 +10359,7 @@ var FECManager = class {
9760
10359
  if (__privateGet(this, _repairRequestedBlocks).has(blockKey)) {
9761
10360
  __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, "repair-arrived", sbn, packetId, catalogTrackName, rsId);
9762
10361
  }
9763
- const workerClient = __privateMethod(this, _FECManager_instances, workerForPacket_fn).call(this, packetId, catalogTrackName);
10362
+ const workerClient = __privateMethod(this, _FECManager_instances, routableWorkerForPacket_fn).call(this, packetId, catalogTrackName);
9764
10363
  if (workerClient && !syncBlockOwner) {
9765
10364
  if (!__privateMethod(this, _FECManager_instances, claimDecoderBlock_fn).call(this, workerClient, sbn, catalogTrackName)) return null;
9766
10365
  const buf = fecData.buffer.slice(
@@ -10045,6 +10644,7 @@ _fpsDetected = new WeakMap();
10045
10644
  _fecFps = new WeakMap();
10046
10645
  _fecInterleaveDepthMs = new WeakMap();
10047
10646
  _workerErrorCounts = new WeakMap();
10647
+ _decoderUnavailableEvents = new WeakMap();
10048
10648
  _repairSymbolSizeMismatchCount = new WeakMap();
10049
10649
  _FECManager_instances = new WeakSet();
10050
10650
  streamKey_fn = function(packetId, catalogTrackName) {
@@ -10064,6 +10664,14 @@ belongsToStream_fn = function(key, packetId, catalogTrackName) {
10064
10664
  packetIdsForStreamKeys_fn = function(keys) {
10065
10665
  return [...new Set([...keys].map((key) => Number(key.split(":", 1)[0])))];
10066
10666
  };
10667
+ parseStreamKey_fn = function(key) {
10668
+ const separator = key.indexOf(":");
10669
+ if (separator < 0) return { packetId: Number(key) || 0 };
10670
+ return {
10671
+ packetId: Number(key.slice(0, separator)) || 0,
10672
+ catalogTrackName: decodeURIComponent(key.slice(separator + 1))
10673
+ };
10674
+ };
10067
10675
  blockKey_fn = function(sbn, packetId, catalogTrackName) {
10068
10676
  const base = `${packetId}:${sbn}`;
10069
10677
  return catalogTrackName === void 0 ? base : `${base}:${encodeURIComponent(catalogTrackName)}`;
@@ -10083,6 +10691,18 @@ decoderForPacket_fn = function(packetId, catalogTrackName) {
10083
10691
  workerForPacket_fn = function(packetId, catalogTrackName) {
10084
10692
  return __privateGet(this, _workerClients).get(__privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId, catalogTrackName)) ?? __privateGet(this, _workerClients).get(__privateMethod(this, _FECManager_instances, streamKey_fn).call(this, packetId));
10085
10693
  };
10694
+ /**
10695
+ * The stream's Worker client for routing, or undefined after evicting a
10696
+ * registered client that was already disposed. A disposed client throws on
10697
+ * every command, so it leaves routing here before a symbol reaches it and
10698
+ * the stream reports its decoder unavailable instead.
10699
+ */
10700
+ routableWorkerForPacket_fn = function(packetId, catalogTrackName) {
10701
+ const client = __privateMethod(this, _FECManager_instances, workerForPacket_fn).call(this, packetId, catalogTrackName);
10702
+ if (client === void 0 || client.disposed !== true) return client;
10703
+ __privateMethod(this, _FECManager_instances, evictDisposedWorker_fn).call(this, client);
10704
+ return void 0;
10705
+ };
10086
10706
  claimDecoderBlock_fn = function(client, sbn, catalogTrackName) {
10087
10707
  let blocks = __privateGet(this, _decoderBlockOwners).get(client);
10088
10708
  if (!blocks) {
@@ -10250,7 +10870,7 @@ armBlockTimeout_fn = function(sbn, packetId, catalogTrackName, delayMs) {
10250
10870
  __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, sbn, packetId, false, catalogTrackName);
10251
10871
  return;
10252
10872
  }
10253
- const workerClient = __privateMethod(this, _FECManager_instances, workerForPacket_fn).call(this, packetId, catalogTrackName);
10873
+ const workerClient = __privateMethod(this, _FECManager_instances, routableWorkerForPacket_fn).call(this, packetId, catalogTrackName);
10254
10874
  if (workerClient) {
10255
10875
  __privateGet(this, _pendingWorkerCleanups).add(key);
10256
10876
  __privateGet(this, _pendingWorkerCleanupClients).set(key, workerClient);
@@ -10333,6 +10953,59 @@ markStartupPartial_fn = function(blockKey) {
10333
10953
  ));
10334
10954
  }
10335
10955
  };
10956
+ /**
10957
+ * Take a Worker client out of routing under one stream key, fail the blocks
10958
+ * whose completion it still owed, and report the stream's decoder
10959
+ * unavailable together with whatever still decodes the stream.
10960
+ */
10961
+ retireWorker_fn = function(streamKey, client, reason) {
10962
+ __privateGet(this, _workerClients).delete(streamKey);
10963
+ __privateMethod(this, _FECManager_instances, releaseWorkerClient_fn).call(this, client);
10964
+ __privateWrapper(this, _decoderUnavailableEvents)._++;
10965
+ const stream = __privateMethod(this, _FECManager_instances, parseStreamKey_fn).call(this, streamKey);
10966
+ const fallbackDecoder = __privateMethod(this, _FECManager_instances, decoderForPacket_fn).call(this, stream.packetId, stream.catalogTrackName) ? "sync" : "none";
10967
+ this.onDecoderUnavailable?.({
10968
+ packetId: stream.packetId,
10969
+ ...stream.catalogTrackName === void 0 ? {} : { catalogTrackName: stream.catalogTrackName },
10970
+ reason,
10971
+ fallbackDecoder
10972
+ });
10973
+ };
10974
+ /**
10975
+ * Fail every block whose Worker cleanup acknowledgement is owed by `client`
10976
+ * and drop its block ownership, so no block waits on a message the Worker
10977
+ * will never post.
10978
+ */
10979
+ releaseWorkerClient_fn = function(client) {
10980
+ const owed = [...__privateGet(this, _pendingWorkerCleanupClients)].filter(([, owner]) => owner === client).map(([key]) => key);
10981
+ for (const key of owed) __privateMethod(this, _FECManager_instances, settleOwedCleanup_fn).call(this, key, "decoder-unavailable");
10982
+ __privateGet(this, _decoderBlockOwners).delete(client);
10983
+ };
10984
+ /**
10985
+ * Resolve one owed Worker cleanup: drop the pending entry and fail the block
10986
+ * unless it already completed. Shared by the cleanup acknowledgement and by
10987
+ * Worker retirement, so the two paths cannot drift in their bookkeeping.
10988
+ */
10989
+ settleOwedCleanup_fn = function(key, event) {
10990
+ __privateGet(this, _pendingWorkerCleanups).delete(key);
10991
+ __privateGet(this, _pendingWorkerCleanupClients).delete(key);
10992
+ if (__privateGet(this, _completedBlocks).has(key)) return;
10993
+ const block = __privateMethod(this, _FECManager_instances, parseBlockKey_fn).call(this, key);
10994
+ __privateMethod(this, _FECManager_instances, traceLifecycle_fn).call(this, event, block.sbn, block.packetId, block.catalogTrackName);
10995
+ __privateMethod(this, _FECManager_instances, failBlock_fn).call(this, block.sbn, block.packetId, false, block.catalogTrackName);
10996
+ };
10997
+ /** Evict a disposed client under every stream key that still maps to it. */
10998
+ evictDisposedWorker_fn = function(client) {
10999
+ for (const [key, registered] of [...__privateGet(this, _workerClients)]) {
11000
+ if (registered !== client) continue;
11001
+ const stream = __privateMethod(this, _FECManager_instances, parseStreamKey_fn).call(this, key);
11002
+ const track = stream.catalogTrackName === void 0 ? "" : ` track=${stream.catalogTrackName}`;
11003
+ console.warn(
11004
+ `[FECManager] packetId=${stream.packetId}${track} Worker decoder was disposed while still registered; evicting it`
11005
+ );
11006
+ __privateMethod(this, _FECManager_instances, retireWorker_fn).call(this, key, client, "disposed");
11007
+ }
11008
+ };
10336
11009
  routeSyncCleanup_fn = function(decoder, sbn, packetId) {
10337
11010
  let framed;
10338
11011
  try {
@@ -10904,7 +11577,7 @@ function sameTrack(a, b) {
10904
11577
  function sameSample(a, b) {
10905
11578
  return a.decodeTime === b.decodeTime && a.presentationTime === b.presentationTime && a.duration === b.duration && a.timescale === b.timescale && a.size === b.size && a.bytePosition === b.bytePosition;
10906
11579
  }
10907
- var _track, _fragments, _pendingSamples, _lastMovieFragmentRejection, _IsoBmffTimingResolver_instances, clearSlot_fn;
11580
+ var _track, _fragments, _pendingSamples, _evictedSamples, _lastMovieFragmentRejection, _IsoBmffTimingResolver_instances, evictOldestFragment_fn, clearSlot_fn;
10908
11581
  var IsoBmffTimingResolver = class {
10909
11582
  constructor(maxPendingSamples) {
10910
11583
  this.maxPendingSamples = maxPendingSamples;
@@ -10912,6 +11585,7 @@ var IsoBmffTimingResolver = class {
10912
11585
  __privateAdd(this, _track, null);
10913
11586
  __privateAdd(this, _fragments, /* @__PURE__ */ new Map());
10914
11587
  __privateAdd(this, _pendingSamples, 0);
11588
+ __privateAdd(this, _evictedSamples, 0);
10915
11589
  __privateAdd(this, _lastMovieFragmentRejection, null);
10916
11590
  if (!Number.isInteger(maxPendingSamples) || maxPendingSamples <= 0) {
10917
11591
  throw new Error("[IsoBmffTimingResolver] maxPendingSamples must be a positive integer");
@@ -10920,6 +11594,15 @@ var IsoBmffTimingResolver = class {
10920
11594
  get pendingSampleCount() {
10921
11595
  return __privateGet(this, _pendingSamples);
10922
11596
  }
11597
+ /**
11598
+ * Slots reclaimed by window displacement rather than by delivery or
11599
+ * abandonment. Deliberately separate from the combiner's own release count:
11600
+ * "nobody ever saw this sample" and "the combiner gave up on it" are
11601
+ * different failures with different owners, and one number cannot say which.
11602
+ */
11603
+ get evictedSampleCount() {
11604
+ return __privateGet(this, _evictedSamples);
11605
+ }
10923
11606
  /** Typed reason for the most recent rejected movie fragment. */
10924
11607
  get lastMovieFragmentRejection() {
10925
11608
  return __privateGet(this, _lastMovieFragmentRejection);
@@ -10957,7 +11640,11 @@ var IsoBmffTimingResolver = class {
10957
11640
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
10958
11641
  );
10959
11642
  }
10960
- if (parsed.samples.length > additionalSampleLimit) {
11643
+ let freed = 0;
11644
+ while (__privateGet(this, _fragments).size > 0 && (__privateGet(this, _pendingSamples) + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
11645
+ freed += __privateMethod(this, _IsoBmffTimingResolver_instances, evictOldestFragment_fn).call(this);
11646
+ }
11647
+ if (parsed.samples.length - freed > additionalSampleLimit) {
10961
11648
  __privateSet(this, _lastMovieFragmentRejection, "budget");
10962
11649
  return false;
10963
11650
  }
@@ -10990,12 +11677,11 @@ var IsoBmffTimingResolver = class {
10990
11677
  * Free the budget slot of a sample that will never be delivered.
10991
11678
  *
10992
11679
  * `consumeSample` is the delivery path and is the only decrement on a
10993
- * healthy stream. But a sample whose data units never complete is never
10994
- * delivered, and without this path its slot is held until `reset()` --
10995
- * making `maxPendingSamples` a one-way ratchet. Once it saturates,
10996
- * `addMovieFragment` rejects every subsequent moof and the stream is
10997
- * wedged permanently: the consumer sees media stop with no error, and only
10998
- * a full track reset clears it.
11680
+ * healthy stream. A sample whose data units never complete is never
11681
+ * delivered; window displacement in `addMovieFragment` eventually reclaims
11682
+ * it, but only after it has aged out of the whole window. This path frees
11683
+ * the slot as soon as the combiner knows the sample is gone, so the budget
11684
+ * tracks what is actually in flight rather than what has merely aged.
10999
11685
  *
11000
11686
  * The caller is whoever abandoned the sample, so the release is driven by
11001
11687
  * the abandonment itself rather than by a timer, an LRU, or an age bound --
@@ -11019,8 +11705,27 @@ var IsoBmffTimingResolver = class {
11019
11705
  _track = new WeakMap();
11020
11706
  _fragments = new WeakMap();
11021
11707
  _pendingSamples = new WeakMap();
11708
+ _evictedSamples = new WeakMap();
11022
11709
  _lastMovieFragmentRejection = new WeakMap();
11023
11710
  _IsoBmffTimingResolver_instances = new WeakSet();
11711
+ /**
11712
+ * Drop the oldest pending fragment whole and return the slots it held.
11713
+ *
11714
+ * Oldest is insertion order, which for a moof stream is arrival order, so
11715
+ * this is the least-recently-declared timing -- the entries least likely to
11716
+ * still have data units in flight.
11717
+ */
11718
+ evictOldestFragment_fn = function() {
11719
+ const oldest = __privateGet(this, _fragments).keys().next().value;
11720
+ if (oldest === void 0) return 0;
11721
+ const samples = __privateGet(this, _fragments).get(oldest);
11722
+ let live = 0;
11723
+ for (const sample of samples) if (sample !== null) live++;
11724
+ __privateGet(this, _fragments).delete(oldest);
11725
+ __privateSet(this, _pendingSamples, __privateGet(this, _pendingSamples) - live);
11726
+ __privateSet(this, _evictedSamples, __privateGet(this, _evictedSamples) + live);
11727
+ return live;
11728
+ };
11024
11729
  /** Null one slot, decrement the budget, and drop the fragment when empty. */
11025
11730
  clearSlot_fn = function(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) {
11026
11731
  if (!isU322(mpuSequenceNumber) || !isU322(movieFragmentSequenceNumber) || movieFragmentSequenceNumber === 0 || !isU322(sampleNumber) || sampleNumber === 0) {
@@ -11199,7 +11904,7 @@ function isFmp4Box(data) {
11199
11904
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
11200
11905
  return FMPU_BOX_TYPES.has(type);
11201
11906
  }
11202
- var _tracks, _defaultTrack, _reassembler, _sampleCombiners, _sampleCombinerOptions, _retiredSampleCombinerStats, _timingStreams, _maxPendingTimingSamples, _pendingTimingSamples, _reclaimedTimingSamples, _rejectedMovieFragments, _sequencers, _reorderWindow, _reassemblyPolicy, _frameCb, _initCb, _sourceSymbolCb, _trackFrameCbs, _reorderStats, _reliableMoqStartupGate, _disposed2, _MmtpContainerParser_instances, streamKey_fn2, sampleCombinerFor_fn, releaseTimingSlot_fn, dropSampleCombiner_fn, emitCombinedSample_fn, passReliableMoqStartupGate_fn, timingResolver_fn, dropTimingStream_fn, validateReassemblyPolicy_fn, buildFrameMeta_fn, sequencerFor_fn, flushSequencers_fn, emitFrame_fn2, _MmtpContainerParser_static, scanForKeyframe_fn, scanLengthPrefixedHevcForKeyframe_fn, scanAnnexBForKeyframe_fn;
11907
+ var _tracks, _defaultTrack, _reassembler, _sampleCombiners, _sampleCombinerOptions, _retiredSampleCombinerStats, _timingStreams, _maxPendingTimingSamples, _pendingTimingSamples, _reclaimedTimingSamples, _evictedTimingSamples, _rejectedMovieFragments, _sequencers, _reorderWindow, _reassemblyPolicy, _frameCb, _initCb, _sourceSymbolCb, _trackFrameCbs, _reorderStats, _reliableMoqStartupGate, _disposed2, _fedObjects, _feedOutcomes, _deferredFeedOutcomes, _lastOutcome, _lastOutcomeCount, _MmtpContainerParser_instances, streamKey_fn2, sampleCombinerFor_fn, releaseTimingSlot_fn, dropSampleCombiner_fn, countOutcome_fn, countDeferredOutcome_fn, drop_fn, feed_fn, emitCombinedSample_fn, passReliableMoqStartupGate_fn, timingResolver_fn, dropTimingStream_fn, validateReassemblyPolicy_fn, buildFrameMeta_fn, sequencerFor_fn, flushSequencers_fn, emitFrame_fn2, _MmtpContainerParser_static, scanForKeyframe_fn, scanLengthPrefixedHevcForKeyframe_fn, scanAnnexBForKeyframe_fn;
11203
11908
  var _MmtpContainerParser = class _MmtpContainerParser {
11204
11909
  constructor(config) {
11205
11910
  __privateAdd(this, _MmtpContainerParser_instances);
@@ -11233,6 +11938,7 @@ var _MmtpContainerParser = class _MmtpContainerParser {
11233
11938
  __privateAdd(this, _maxPendingTimingSamples);
11234
11939
  __privateAdd(this, _pendingTimingSamples, 0);
11235
11940
  __privateAdd(this, _reclaimedTimingSamples, 0);
11941
+ __privateAdd(this, _evictedTimingSamples, 0);
11236
11942
  __privateAdd(this, _rejectedMovieFragments, 0);
11237
11943
  __privateAdd(this, _sequencers, /* @__PURE__ */ new Map());
11238
11944
  __privateAdd(this, _reorderWindow, 0);
@@ -11259,6 +11965,11 @@ var _MmtpContainerParser = class _MmtpContainerParser {
11259
11965
  * reordering into the parser. */
11260
11966
  __privateAdd(this, _reliableMoqStartupGate, /* @__PURE__ */ new Map());
11261
11967
  __privateAdd(this, _disposed2, false);
11968
+ __privateAdd(this, _fedObjects, 0);
11969
+ __privateAdd(this, _feedOutcomes, /* @__PURE__ */ new Map());
11970
+ __privateAdd(this, _deferredFeedOutcomes, /* @__PURE__ */ new Map());
11971
+ __privateAdd(this, _lastOutcome, null);
11972
+ __privateAdd(this, _lastOutcomeCount, 0);
11262
11973
  /** Authored presentation timestamp of the last emitted frame, in microseconds. */
11263
11974
  this.lastFrameTimestamp = void 0;
11264
11975
  if (config?.reassemblyPolicy && config.mfuTimeoutMs !== void 0) {
@@ -11361,6 +12072,7 @@ var _MmtpContainerParser = class _MmtpContainerParser {
11361
12072
  pending: __privateGet(this, _pendingTimingSamples),
11362
12073
  capacity: __privateGet(this, _maxPendingTimingSamples),
11363
12074
  reclaimed: __privateGet(this, _reclaimedTimingSamples),
12075
+ evicted: __privateGet(this, _evictedTimingSamples),
11364
12076
  rejectedMovieFragments: __privateGet(this, _rejectedMovieFragments)
11365
12077
  };
11366
12078
  }
@@ -11369,6 +12081,36 @@ var _MmtpContainerParser = class _MmtpContainerParser {
11369
12081
  for (const { sequencer } of __privateGet(this, _sequencers).values()) bufferedFrames += sequencer.buffered;
11370
12082
  return { ...__privateGet(this, _reorderStats), bufferedFrames };
11371
12083
  }
12084
+ /**
12085
+ * Feed tallies for this parser. A fresh snapshot per call, not a live view,
12086
+ * so a caller can hold one and compare it against a later read.
12087
+ *
12088
+ * Survives dispose() — the counters are the parser's own state and are not
12089
+ * cleared by teardown, because a wedged receive path is usually read after
12090
+ * the fact.
12091
+ */
12092
+ get feedStats() {
12093
+ return {
12094
+ fedObjects: __privateGet(this, _fedObjects),
12095
+ outcomes: Object.fromEntries(__privateGet(this, _feedOutcomes)),
12096
+ deferredOutcomes: Object.fromEntries(__privateGet(this, _deferredFeedOutcomes))
12097
+ };
12098
+ }
12099
+ /**
12100
+ * Outcome token of the most recent feed(), or null before the first call.
12101
+ *
12102
+ * Exposed alongside `lastFeedOutcomeCount` as two scalars rather than one
12103
+ * object because a wrapper reads them on every packet, and feedStats()
12104
+ * allocates a fresh snapshot per call.
12105
+ */
12106
+ get lastFeedOutcome() {
12107
+ return __privateGet(this, _lastOutcome);
12108
+ }
12109
+ /** How many times `lastFeedOutcome` has now been seen. 1 on its first
12110
+ * occurrence, which is what a caller logging once per novel outcome needs. */
12111
+ get lastFeedOutcomeCount() {
12112
+ return __privateGet(this, _lastOutcomeCount);
12113
+ }
11372
12114
  get reorderDiagnostics() {
11373
12115
  const streams = [];
11374
12116
  for (const { packetId, sequencer } of __privateGet(this, _sequencers).values()) {
@@ -11418,181 +12160,16 @@ var _MmtpContainerParser = class _MmtpContainerParser {
11418
12160
  }
11419
12161
  /** Feed a complete MMTP packet. For two-phase use, call parseHeader() first. */
11420
12162
  feed(packet, options) {
11421
- var _a;
11422
- if (__privateGet(this, _disposed2)) return null;
11423
- this.cleanupTimeouts();
11424
- const info = this.parseHeader(packet, options);
11425
- if (!info) return null;
11426
- if (info.packetType !== PACKET_TYPE_MPU2) {
11427
- return {
11428
- kind: info.isRepair ? "repair" : "non-media",
11429
- packet: info,
11430
- byteLength: packet.byteLength
11431
- };
11432
- }
11433
- if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb)) {
11434
- const rawSymbol = packet.subarray(0, packet.length - 4);
11435
- const altaTrailer = extractAltaTrailer2(packet);
11436
- const alta = altaTrailer ? { auth: altaTrailer.auth, payloadEnd: altaTrailer.signedEnd } : void 0;
11437
- try {
11438
- __privateGet(this, _sourceSymbolCb).call(this, info.packetId, info.fecPayloadId.ssId, rawSymbol, alta);
11439
- } catch {
11440
- }
11441
- }
11442
- const extraction = extractMFUPayload(packet, {
11443
- skipFecId: options?.skipFecPayloadId
11444
- });
11445
- if (!extraction) return null;
11446
- const { mpu, fragmentType, data, mfuDuHeader } = extraction;
11447
- if (mpu.timedFlag !== 1) return null;
11448
- const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn2).call(this, info.packetId, options?.catalogTrackName);
11449
- if (fragmentType === 0) {
11450
- if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0) return null;
11451
- const normalizedInit = normalizeMmtpInitSegment(data);
11452
- if (!normalizedInit) return null;
11453
- const resolver2 = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, true);
11454
- if (!resolver2?.addInitialization(normalizedInit)) return null;
11455
- (_a = __privateGet(this, _initCb)) == null ? void 0 : _a.call(this, normalizedInit, info.packetId, options?.catalogTrackName);
11456
- return {
11457
- kind: "init",
11458
- packet: info,
11459
- data: normalizedInit,
11460
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11461
- fragmentationIndicator: mpu.fragmentationIndicator,
11462
- fragmentCounter: mpu.fragmentCounter
11463
- };
11464
- }
11465
- if (fragmentType === 1) {
11466
- if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0) return null;
11467
- const resolver2 = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, false);
11468
- if (!resolver2) return null;
11469
- const pendingBefore = resolver2.pendingSampleCount;
11470
- const remaining = __privateGet(this, _maxPendingTimingSamples) - __privateGet(this, _pendingTimingSamples);
11471
- if (!resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining)) {
11472
- if (resolver2.lastMovieFragmentRejection === "budget") {
11473
- __privateWrapper(this, _rejectedMovieFragments)._++;
11474
- }
11475
- return null;
11476
- }
11477
- __privateSet(this, _pendingTimingSamples, __privateGet(this, _pendingTimingSamples) + (resolver2.pendingSampleCount - pendingBefore));
11478
- return {
11479
- kind: "fragment",
11480
- packet: info,
11481
- data,
11482
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11483
- fragmentationIndicator: mpu.fragmentationIndicator,
11484
- fragmentCounter: mpu.fragmentCounter
11485
- };
11486
- }
11487
- if (fragmentType !== 2) return null;
11488
- const resolver = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, false);
11489
- if (!resolver) return null;
11490
- if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0) return null;
11491
- if (mpu.fragmentationIndicator === 0 || mpu.fragmentationIndicator === 1) {
11492
- if (!mfuDuHeader || mfuDuHeader.movieFragmentSequenceNumber === 0 || mfuDuHeader.sampleNumber === 0) {
11493
- return null;
11494
- }
11495
- const headTiming = resolver.sampleTiming(
11496
- mpu.mpuSequenceNumber,
11497
- mfuDuHeader.movieFragmentSequenceNumber,
11498
- mfuDuHeader.sampleNumber
11499
- );
11500
- if (!headTiming) return null;
11501
- const offset = mfuDuHeader.offset;
11502
- if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size) return null;
11503
- const remaining = headTiming.size - offset;
11504
- if (mpu.fragmentationIndicator === 0 && data.byteLength !== remaining) return null;
11505
- if (mpu.fragmentationIndicator === 1 && data.byteLength >= remaining) return null;
11506
- const readyOnRegister = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).registerAuthoredSize(
11507
- options?.catalogTrackName,
11508
- mpu.mpuSequenceNumber,
11509
- mfuDuHeader.movieFragmentSequenceNumber,
11510
- mfuDuHeader.sampleNumber,
11511
- headTiming.size
11512
- );
11513
- if (readyOnRegister) {
11514
- __privateMethod(this, _MmtpContainerParser_instances, emitCombinedSample_fn).call(this, readyOnRegister, info, resolver, options?.recovered === true);
11515
- }
11516
- }
11517
- let assembled;
11518
- try {
11519
- assembled = __privateGet(this, _reassembler).addFragment({
11520
- fragmentationIndicator: mpu.fragmentationIndicator,
11521
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11522
- fragmentCounter: mpu.fragmentCounter,
11523
- data,
11524
- timestamp: info.timestamp,
11525
- rapFlag: info.rapFlag,
11526
- priority: mfuDuHeader?.priority,
11527
- sampleNumber: mfuDuHeader?.sampleNumber,
11528
- movieFragmentSequenceNumber: mfuDuHeader?.movieFragmentSequenceNumber,
11529
- sampleOffset: mfuDuHeader?.offset,
11530
- packetSequenceNumber: info.sequenceNumber,
11531
- recovered: options?.recovered === true,
11532
- source: options?.source,
11533
- deliveryProvenance: options?.deliveryProvenance,
11534
- catalogTrackName: options?.catalogTrackName,
11535
- packetId: info.packetId
11536
- });
11537
- } catch (error) {
11538
- if (!isMfuReassemblyError(error)) throw error;
11539
- console.warn(
11540
- `[MmtpContainerParser] rejected MFU fragment: code=${error.code} mpu=${mpu.mpuSequenceNumber} fi=${mpu.fragmentationIndicator} counter=${mpu.fragmentCounter}`
11541
- );
11542
- return {
11543
- kind: "rejected",
11544
- packet: info,
11545
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11546
- fragmentationIndicator: mpu.fragmentationIndicator,
11547
- fragmentCounter: mpu.fragmentCounter,
11548
- error: { code: error.code, message: error.message }
11549
- };
11550
- }
11551
- if (!assembled) {
11552
- return {
11553
- kind: "pending",
11554
- packet: info,
11555
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11556
- fragmentationIndicator: mpu.fragmentationIndicator,
11557
- fragmentCounter: mpu.fragmentCounter
11558
- };
11559
- }
11560
- const movieFragmentSequenceNumber = assembled.movieFragmentSequenceNumber;
11561
- const sampleNumber = assembled.sampleNumber;
11562
- if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0) return null;
11563
- if (!resolver.sampleTiming(
11564
- assembled.mpuSequenceNumber,
11565
- movieFragmentSequenceNumber,
11566
- sampleNumber
11567
- )) return null;
11568
- if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber) return null;
11569
- let combined;
12163
+ __privateSet(this, _fedObjects, __privateGet(this, _fedObjects) + 1);
12164
+ let record;
11570
12165
  try {
11571
- combined = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).addMfu(assembled);
12166
+ record = __privateMethod(this, _MmtpContainerParser_instances, feed_fn).call(this, packet, options);
11572
12167
  } catch (error) {
11573
- if (!(error instanceof SampleCombineError)) throw error;
11574
- console.warn(
11575
- `[MmtpContainerParser] rejected subsample data unit: code=${error.code} mpu=${assembled.mpuSequenceNumber} sample=${sampleNumber} offset=${assembled.sampleOffset ?? 0}`
11576
- );
11577
- return {
11578
- kind: "rejected",
11579
- packet: info,
11580
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11581
- fragmentationIndicator: mpu.fragmentationIndicator,
11582
- fragmentCounter: mpu.fragmentCounter,
11583
- error: { code: error.code, message: error.message }
11584
- };
11585
- }
11586
- if (!combined) {
11587
- return {
11588
- kind: "pending",
11589
- packet: info,
11590
- mpuSequenceNumber: mpu.mpuSequenceNumber,
11591
- fragmentationIndicator: mpu.fragmentationIndicator,
11592
- fragmentCounter: mpu.fragmentCounter
11593
- };
12168
+ __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, "drop:threw");
12169
+ throw error;
11594
12170
  }
11595
- return __privateMethod(this, _MmtpContainerParser_instances, emitCombinedSample_fn).call(this, combined, info, resolver, options?.recovered === true);
12171
+ if (record) __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, record.kind);
12172
+ return record;
11596
12173
  }
11597
12174
  onInit(cb) {
11598
12175
  __privateSet(this, _initCb, cb);
@@ -11760,6 +12337,7 @@ _timingStreams = new WeakMap();
11760
12337
  _maxPendingTimingSamples = new WeakMap();
11761
12338
  _pendingTimingSamples = new WeakMap();
11762
12339
  _reclaimedTimingSamples = new WeakMap();
12340
+ _evictedTimingSamples = new WeakMap();
11763
12341
  _rejectedMovieFragments = new WeakMap();
11764
12342
  _sequencers = new WeakMap();
11765
12343
  _reorderWindow = new WeakMap();
@@ -11771,6 +12349,11 @@ _trackFrameCbs = new WeakMap();
11771
12349
  _reorderStats = new WeakMap();
11772
12350
  _reliableMoqStartupGate = new WeakMap();
11773
12351
  _disposed2 = new WeakMap();
12352
+ _fedObjects = new WeakMap();
12353
+ _feedOutcomes = new WeakMap();
12354
+ _deferredFeedOutcomes = new WeakMap();
12355
+ _lastOutcome = new WeakMap();
12356
+ _lastOutcomeCount = new WeakMap();
11774
12357
  _MmtpContainerParser_instances = new WeakSet();
11775
12358
  streamKey_fn2 = function(packetId, catalogTrackName) {
11776
12359
  return JSON.stringify([packetId, catalogTrackName ?? null]);
@@ -11789,12 +12372,12 @@ sampleCombinerFor_fn = function(streamKey) {
11789
12372
  /**
11790
12373
  * Return the timing budget slot of a sample the combiner abandoned.
11791
12374
  *
11792
- * Without this, `#pendingTimingSamples` is a one-way ratchet: it is charged
11793
- * for every sample a moof declares but credited only when that sample is
11794
- * delivered, so each sample lost to eviction or timeout permanently burns a
11795
- * slot. At saturation `addMovieFragment` rejects every subsequent moof and
11796
- * every FT=2 data unit is dropped -- media stops with no error surfaced and
11797
- * nothing short of a track reset recovers.
12375
+ * Without this, `#pendingTimingSamples` is charged for every sample a moof
12376
+ * declares but credited only when that sample is delivered, so each sample
12377
+ * lost to eviction or timeout burns a slot until the window displaces it.
12378
+ * Window displacement bounds that leak but only reclaims the OLDEST entries;
12379
+ * this path returns a slot the moment the combiner knows the sample is gone,
12380
+ * which keeps the live window as wide as the stream actually needs.
11798
12381
  *
11799
12382
  * The parser total is decremented only when the resolver reports it
11800
12383
  * actually freed a slot, so a resolver already dropped by a track reset, or
@@ -11826,11 +12409,232 @@ dropSampleCombiner_fn = function(streamKey) {
11826
12409
  __privateGet(this, _retiredSampleCombinerStats).evictedSamples += stats.evictedSamples;
11827
12410
  __privateGet(this, _sampleCombiners).delete(streamKey);
11828
12411
  };
12412
+ countOutcome_fn = function(token) {
12413
+ const count = (__privateGet(this, _feedOutcomes).get(token) ?? 0) + 1;
12414
+ __privateGet(this, _feedOutcomes).set(token, count);
12415
+ __privateSet(this, _lastOutcome, token);
12416
+ __privateSet(this, _lastOutcomeCount, count);
12417
+ };
12418
+ countDeferredOutcome_fn = function(reason) {
12419
+ __privateGet(this, _deferredFeedOutcomes).set(
12420
+ reason,
12421
+ (__privateGet(this, _deferredFeedOutcomes).get(reason) ?? 0) + 1
12422
+ );
12423
+ };
12424
+ /**
12425
+ * Count a feed() drop and return null in one expression, so every early
12426
+ * return inside feed() states the reason it took instead of collapsing into
12427
+ * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
12428
+ */
12429
+ drop_fn = function(reason) {
12430
+ __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, `drop:${reason}`);
12431
+ return null;
12432
+ };
12433
+ feed_fn = function(packet, options) {
12434
+ var _a;
12435
+ if (__privateGet(this, _disposed2)) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "disposed");
12436
+ this.cleanupTimeouts();
12437
+ const info = this.parseHeader(packet, options);
12438
+ if (!info) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "header-parse-failed");
12439
+ if (info.packetType !== PACKET_TYPE_MPU2) {
12440
+ return {
12441
+ kind: info.isRepair ? "repair" : "non-media",
12442
+ packet: info,
12443
+ byteLength: packet.byteLength
12444
+ };
12445
+ }
12446
+ if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb)) {
12447
+ const rawSymbol = packet.subarray(0, packet.length - 4);
12448
+ const altaTrailer = extractAltaTrailer2(packet);
12449
+ const alta = altaTrailer ? { auth: altaTrailer.auth, payloadEnd: altaTrailer.signedEnd } : void 0;
12450
+ try {
12451
+ __privateGet(this, _sourceSymbolCb).call(this, info.packetId, info.fecPayloadId.ssId, rawSymbol, alta);
12452
+ } catch {
12453
+ }
12454
+ }
12455
+ const extraction = extractMFUPayload(packet, {
12456
+ skipFecId: options?.skipFecPayloadId
12457
+ });
12458
+ if (!extraction) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-extract-failed");
12459
+ const { mpu, fragmentType, data, mfuDuHeader } = extraction;
12460
+ if (mpu.timedFlag !== 1) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "untimed-mpu");
12461
+ const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn2).call(this, info.packetId, options?.catalogTrackName);
12462
+ if (fragmentType === 0) {
12463
+ if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
12464
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "init-unexpected-fragmentation");
12465
+ const normalizedInit = normalizeMmtpInitSegment(data);
12466
+ if (!normalizedInit) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "init-normalize-failed");
12467
+ const resolver2 = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, true);
12468
+ if (!resolver2?.addInitialization(normalizedInit)) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "init-timing-refused");
12469
+ (_a = __privateGet(this, _initCb)) == null ? void 0 : _a.call(this, normalizedInit, info.packetId, options?.catalogTrackName);
12470
+ return {
12471
+ kind: "init",
12472
+ packet: info,
12473
+ data: normalizedInit,
12474
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12475
+ fragmentationIndicator: mpu.fragmentationIndicator,
12476
+ fragmentCounter: mpu.fragmentCounter
12477
+ };
12478
+ }
12479
+ if (fragmentType === 1) {
12480
+ if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
12481
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-unexpected-fragmentation");
12482
+ const resolver2 = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, false);
12483
+ if (!resolver2) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-no-resolver");
12484
+ const pendingBefore = resolver2.pendingSampleCount;
12485
+ const evictedBefore = resolver2.evictedSampleCount;
12486
+ const remaining = __privateGet(this, _maxPendingTimingSamples) - __privateGet(this, _pendingTimingSamples);
12487
+ const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
12488
+ __privateSet(this, _pendingTimingSamples, __privateGet(this, _pendingTimingSamples) + (resolver2.pendingSampleCount - pendingBefore));
12489
+ __privateSet(this, _evictedTimingSamples, __privateGet(this, _evictedTimingSamples) + (resolver2.evictedSampleCount - evictedBefore));
12490
+ if (!admitted) {
12491
+ if (resolver2.lastMovieFragmentRejection === "budget") {
12492
+ __privateWrapper(this, _rejectedMovieFragments)._++;
12493
+ }
12494
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-timing-refused");
12495
+ }
12496
+ return {
12497
+ kind: "fragment",
12498
+ packet: info,
12499
+ data,
12500
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12501
+ fragmentationIndicator: mpu.fragmentationIndicator,
12502
+ fragmentCounter: mpu.fragmentCounter
12503
+ };
12504
+ }
12505
+ if (fragmentType !== 2) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "unknown-fragment-type");
12506
+ const resolver = __privateMethod(this, _MmtpContainerParser_instances, timingResolver_fn).call(this, streamKey, info.packetId, false);
12507
+ if (!resolver) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-no-resolver");
12508
+ if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
12509
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-empty-payload");
12510
+ if (mpu.fragmentationIndicator === 0 || mpu.fragmentationIndicator === 1) {
12511
+ if (!mfuDuHeader || mfuDuHeader.movieFragmentSequenceNumber === 0 || mfuDuHeader.sampleNumber === 0) {
12512
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-du-header-missing");
12513
+ }
12514
+ const headTiming = resolver.sampleTiming(
12515
+ mpu.mpuSequenceNumber,
12516
+ mfuDuHeader.movieFragmentSequenceNumber,
12517
+ mfuDuHeader.sampleNumber
12518
+ );
12519
+ if (!headTiming) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-sample-timing-missing");
12520
+ const offset = mfuDuHeader.offset;
12521
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
12522
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-offset-out-of-range");
12523
+ const remaining = headTiming.size - offset;
12524
+ if (mpu.fragmentationIndicator === 0 && data.byteLength !== remaining)
12525
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-size-mismatch");
12526
+ if (mpu.fragmentationIndicator === 1 && data.byteLength >= remaining)
12527
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-size-mismatch");
12528
+ const readyOnRegister = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).registerAuthoredSize(
12529
+ options?.catalogTrackName,
12530
+ mpu.mpuSequenceNumber,
12531
+ mfuDuHeader.movieFragmentSequenceNumber,
12532
+ mfuDuHeader.sampleNumber,
12533
+ headTiming.size
12534
+ );
12535
+ if (readyOnRegister) {
12536
+ const deferred = __privateMethod(this, _MmtpContainerParser_instances, emitCombinedSample_fn).call(this, readyOnRegister, info, resolver, options?.recovered === true);
12537
+ if (deferred.record === void 0) __privateMethod(this, _MmtpContainerParser_instances, countDeferredOutcome_fn).call(this, deferred.reason);
12538
+ }
12539
+ }
12540
+ let assembled;
12541
+ try {
12542
+ assembled = __privateGet(this, _reassembler).addFragment({
12543
+ fragmentationIndicator: mpu.fragmentationIndicator,
12544
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12545
+ fragmentCounter: mpu.fragmentCounter,
12546
+ data,
12547
+ timestamp: info.timestamp,
12548
+ rapFlag: info.rapFlag,
12549
+ priority: mfuDuHeader?.priority,
12550
+ sampleNumber: mfuDuHeader?.sampleNumber,
12551
+ movieFragmentSequenceNumber: mfuDuHeader?.movieFragmentSequenceNumber,
12552
+ sampleOffset: mfuDuHeader?.offset,
12553
+ packetSequenceNumber: info.sequenceNumber,
12554
+ recovered: options?.recovered === true,
12555
+ source: options?.source,
12556
+ deliveryProvenance: options?.deliveryProvenance,
12557
+ catalogTrackName: options?.catalogTrackName,
12558
+ packetId: info.packetId
12559
+ });
12560
+ } catch (error) {
12561
+ if (!isMfuReassemblyError(error)) throw error;
12562
+ console.warn(
12563
+ `[MmtpContainerParser] rejected MFU fragment: code=${error.code} mpu=${mpu.mpuSequenceNumber} fi=${mpu.fragmentationIndicator} counter=${mpu.fragmentCounter}`
12564
+ );
12565
+ return {
12566
+ kind: "rejected",
12567
+ packet: info,
12568
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12569
+ fragmentationIndicator: mpu.fragmentationIndicator,
12570
+ fragmentCounter: mpu.fragmentCounter,
12571
+ error: { code: error.code, message: error.message }
12572
+ };
12573
+ }
12574
+ if (!assembled) {
12575
+ return {
12576
+ kind: "pending",
12577
+ packet: info,
12578
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12579
+ fragmentationIndicator: mpu.fragmentationIndicator,
12580
+ fragmentCounter: mpu.fragmentCounter
12581
+ };
12582
+ }
12583
+ const movieFragmentSequenceNumber = assembled.movieFragmentSequenceNumber;
12584
+ const sampleNumber = assembled.sampleNumber;
12585
+ if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
12586
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-identity-missing");
12587
+ if (!resolver.sampleTiming(
12588
+ assembled.mpuSequenceNumber,
12589
+ movieFragmentSequenceNumber,
12590
+ sampleNumber
12591
+ )) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-timing-missing");
12592
+ if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
12593
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-mpu-mismatch");
12594
+ let combined;
12595
+ try {
12596
+ combined = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).addMfu(assembled);
12597
+ } catch (error) {
12598
+ if (!(error instanceof SampleCombineError)) throw error;
12599
+ console.warn(
12600
+ `[MmtpContainerParser] rejected subsample data unit: code=${error.code} mpu=${assembled.mpuSequenceNumber} sample=${sampleNumber} offset=${assembled.sampleOffset ?? 0}`
12601
+ );
12602
+ return {
12603
+ kind: "rejected",
12604
+ packet: info,
12605
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12606
+ fragmentationIndicator: mpu.fragmentationIndicator,
12607
+ fragmentCounter: mpu.fragmentCounter,
12608
+ error: { code: error.code, message: error.message }
12609
+ };
12610
+ }
12611
+ if (!combined) {
12612
+ return {
12613
+ kind: "pending",
12614
+ packet: info,
12615
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
12616
+ fragmentationIndicator: mpu.fragmentationIndicator,
12617
+ fragmentCounter: mpu.fragmentCounter
12618
+ };
12619
+ }
12620
+ const outcome = __privateMethod(this, _MmtpContainerParser_instances, emitCombinedSample_fn).call(this, combined, info, resolver, options?.recovered === true);
12621
+ if (outcome.record !== void 0) return outcome.record;
12622
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, outcome.reason);
12623
+ };
11829
12624
  /**
11830
12625
  * Deliver one combined sample: resolve its authored timing, build frame
11831
12626
  * metadata, retire the timing entry, and route it. Shared by the ordinary
11832
12627
  * completion path and by the rarer completion that falls out of registering
11833
12628
  * an authored size for data units that arrived before it.
12629
+ *
12630
+ * Reports a refusal as a reason rather than counting it, because the two
12631
+ * call sites owe different accounting. On `#feed()`'s tail return the
12632
+ * refusal *is* that feed()'s outcome and must be attributed; on the
12633
+ * register-completion path it belongs to an earlier sample while this
12634
+ * packet's own fragment continues to its own outcome, so counting it there
12635
+ * would push `outcomes` past `fedObjects` — the very invariant the
12636
+ * attribution exists to keep readable. Leaving the choice at the call site
12637
+ * is what keeps both true.
11834
12638
  */
11835
12639
  emitCombinedSample_fn = function(combined, info, resolver, recovered) {
11836
12640
  const timing = resolver.sampleTiming(
@@ -11838,27 +12642,29 @@ emitCombinedSample_fn = function(combined, info, resolver, recovered) {
11838
12642
  combined.movieFragmentSequenceNumber,
11839
12643
  combined.sampleNumber
11840
12644
  );
11841
- if (!timing) return null;
11842
- if (combined.data.byteLength !== timing.size) return null;
12645
+ if (!timing) return { reason: "combined-timing-missing" };
12646
+ if (combined.data.byteLength !== timing.size) return { reason: "combined-size-mismatch" };
11843
12647
  const meta = __privateMethod(this, _MmtpContainerParser_instances, buildFrameMeta_fn).call(this, combined, info.packetId, info.sequenceNumber, timing, recovered);
11844
- if (!meta) return null;
12648
+ if (!meta) return { reason: "combined-meta-build-failed" };
11845
12649
  if (!resolver.consumeSample(
11846
12650
  combined.mpuSequenceNumber,
11847
12651
  combined.movieFragmentSequenceNumber,
11848
12652
  combined.sampleNumber,
11849
12653
  timing
11850
- )) return null;
12654
+ )) return { reason: "combined-timing-consume-refused" };
11851
12655
  __privateWrapper(this, _pendingTimingSamples)._--;
11852
12656
  this.routeFrame(combined.data, meta);
11853
12657
  return {
11854
- kind: "frame",
11855
- packet: info,
11856
- data: combined.data,
11857
- meta,
11858
- mpuSequenceNumber: combined.mpuSequenceNumber,
11859
- fragmentCount: combined.fragmentCount,
11860
- rapFlag: combined.rapFlag,
11861
- ...combined.priority === void 0 ? {} : { priority: combined.priority }
12658
+ record: {
12659
+ kind: "frame",
12660
+ packet: info,
12661
+ data: combined.data,
12662
+ meta,
12663
+ mpuSequenceNumber: combined.mpuSequenceNumber,
12664
+ fragmentCount: combined.fragmentCount,
12665
+ rapFlag: combined.rapFlag,
12666
+ ...combined.priority === void 0 ? {} : { priority: combined.priority }
12667
+ }
11862
12668
  };
11863
12669
  };
11864
12670
  /** Order-independent reliable-moq startup gate: discard delta frames for a
@@ -11951,7 +12757,7 @@ buildFrameMeta_fn = function(assembled, packetId, seq, timing, recovered = false
11951
12757
  }
11952
12758
  return meta;
11953
12759
  };
11954
- sequencerFor_fn = function(packetId, _trackType, catalogTrackName) {
12760
+ sequencerFor_fn = function(packetId, _trackType2, catalogTrackName) {
11955
12761
  const windowSize = __privateGet(this, _reassemblyPolicy) ? mmtpFrameReorderWindowFrames(__privateGet(this, _reassemblyPolicy), __privateGet(this, _reorderWindow)) : __privateGet(this, _reorderWindow);
11956
12762
  if (windowSize <= 0) return null;
11957
12763
  const streamKey = __privateMethod(this, _MmtpContainerParser_instances, streamKey_fn2).call(this, packetId, catalogTrackName);
@@ -13683,7 +14489,7 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13683
14489
  let dedupedAgainstSource2 = 0;
13684
14490
  let droppedBeforeSync2 = 0;
13685
14491
  for (const sym of result.symbols) {
13686
- if (sym.fragmentType === 0) continue;
14492
+ if (sym.fragmentType === 0 || sym.fragmentType === 1) continue;
13687
14493
  const fi = sym.fragment.fragmentationIndicator;
13688
14494
  if (fi === 0) {
13689
14495
  if (__privateGet(this, _sourcePktSeqs).has(
@@ -13693,6 +14499,7 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13693
14499
  continue;
13694
14500
  }
13695
14501
  const keyframe = isVideoTrack ? __privateMethod(this, _MmtpRouter_instances, detectKeyframe_fn).call(this, ownerPacketId, sym.fragment.data, isMfuKeyframeMetadata2(sym.fragment.rapFlag, sym.fragment.priority)) : sym.fragment.rapFlag;
14502
+ const sourceDiscontinuity = __privateMethod(this, _MmtpRouter_instances, opensFecSync_fn).call(this, ownerPacketId, keyframe, catalogTrackName);
13696
14503
  if (!__privateMethod(this, _MmtpRouter_instances, shouldEmitFrame_fn).call(this, ownerPacketId, keyframe, catalogTrackName)) {
13697
14504
  droppedBeforeSync2++;
13698
14505
  continue;
@@ -13717,7 +14524,8 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13717
14524
  // reassembler fold (`assembled.deliveryProvenance`); this branch
13718
14525
  // never touches the reassembler, so it must carry the block-level
13719
14526
  // verdict directly or the sample reaches MSE unattributed.
13720
- deliveryProvenance
14527
+ deliveryProvenance,
14528
+ ...sourceDiscontinuity ? { sourceDiscontinuity: true } : {}
13721
14529
  });
13722
14530
  __privateMethod(this, _MmtpRouter_instances, noteEmittedKeyframe_fn).call(this, ownerPacketId, keyframe);
13723
14531
  } else {
@@ -13758,11 +14566,12 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13758
14566
  }
13759
14567
  if (assembled) {
13760
14568
  const keyframe = isVideoTrack ? __privateMethod(this, _MmtpRouter_instances, detectKeyframe_fn).call(this, ownerPacketId, assembled.data, isMfuKeyframeMetadata2(assembled.rapFlag, assembled.priority)) : assembled.rapFlag;
13761
- if (!__privateMethod(this, _MmtpRouter_instances, shouldEmitFrame_fn).call(this, ownerPacketId, keyframe, assembled.catalogTrackName)) {
14569
+ const recoveredCatalogTrackName = assembled.catalogTrackName ?? catalogTrackName;
14570
+ const sourceDiscontinuity = __privateMethod(this, _MmtpRouter_instances, opensFecSync_fn).call(this, ownerPacketId, keyframe, recoveredCatalogTrackName);
14571
+ if (!__privateMethod(this, _MmtpRouter_instances, shouldEmitFrame_fn).call(this, ownerPacketId, keyframe, recoveredCatalogTrackName)) {
13762
14572
  droppedBeforeSync2++;
13763
14573
  continue;
13764
14574
  }
13765
- const recoveredCatalogTrackName = assembled.catalogTrackName ?? catalogTrackName;
13766
14575
  const recoveredTiming = __privateMethod(this, _MmtpRouter_instances, resolveRecoveredTiming_fn).call(this, ownerPacketId, assembled.mpuSequenceNumber, assembled.movieFragmentSequenceNumber, assembled.sampleNumber, assembled.timestamp, recoveredCatalogTrackName);
13767
14576
  if (!recoveredTiming) continue;
13768
14577
  frames.push({
@@ -13782,7 +14591,8 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13782
14591
  ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
13783
14592
  ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
13784
14593
  ...assembled.catalogTrackName === void 0 ? {} : { catalogTrackName: assembled.catalogTrackName },
13785
- deliveryProvenance: assembled.deliveryProvenance
14594
+ deliveryProvenance: assembled.deliveryProvenance,
14595
+ ...sourceDiscontinuity ? { sourceDiscontinuity: true } : {}
13786
14596
  });
13787
14597
  __privateMethod(this, _MmtpRouter_instances, noteEmittedKeyframe_fn).call(this, ownerPacketId, keyframe);
13788
14598
  }
@@ -13790,6 +14600,26 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13790
14600
  }
13791
14601
  if (frames.length > 0) {
13792
14602
  assembler.addRecoveredBlock(blockId, frames);
14603
+ const cb2 = __privateMethod(this, _MmtpRouter_instances, getFrameCallback_fn).call(this, ownerPacketId);
14604
+ for (const frame of frames) {
14605
+ cb2?.(frame.data, {
14606
+ timestamp: frame.timestamp,
14607
+ ...frame.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: frame.mmtpTimestamp },
14608
+ keyframe: frame.keyframe,
14609
+ ...frame.authoredTiming === void 0 ? {} : { authoredTiming: frame.authoredTiming },
14610
+ packetId: ownerPacketId,
14611
+ ...frame.packetSequenceNumber === void 0 ? {} : { packetSequenceNumber: frame.packetSequenceNumber },
14612
+ ...frame.packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers: frame.packetSequenceNumbers },
14613
+ ...frame.repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers: frame.repairedPacketSequenceNumbers },
14614
+ ...frame.mpuSequenceNumber === void 0 ? {} : { mpuSequenceNumber: frame.mpuSequenceNumber },
14615
+ ...frame.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: frame.movieFragmentSequenceNumber },
14616
+ ...frame.sampleNumber === void 0 ? {} : { sampleNumber: frame.sampleNumber },
14617
+ ...frame.catalogTrackName === void 0 ? {} : { catalogTrackName: frame.catalogTrackName },
14618
+ recovered: true,
14619
+ deliveryProvenance: frame.deliveryProvenance,
14620
+ ...frame.sourceDiscontinuity ? { sourceDiscontinuity: true } : {}
14621
+ });
14622
+ }
13793
14623
  debugRouter(
13794
14624
  `[MmtpRouter] Block ${blockId}: ${result.symbols.length} symbols \u2192 ${frames.length} reassembled frames \u2192 MSE assembler (packetId=${ownerPacketId}, dedupedAgainstSource=${dedupedAgainstSource2}, droppedBeforeSync=${droppedBeforeSync2})`
13795
14625
  );
@@ -13806,7 +14636,7 @@ routeProcessedFecSymbols_fn = function(blockId, result, ownerPacketId, catalogTr
13806
14636
  let droppedStale = 0;
13807
14637
  let dedupedAgainstSource = 0;
13808
14638
  for (const sym of result.symbols) {
13809
- if (sym.fragmentType === 0) continue;
14639
+ if (sym.fragmentType === 0 || sym.fragmentType === 1) continue;
13810
14640
  if (isVideo) {
13811
14641
  const fi = sym.fragment.fragmentationIndicator;
13812
14642
  if (fi === 0) {
@@ -14135,7 +14965,7 @@ refreshStats_fn = function() {
14135
14965
  this.stats.reassembledMFUs = asNumber(stats.reassembled_mfus);
14136
14966
  this.stats.rejectedFragments = __privateGet(this, _rejectedFragments);
14137
14967
  this.stats.timedOutMFUs = asNumber(stats.timed_out_mfus);
14138
- this.stats.evictedMemoryLimit = asNumber(stats.evicted_memory_limit);
14968
+ this.stats.evictedMemoryLimit = asNumber(stats.evicted_memory_limit) + asNumber(stats.evicted_data_units ?? 0);
14139
14969
  this.stats.outOfOrderFragments = asNumber(stats.out_of_order_fragments);
14140
14970
  stats.free?.();
14141
14971
  };
@@ -14245,106 +15075,1431 @@ var ReedSolomonCodec = class {
14245
15075
  }
14246
15076
  };
14247
15077
 
14248
- // src/multicast-transport.ts
14249
- var MAX_TRACKED_DROPPED_PIDS = 16;
14250
- function getMulticastGlobals() {
14251
- return globalThis;
14252
- }
14253
- function hasMulticastGateway() {
14254
- return typeof getMulticastGlobals().multicast?.subscribe === "function";
14255
- }
14256
- function normalizeResolvedTransport(value) {
14257
- if (value === "native") return "native";
14258
- if (value === "amt") return "amt";
14259
- return void 0;
14260
- }
14261
- 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;
14262
- var _MulticastTransport = class _MulticastTransport {
14263
- constructor(onPacket) {
14264
- __privateAdd(this, _MulticastTransport_instances);
14265
- __privateAdd(this, _onPacket);
14266
- __privateAdd(this, _subscription2, null);
14267
- __privateAdd(this, _bytesListener, null);
14268
- __privateAdd(this, _transportListener, null);
14269
- __privateAdd(this, _resolvedTransport);
14270
- __privateAdd(this, _videoConfirmed, false);
14271
- __privateAdd(this, _audioConfirmed, false);
14272
- __privateAdd(this, _watchdog, null);
14273
- __privateAdd(this, _failbackWindowMs, null);
14274
- __privateAdd(this, _onTakeover, null);
14275
- __privateAdd(this, _onFailback, null);
14276
- __privateAdd(this, _disposed4, false);
14277
- __privateAdd(this, _stats3, {
14278
- packetsReceived: 0,
14279
- bytesReceived: 0,
14280
- packetsDroppedUnregisteredPid: 0,
14281
- packetsDroppedUnparseable: 0
14282
- });
14283
- __privateAdd(this, _droppedPidCounts, /* @__PURE__ */ new Map());
14284
- __privateAdd(this, _packetIds, null);
14285
- __privateAdd(this, _joinGeneration, 0);
14286
- __privateSet(this, _onPacket, onPacket);
15078
+ // node_modules/@blockcast/mmt-transport/dist/types.js
15079
+ var MoqFecAlgorithm;
15080
+ (function(MoqFecAlgorithm2) {
15081
+ MoqFecAlgorithm2[MoqFecAlgorithm2["None"] = 0] = "None";
15082
+ MoqFecAlgorithm2[MoqFecAlgorithm2["Xor"] = 1] = "Xor";
15083
+ MoqFecAlgorithm2[MoqFecAlgorithm2["RaptorQ"] = 2] = "RaptorQ";
15084
+ })(MoqFecAlgorithm || (MoqFecAlgorithm = {}));
15085
+
15086
+ // node_modules/@blockcast/mmt-transport/dist/driad-discovery.js
15087
+ var DRIADDiscovery = class {
15088
+ constructor() {
15089
+ __publicField(this, "cache", /* @__PURE__ */ new Map());
15090
+ __publicField(this, "cacheExpiry", 3e5);
14287
15091
  }
14288
- static isAvailable() {
14289
- return hasMulticastGateway();
15092
+ // 5 minutes
15093
+ /**
15094
+ * Discover AMT relays for a multicast source address (RFC 8777)
15095
+ *
15096
+ * @param source - The multicast source IP address (NOT the group!)
15097
+ * @returns Array of discovered AMT relays that can tunnel traffic from this source
15098
+ */
15099
+ async discoverRelays(source) {
15100
+ const cached = this.cache.get(source);
15101
+ if (cached) {
15102
+ return cached;
15103
+ }
15104
+ try {
15105
+ const reversedSource = source.split(".").reverse().join(".");
15106
+ const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
15107
+ console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
15108
+ const relays = await this.queryDRIADProxy(source);
15109
+ if (relays.length > 0) {
15110
+ this.cache.set(source, relays);
15111
+ setTimeout(() => this.cache.delete(source), this.cacheExpiry);
15112
+ }
15113
+ return relays;
15114
+ } catch (error) {
15115
+ console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
15116
+ return [];
15117
+ }
14290
15118
  }
14291
- async join(config, context) {
14292
- const generation = ++__privateWrapper(this, _joinGeneration)._;
14293
- __privateMethod(this, _MulticastTransport_instances, releaseSubscription_fn).call(this);
14294
- if (__privateGet(this, _disposed4)) return false;
14295
- if (!_MulticastTransport.isAvailable()) {
14296
- console.warn("[MulticastTransport] Multicast API not available");
14297
- return false;
15119
+ /**
15120
+ * Query DRIAD proxy service (browser-compatible)
15121
+ */
15122
+ async queryDRIADProxy(source) {
15123
+ const proxyEndpoints = [
15124
+ "https://driad.amt.net/api/v1/relays",
15125
+ "https://multicast-gateway.cloudflare.com/driad"
15126
+ ];
15127
+ for (const endpoint of proxyEndpoints) {
15128
+ try {
15129
+ const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
15130
+ method: "GET",
15131
+ headers: { Accept: "application/json" },
15132
+ signal: AbortSignal.timeout(5e3)
15133
+ });
15134
+ if (response.ok) {
15135
+ const data = await response.json();
15136
+ return data.relays || [];
15137
+ }
15138
+ } catch {
15139
+ }
15140
+ }
15141
+ const dohRelay = await this.queryDNSOverHTTPS(source);
15142
+ if (dohRelay) {
15143
+ return [dohRelay];
14298
15144
  }
15145
+ return [];
15146
+ }
15147
+ /**
15148
+ * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
15149
+ */
15150
+ async queryDNSOverHTTPS(source) {
14299
15151
  try {
14300
- const packetIds = config.packetIds?.length ? new Set(config.packetIds) : null;
14301
- console.log(
14302
- `[MulticastTransport] window.multicast.subscribe(${config.sourceAddress}, ${config.groupAddress}, ${config.port})`
14303
- );
14304
- const subscription = await getMulticastGlobals().multicast.subscribe({
14305
- source: config.sourceAddress,
14306
- group: config.groupAddress,
14307
- port: config.port,
14308
- consume: "bytes",
14309
- mode: config.mode,
14310
- amtRelay: config.amtRelay,
14311
- amtRelayPort: config.amtRelayPort,
14312
- packetIds: config.packetIds,
14313
- tracks: config.tracks?.map(({ name, packetId }) => ({ name, packetId }))
15152
+ const reversedSource = source.split(".").reverse().join(".");
15153
+ const queryName = `${reversedSource}.amt.in-addr.arpa`;
15154
+ const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
15155
+ const response = await fetch(dohUrl, {
15156
+ headers: { Accept: "application/dns-json" },
15157
+ signal: AbortSignal.timeout(3e3)
14314
15158
  });
14315
- console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
14316
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) {
14317
- void subscription.unsubscribe();
14318
- return false;
15159
+ if (!response.ok) {
15160
+ return null;
14319
15161
  }
14320
- if (typeof subscription.addEventListener !== "function") {
14321
- if (typeof subscription.unsubscribe === "function") {
14322
- void subscription.unsubscribe();
14323
- }
14324
- throw new Error("window.multicast subscription does not support bytes events");
15162
+ const result = await response.json();
15163
+ if (result.Answer && result.Answer.length > 0) {
15164
+ return {
15165
+ host: result.Answer[0].data,
15166
+ port: 2268,
15167
+ priority: 10,
15168
+ weight: 100,
15169
+ asn: 0
15170
+ };
14325
15171
  }
14326
- const onBytes = (event) => {
14327
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return;
14328
- const detail = event.detail;
14329
- const packet = detail instanceof Uint8Array ? detail : new Uint8Array(detail);
15172
+ return null;
15173
+ } catch (error) {
15174
+ console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
15175
+ return null;
15176
+ }
15177
+ }
15178
+ /**
15179
+ * Select best relay based on RTT measurements
15180
+ */
15181
+ async selectBestRelay(relays) {
15182
+ if (relays.length === 0)
15183
+ return null;
15184
+ const measured = await Promise.all(relays.map(async (relay) => {
15185
+ const rtt = await this.measureRTT(relay.host, relay.port);
15186
+ return { ...relay, rtt };
15187
+ }));
15188
+ measured.sort((a, b) => {
15189
+ if (a.priority !== b.priority)
15190
+ return a.priority - b.priority;
15191
+ return (a.rtt || Infinity) - (b.rtt || Infinity);
15192
+ });
15193
+ console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
15194
+ return measured[0];
15195
+ }
15196
+ async measureRTT(host, _port) {
15197
+ const start = performance.now();
15198
+ try {
15199
+ await fetch(`https://${host}/health`, {
15200
+ method: "HEAD",
15201
+ signal: AbortSignal.timeout(2e3),
15202
+ mode: "no-cors"
15203
+ });
15204
+ return performance.now() - start;
15205
+ } catch {
15206
+ return Infinity;
15207
+ }
15208
+ }
15209
+ /**
15210
+ * Clear the relay cache
15211
+ */
15212
+ clearCache() {
15213
+ this.cache.clear();
15214
+ }
15215
+ /**
15216
+ * Get cached relays for a source address
15217
+ */
15218
+ getCached(source) {
15219
+ return this.cache.get(source);
15220
+ }
15221
+ };
15222
+ var driadDiscovery = new DRIADDiscovery();
15223
+
15224
+ // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
15225
+ function endpointKey(endpoint) {
15226
+ return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
15227
+ }
15228
+ function selectMulticastTier(endpoints, estimate) {
15229
+ if (endpoints.length <= 1)
15230
+ return endpoints[0];
15231
+ const ranked = endpoints.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > 0).sort((a, b) => a.bandwidth - b.bandwidth);
15232
+ if (ranked.length < 2)
15233
+ return endpoints[0];
15234
+ if (estimate === void 0)
15235
+ return ranked[0];
15236
+ const budget = estimate * 0.8;
15237
+ let selected;
15238
+ for (const endpoint of ranked) {
15239
+ if (endpoint.bandwidth <= budget)
15240
+ selected = endpoint;
15241
+ }
15242
+ return selected ?? ranked[0];
15243
+ }
15244
+
15245
+ // node_modules/@blockcast/mmt-transport/dist/abr-controller.js
15246
+ var QUALITY_LEVELS = [
15247
+ { name: "240p", bitrate: 3e5, width: 426, height: 240, fps: 15 },
15248
+ { name: "360p", bitrate: 5e5, width: 640, height: 360, fps: 24 },
15249
+ { name: "480p", bitrate: 1e6, width: 854, height: 480, fps: 30 },
15250
+ { name: "720p", bitrate: 25e5, width: 1280, height: 720, fps: 30 },
15251
+ { name: "1080p", bitrate: 5e6, width: 1920, height: 1080, fps: 30 },
15252
+ { name: "1440p", bitrate: 8e6, width: 2560, height: 1440, fps: 30 },
15253
+ { name: "4K", bitrate: 15e6, width: 3840, height: 2160, fps: 30 }
15254
+ ];
15255
+ var AdaptiveBitrateController = class {
15256
+ constructor(initialQuality) {
15257
+ __publicField(this, "currentQualityIndex");
15258
+ __publicField(this, "history", []);
15259
+ __publicField(this, "historyWindow", 1e4);
15260
+ // 10 second window
15261
+ __publicField(this, "upgradeThreshold", 0.8);
15262
+ // 80% of target bitrate sustained
15263
+ __publicField(this, "downgradeThreshold", 0.5);
15264
+ // 50% of target bitrate triggers downgrade
15265
+ __publicField(this, "stabilityPeriod", 5e3);
15266
+ // Wait 5s before upgrading
15267
+ __publicField(this, "lastQualityChange", 0);
15268
+ __publicField(this, "onQualityChange");
15269
+ // FEC stats for effective loss rate calculation
15270
+ __publicField(this, "fecStats", {
15271
+ rawLossRate: 0,
15272
+ effectiveLossRate: 0,
15273
+ recoveryRate: 1,
15274
+ fecEnabled: false
15275
+ });
15276
+ this.currentQualityIndex = initialQuality ? QUALITY_LEVELS.findIndex((q) => q.name === initialQuality.name) : 0;
15277
+ if (this.currentQualityIndex < 0)
15278
+ this.currentQualityIndex = 0;
15279
+ }
15280
+ setCallback(callback) {
15281
+ this.onQualityChange = callback;
15282
+ }
15283
+ getCurrentQuality() {
15284
+ return QUALITY_LEVELS[this.currentQualityIndex];
15285
+ }
15286
+ /** Selects the multicast (S,G) tier without replacing a player's unicast ABR manager. */
15287
+ selectMulticastTier(endpoints, estimate = this.getMetrics().measuredBitrate || void 0) {
15288
+ return selectMulticastTier(endpoints, estimate);
15289
+ }
15290
+ /**
15291
+ * Record network sample for bitrate adaptation
15292
+ *
15293
+ * @param bytesReceived - Bytes received in this sample
15294
+ * @param packetsLost - Packets lost (raw, before FEC recovery)
15295
+ */
15296
+ recordSample(bytesReceived, packetsLost) {
15297
+ const now = Date.now();
15298
+ this.history.push({ timestamp: now, bytesReceived, packetsLost });
15299
+ this.history = this.history.filter((s) => now - s.timestamp < this.historyWindow);
15300
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
15301
+ const currentQuality = this.getCurrentQuality();
15302
+ const effectiveLossRate = this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate;
15303
+ if (now - this.lastQualityChange < this.stabilityPeriod) {
15304
+ return;
15305
+ }
15306
+ if (effectiveLossRate > 0.05 || measuredBitrate < currentQuality.bitrate * this.downgradeThreshold) {
15307
+ this.downgrade();
15308
+ return;
15309
+ }
15310
+ if (measuredBitrate > currentQuality.bitrate * this.upgradeThreshold && effectiveLossRate < 0.01 && this.currentQualityIndex < QUALITY_LEVELS.length - 1) {
15311
+ this.upgrade();
15312
+ }
15313
+ }
15314
+ /**
15315
+ * Update FEC statistics for ABR decisions
15316
+ *
15317
+ * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
15318
+ * (after FEC recovery) rather than raw transport loss rate.
15319
+ *
15320
+ * @param stats - FEC statistics from the FEC decoder
15321
+ */
15322
+ setFecStats(stats) {
15323
+ this.fecStats = stats;
15324
+ }
15325
+ /**
15326
+ * Get current FEC statistics
15327
+ */
15328
+ getFecStats() {
15329
+ return { ...this.fecStats };
15330
+ }
15331
+ calculateMetrics() {
15332
+ if (this.history.length < 2) {
15333
+ return { measuredBitrate: 0, lossRate: 0 };
15334
+ }
15335
+ const totalBytes = this.history.reduce((sum, s) => sum + s.bytesReceived, 0);
15336
+ const totalLost = this.history.reduce((sum, s) => sum + s.packetsLost, 0);
15337
+ const duration = (this.history[this.history.length - 1].timestamp - this.history[0].timestamp) / 1e3;
15338
+ const measuredBitrate = duration > 0 ? totalBytes * 8 / duration : 0;
15339
+ const lossRate = totalLost / (this.history.length + totalLost);
15340
+ return { measuredBitrate, lossRate };
15341
+ }
15342
+ upgrade() {
15343
+ if (this.currentQualityIndex >= QUALITY_LEVELS.length - 1)
15344
+ return;
15345
+ this.currentQualityIndex++;
15346
+ this.lastQualityChange = Date.now();
15347
+ const newQuality = this.getCurrentQuality();
15348
+ console.log(`[ABR] Upgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
15349
+ this.onQualityChange?.(newQuality);
15350
+ }
15351
+ downgrade() {
15352
+ if (this.currentQualityIndex <= 0)
15353
+ return;
15354
+ this.currentQualityIndex--;
15355
+ this.lastQualityChange = Date.now();
15356
+ const newQuality = this.getCurrentQuality();
15357
+ console.log(`[ABR] Downgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
15358
+ this.onQualityChange?.(newQuality);
15359
+ }
15360
+ /**
15361
+ * Force quality level (for testing)
15362
+ */
15363
+ setQuality(name) {
15364
+ const index = QUALITY_LEVELS.findIndex((q) => q.name === name);
15365
+ if (index >= 0) {
15366
+ this.currentQualityIndex = index;
15367
+ this.lastQualityChange = Date.now();
15368
+ this.onQualityChange?.(this.getCurrentQuality());
15369
+ }
15370
+ }
15371
+ /**
15372
+ * Get current metrics including both raw and effective loss rates
15373
+ */
15374
+ getMetrics() {
15375
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
15376
+ return {
15377
+ measuredBitrate,
15378
+ rawLossRate,
15379
+ effectiveLossRate: this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate,
15380
+ fecEnabled: this.fecStats.fecEnabled,
15381
+ sampleCount: this.history.length
15382
+ };
15383
+ }
15384
+ /**
15385
+ * Reset history and start fresh
15386
+ */
15387
+ reset() {
15388
+ this.history = [];
15389
+ this.lastQualityChange = 0;
15390
+ }
15391
+ };
15392
+
15393
+ // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
15394
+ var DEFAULT_DWELL_MS = 3e3;
15395
+ var DEFAULT_JOIN_DEADLINE_MS = 5e3;
15396
+ var _state2, _current, _target, _estimate, _favored, _joinStartedAt, _lastCommittedTimestamp, _dwellMs, _joinDeadlineMs, _MulticastOrchestrator_instances, now_fn;
15397
+ var MulticastOrchestrator = class {
15398
+ constructor(options) {
15399
+ __privateAdd(this, _MulticastOrchestrator_instances);
15400
+ __publicField(this, "options");
15401
+ __privateAdd(this, _state2, "stable");
15402
+ __privateAdd(this, _current);
15403
+ __privateAdd(this, _target);
15404
+ __privateAdd(this, _estimate);
15405
+ __privateAdd(this, _favored);
15406
+ __privateAdd(this, _joinStartedAt, 0);
15407
+ __privateAdd(this, _lastCommittedTimestamp, Number.NEGATIVE_INFINITY);
15408
+ __privateAdd(this, _dwellMs);
15409
+ __privateAdd(this, _joinDeadlineMs);
15410
+ this.options = options;
15411
+ __privateSet(this, _dwellMs, options.dwellMs ?? DEFAULT_DWELL_MS);
15412
+ __privateSet(this, _joinDeadlineMs, options.joinDeadlineMs ?? DEFAULT_JOIN_DEADLINE_MS);
15413
+ if (!Number.isFinite(__privateGet(this, _dwellMs)) || !Number.isFinite(__privateGet(this, _joinDeadlineMs)) || __privateGet(this, _dwellMs) <= 0 || __privateGet(this, _joinDeadlineMs) <= 0) {
15414
+ throw new Error("Multicast dwell and join deadline must be positive");
15415
+ }
15416
+ }
15417
+ get state() {
15418
+ return __privateGet(this, _state2);
15419
+ }
15420
+ get current() {
15421
+ return __privateGet(this, _current);
15422
+ }
15423
+ get target() {
15424
+ return __privateGet(this, _target);
15425
+ }
15426
+ get estimate() {
15427
+ return __privateGet(this, _estimate);
15428
+ }
15429
+ start() {
15430
+ __privateGet(this, _current) ?? __privateSet(this, _current, this.options.initialEndpoint ?? selectMulticastTier(this.options.endpoints, void 0));
15431
+ return __privateGet(this, _current);
15432
+ }
15433
+ onGoodput(sample) {
15434
+ const bitrate = sample.bitrate;
15435
+ if (!__privateGet(this, _current) || this.options.adaptive === false)
15436
+ return void 0;
15437
+ if (__privateGet(this, _state2) === "joining")
15438
+ return this.poll();
15439
+ if (bitrate === void 0 || !Number.isFinite(bitrate))
15440
+ return void 0;
15441
+ __privateSet(this, _estimate, bitrate);
15442
+ const desired = selectMulticastTier(this.options.endpoints, bitrate);
15443
+ if (!desired)
15444
+ return void 0;
15445
+ const desiredKey = endpointKey(desired);
15446
+ if (desiredKey === endpointKey(__privateGet(this, _current))) {
15447
+ if (__privateGet(this, _favored)?.source === "goodput")
15448
+ __privateSet(this, _favored, void 0);
15449
+ return void 0;
15450
+ }
15451
+ if (typeof desired.bandwidth !== "number" || typeof __privateGet(this, _current).bandwidth !== "number" || desired.bandwidth >= __privateGet(this, _current).bandwidth) {
15452
+ if (__privateGet(this, _favored)?.source === "goodput")
15453
+ __privateSet(this, _favored, void 0);
15454
+ return void 0;
15455
+ }
15456
+ const now = __privateMethod(this, _MulticastOrchestrator_instances, now_fn).call(this);
15457
+ if (!__privateGet(this, _favored) || __privateGet(this, _favored).key !== desiredKey || __privateGet(this, _favored).source !== "goodput") {
15458
+ __privateSet(this, _favored, { key: desiredKey, since: now, source: "goodput" });
15459
+ return void 0;
15460
+ }
15461
+ if (now - __privateGet(this, _favored).since < __privateGet(this, _dwellMs))
15462
+ return void 0;
15463
+ __privateSet(this, _state2, "joining");
15464
+ __privateSet(this, _target, desired);
15465
+ __privateSet(this, _joinStartedAt, now);
15466
+ __privateSet(this, _favored, void 0);
15467
+ return { kind: "join-target", current: __privateGet(this, _current), target: desired };
15468
+ }
15469
+ onHeadroom(sample) {
15470
+ if (!__privateGet(this, _current) || this.options.adaptive === false || __privateGet(this, _state2) === "joining")
15471
+ return void 0;
15472
+ if (!sample.healthy) {
15473
+ if (__privateGet(this, _favored)?.source === "headroom")
15474
+ __privateSet(this, _favored, void 0);
15475
+ return void 0;
15476
+ }
15477
+ if (__privateGet(this, _favored)?.source === "goodput")
15478
+ return void 0;
15479
+ const currentBandwidth = __privateGet(this, _current).bandwidth;
15480
+ if (typeof currentBandwidth !== "number")
15481
+ return void 0;
15482
+ const desired = this.options.endpoints.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > currentBandwidth).sort((a, b) => a.bandwidth - b.bandwidth)[0];
15483
+ if (!desired) {
15484
+ __privateSet(this, _favored, void 0);
15485
+ return void 0;
15486
+ }
15487
+ const desiredKey = endpointKey(desired);
15488
+ if (desiredKey === endpointKey(__privateGet(this, _current))) {
15489
+ __privateSet(this, _favored, void 0);
15490
+ return void 0;
15491
+ }
15492
+ const now = __privateMethod(this, _MulticastOrchestrator_instances, now_fn).call(this);
15493
+ if (!__privateGet(this, _favored) || __privateGet(this, _favored).key !== desiredKey) {
15494
+ __privateSet(this, _favored, { key: desiredKey, since: now, source: "headroom" });
15495
+ return void 0;
15496
+ }
15497
+ if (now - __privateGet(this, _favored).since < __privateGet(this, _dwellMs))
15498
+ return void 0;
15499
+ __privateSet(this, _state2, "joining");
15500
+ __privateSet(this, _target, desired);
15501
+ __privateSet(this, _joinStartedAt, now);
15502
+ __privateSet(this, _favored, void 0);
15503
+ return { kind: "join-target", current: __privateGet(this, _current), target: desired };
15504
+ }
15505
+ onTierPacket(packet) {
15506
+ if (!__privateGet(this, _current))
15507
+ return void 0;
15508
+ if (packet.endpointKey === endpointKey(__privateGet(this, _current)) && Number.isFinite(packet.timestamp)) {
15509
+ __privateSet(this, _lastCommittedTimestamp, Math.max(__privateGet(this, _lastCommittedTimestamp), packet.timestamp));
15510
+ }
15511
+ if (__privateGet(this, _state2) !== "joining" || !__privateGet(this, _target))
15512
+ return void 0;
15513
+ const expired = this.poll();
15514
+ if (expired)
15515
+ return expired;
15516
+ if (packet.endpointKey !== endpointKey(__privateGet(this, _target)) || !packet.keyframe || !packet.hasValidCodecConfig || !Number.isFinite(packet.timestamp) || packet.timestamp < __privateGet(this, _lastCommittedTimestamp))
15517
+ return void 0;
15518
+ const command = {
15519
+ kind: "commit-swap",
15520
+ target: __privateGet(this, _target),
15521
+ old: __privateGet(this, _current)
15522
+ };
15523
+ __privateSet(this, _lastCommittedTimestamp, packet.timestamp);
15524
+ __privateSet(this, _current, __privateGet(this, _target));
15525
+ __privateSet(this, _target, void 0);
15526
+ __privateSet(this, _state2, "stable");
15527
+ return command;
15528
+ }
15529
+ poll() {
15530
+ if (__privateGet(this, _state2) !== "joining" || !__privateGet(this, _target) || !__privateGet(this, _current))
15531
+ return void 0;
15532
+ if (__privateMethod(this, _MulticastOrchestrator_instances, now_fn).call(this) - __privateGet(this, _joinStartedAt) < __privateGet(this, _joinDeadlineMs))
15533
+ return void 0;
15534
+ return this.cancel();
15535
+ }
15536
+ cancel() {
15537
+ if (__privateGet(this, _state2) !== "joining" || !__privateGet(this, _target) || !__privateGet(this, _current))
15538
+ return void 0;
15539
+ const command = {
15540
+ kind: "abandon-join",
15541
+ current: __privateGet(this, _current),
15542
+ target: __privateGet(this, _target)
15543
+ };
15544
+ __privateSet(this, _target, void 0);
15545
+ __privateSet(this, _state2, "stable");
15546
+ return command;
15547
+ }
15548
+ };
15549
+ _state2 = new WeakMap();
15550
+ _current = new WeakMap();
15551
+ _target = new WeakMap();
15552
+ _estimate = new WeakMap();
15553
+ _favored = new WeakMap();
15554
+ _joinStartedAt = new WeakMap();
15555
+ _lastCommittedTimestamp = new WeakMap();
15556
+ _dwellMs = new WeakMap();
15557
+ _joinDeadlineMs = new WeakMap();
15558
+ _MulticastOrchestrator_instances = new WeakSet();
15559
+ now_fn = function() {
15560
+ const now = this.options.now();
15561
+ if (!Number.isFinite(now))
15562
+ throw new Error("Multicast orchestrator clock must be finite");
15563
+ return now;
15564
+ };
15565
+
15566
+ // node_modules/@blockcast/mmt-transport/dist/endpoint-config.js
15567
+ function toWindowMulticastSubscribeConfig(input) {
15568
+ if (input.mode !== void 0 && !["auto", "native", "tunnel"].includes(input.mode)) {
15569
+ throw new TypeError(`Unsupported multicast mode: ${String(input.mode)}`);
15570
+ }
15571
+ const base = {
15572
+ group: input.group,
15573
+ port: input.port,
15574
+ ...input.source?.trim() ? { source: input.source.trim() } : {},
15575
+ consume: "bytes",
15576
+ ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
15577
+ };
15578
+ const relay = input.amtRelay?.trim();
15579
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
15580
+ if (!wantsAmt) {
15581
+ const native = {
15582
+ ...base,
15583
+ origin: "ip-multicast",
15584
+ ...input.tracks?.length ? { tracks: input.tracks.map(({ name, packetId }) => ({ name, packetId })) } : {}
15585
+ };
15586
+ return native;
15587
+ }
15588
+ const relayPort = input.amtRelayPort;
15589
+ if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
15590
+ throw new TypeError("AMT requires a resolved relay and a valid relay port");
15591
+ }
15592
+ return {
15593
+ ...base,
15594
+ origin: "amt",
15595
+ relay,
15596
+ relayPort
15597
+ };
15598
+ }
15599
+ function isValidMulticastGroupAddress(address) {
15600
+ const value = address?.trim().toLowerCase();
15601
+ if (!value)
15602
+ return false;
15603
+ if (value.startsWith("ff"))
15604
+ return isValidIpv6MulticastAddress(value);
15605
+ const parts = value.split(".");
15606
+ if (parts.length !== 4)
15607
+ return false;
15608
+ const octets = parts.map((part) => {
15609
+ if (!/^\d+$/.test(part))
15610
+ return Number.NaN;
15611
+ const octet = Number(part);
15612
+ return Number.isInteger(octet) && octet >= 0 && octet <= 255 ? octet : Number.NaN;
15613
+ });
15614
+ return octets.every(Number.isInteger) && octets[0] >= 224 && octets[0] <= 239;
15615
+ }
15616
+ function normalizeMulticastEndpoint(endpoint) {
15617
+ const groupAddress = endpoint.groupAddress.trim().toLowerCase();
15618
+ const sourceAddress = endpoint.sourceAddress?.trim().toLowerCase() || void 0;
15619
+ const amtRelay = endpoint.amtRelay?.trim().toLowerCase() || void 0;
15620
+ if (!isValidMulticastGroupAddress(groupAddress) || !isPositivePort(endpoint.port))
15621
+ return void 0;
15622
+ if (endpoint.mode && !["auto", "native", "tunnel"].includes(endpoint.mode))
15623
+ return void 0;
15624
+ if (endpoint.amtRelayPort !== void 0 && !isPositivePort(endpoint.amtRelayPort))
15625
+ return void 0;
15626
+ return {
15627
+ groupAddress,
15628
+ ...sourceAddress ? { sourceAddress } : {},
15629
+ port: endpoint.port,
15630
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
15631
+ ...amtRelay ? { amtRelay } : {},
15632
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
15633
+ };
15634
+ }
15635
+ function multicastEndpointKey(endpoint) {
15636
+ const normalized = normalizeMulticastEndpoint(endpoint);
15637
+ if (!normalized)
15638
+ throw new Error("Invalid multicast endpoint");
15639
+ return JSON.stringify([
15640
+ normalized.sourceAddress ?? "",
15641
+ normalized.groupAddress,
15642
+ normalized.port,
15643
+ normalized.mode ?? "auto",
15644
+ normalized.amtRelay ?? "",
15645
+ normalized.amtRelayPort ?? ""
15646
+ ]);
15647
+ }
15648
+ function isValidIpv6MulticastAddress(value) {
15649
+ if (!/^[0-9a-f:]+$/.test(value))
15650
+ return false;
15651
+ const compressed = value.includes("::");
15652
+ if (value.indexOf("::") !== value.lastIndexOf("::"))
15653
+ return false;
15654
+ const groups = value.split(":").filter(Boolean);
15655
+ if (groups.length === 0 || groups.length > 8)
15656
+ return false;
15657
+ if (!compressed && groups.length !== 8)
15658
+ return false;
15659
+ return groups.every((group) => /^[0-9a-f]{1,4}$/.test(group));
15660
+ }
15661
+ function isPositivePort(port) {
15662
+ return Number.isInteger(port) && port > 0 && port <= 65535;
15663
+ }
15664
+
15665
+ // node_modules/@blockcast/mmt-transport/dist/multicast-subscription-pool.js
15666
+ var _entries, _gatewayIds, _nextGatewayId, _MulticastSubscriptionPool_instances, createEntry_fn, gatewayId_fn, detach_fn, dispatch_fn;
15667
+ var MulticastSubscriptionPool = class {
15668
+ constructor() {
15669
+ __privateAdd(this, _MulticastSubscriptionPool_instances);
15670
+ __privateAdd(this, _entries, /* @__PURE__ */ new Map());
15671
+ __privateAdd(this, _gatewayIds, /* @__PURE__ */ new WeakMap());
15672
+ __privateAdd(this, _nextGatewayId, 1);
15673
+ }
15674
+ async acquire(gateway, config, consumer) {
15675
+ const endpoint = normalizeMulticastEndpoint({
15676
+ groupAddress: config.group,
15677
+ sourceAddress: config.source,
15678
+ port: config.port,
15679
+ mode: config.mode,
15680
+ amtRelay: config.amtRelay,
15681
+ amtRelayPort: config.amtRelayPort
15682
+ });
15683
+ if (!endpoint)
15684
+ throw new Error("Invalid multicast endpoint");
15685
+ if (typeof gateway.subscribe !== "function")
15686
+ throw new Error("window.multicast.subscribe unavailable");
15687
+ const key = multicastEndpointKey(endpoint);
15688
+ const internalKey = `${__privateMethod(this, _MulticastSubscriptionPool_instances, gatewayId_fn).call(this, gateway)}|${key}`;
15689
+ let record = __privateGet(this, _entries).get(internalKey);
15690
+ if (!record) {
15691
+ record = { claims: 0, entry: Promise.resolve(null) };
15692
+ const createdRecord = record;
15693
+ record.entry = __privateMethod(this, _MulticastSubscriptionPool_instances, createEntry_fn).call(this, gateway, endpoint, (entry2) => {
15694
+ if (__privateGet(this, _entries).get(internalKey) === createdRecord)
15695
+ __privateGet(this, _entries).delete(internalKey);
15696
+ __privateMethod(this, _MulticastSubscriptionPool_instances, detach_fn).call(this, entry2);
15697
+ }).catch((error) => {
15698
+ if (__privateGet(this, _entries).get(internalKey) === createdRecord)
15699
+ __privateGet(this, _entries).delete(internalKey);
15700
+ throw error;
15701
+ });
15702
+ __privateGet(this, _entries).set(internalKey, record);
15703
+ }
15704
+ record.claims++;
15705
+ let entry;
15706
+ try {
15707
+ entry = await record.entry;
15708
+ } catch (error) {
15709
+ record.claims--;
15710
+ throw error;
15711
+ }
15712
+ if (entry.closed) {
15713
+ record.claims--;
15714
+ return this.acquire(gateway, config, consumer);
15715
+ }
15716
+ const token = Symbol(key);
15717
+ entry.consumers.set(token, consumer);
15718
+ let released = false;
15719
+ return {
15720
+ key,
15721
+ release: async () => {
15722
+ if (released)
15723
+ return;
15724
+ released = true;
15725
+ entry.consumers.delete(token);
15726
+ record.claims--;
15727
+ if (record.claims > 0)
15728
+ return;
15729
+ if (__privateGet(this, _entries).get(internalKey) === record)
15730
+ __privateGet(this, _entries).delete(internalKey);
15731
+ __privateMethod(this, _MulticastSubscriptionPool_instances, detach_fn).call(this, entry);
15732
+ if (!entry.closed)
15733
+ await entry.subscription.unsubscribe();
15734
+ }
15735
+ };
15736
+ }
15737
+ get size() {
15738
+ return __privateGet(this, _entries).size;
15739
+ }
15740
+ };
15741
+ _entries = new WeakMap();
15742
+ _gatewayIds = new WeakMap();
15743
+ _nextGatewayId = new WeakMap();
15744
+ _MulticastSubscriptionPool_instances = new WeakSet();
15745
+ createEntry_fn = async function(gateway, endpoint, onClosed) {
15746
+ const subscription = await gateway.subscribe(toWindowMulticastSubscribeConfig({
15747
+ group: endpoint.groupAddress,
15748
+ ...endpoint.sourceAddress ? { source: endpoint.sourceAddress } : {},
15749
+ port: endpoint.port,
15750
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
15751
+ ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
15752
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
15753
+ }));
15754
+ const consumers = /* @__PURE__ */ new Map();
15755
+ let entry;
15756
+ const bytesListener = (event) => {
15757
+ __privateMethod(this, _MulticastSubscriptionPool_instances, dispatch_fn).call(this, consumers, (consumer) => consumer.onBytes(event.detail));
15758
+ };
15759
+ const stateListener = (event) => {
15760
+ __privateMethod(this, _MulticastSubscriptionPool_instances, dispatch_fn).call(this, consumers, (consumer) => consumer.onState?.(event.detail));
15761
+ if (event.detail === "closed" && !entry.closed) {
15762
+ entry.closed = true;
15763
+ onClosed(entry);
15764
+ }
15765
+ };
15766
+ const errorListener = (event) => {
15767
+ const error = event.detail instanceof Error ? event.detail : new Error(String(event.detail));
15768
+ __privateMethod(this, _MulticastSubscriptionPool_instances, dispatch_fn).call(this, consumers, (consumer) => consumer.onError?.(error));
15769
+ };
15770
+ entry = { subscription, consumers, bytesListener, stateListener, errorListener, closed: false };
15771
+ subscription.addEventListener("bytes", bytesListener);
15772
+ subscription.addEventListener("state", stateListener);
15773
+ subscription.addEventListener("error", errorListener);
15774
+ return entry;
15775
+ };
15776
+ gatewayId_fn = function(gateway) {
15777
+ const object = gateway;
15778
+ let id = __privateGet(this, _gatewayIds).get(object);
15779
+ if (!id) {
15780
+ id = __privateWrapper(this, _nextGatewayId)._++;
15781
+ __privateGet(this, _gatewayIds).set(object, id);
15782
+ }
15783
+ return id;
15784
+ };
15785
+ detach_fn = function(entry) {
15786
+ entry.subscription.removeEventListener("bytes", entry.bytesListener);
15787
+ entry.subscription.removeEventListener("state", entry.stateListener);
15788
+ entry.subscription.removeEventListener("error", entry.errorListener);
15789
+ };
15790
+ dispatch_fn = function(consumers, callback) {
15791
+ for (const consumer of consumers.values()) {
15792
+ try {
15793
+ callback(consumer);
15794
+ } catch (error) {
15795
+ console.error("[Transport] multicast consumer callback failed", error);
15796
+ }
15797
+ }
15798
+ };
15799
+ var multicastSubscriptionPool = new MulticastSubscriptionPool();
15800
+
15801
+ // node_modules/@blockcast/mmt-transport/dist/transport-manager.js
15802
+ var TransportManager = class {
15803
+ constructor() {
15804
+ __publicField(this, "state", {
15805
+ mode: "disconnected",
15806
+ connected: false,
15807
+ packetsReceived: 0,
15808
+ bytesReceived: 0,
15809
+ lastPacketTime: 0
15810
+ });
15811
+ __publicField(this, "capabilities", null);
15812
+ __publicField(this, "subscription", null);
15813
+ __publicField(this, "driad", new DRIADDiscovery());
15814
+ __publicField(this, "abr");
15815
+ __publicField(this, "multicastOrchestrator", null);
15816
+ __publicField(this, "onOrchestratorCommand");
15817
+ __publicField(this, "connectionGeneration", 0);
15818
+ __publicField(this, "onPacket");
15819
+ __publicField(this, "onError");
15820
+ __publicField(this, "onStateChange");
15821
+ this.abr = new AdaptiveBitrateController();
15822
+ }
15823
+ getWindow() {
15824
+ return typeof window === "undefined" ? void 0 : window;
15825
+ }
15826
+ getWindowMulticastGateway() {
15827
+ return this.getWindow()?.multicast;
15828
+ }
15829
+ async getGatewayCapabilities(gateway) {
15830
+ if (!gateway?.capabilities)
15831
+ return void 0;
15832
+ try {
15833
+ return typeof gateway.capabilities === "function" ? await gateway.capabilities() : gateway.capabilities;
15834
+ } catch (error) {
15835
+ console.warn("[Transport] window.multicast capabilities failed:", error);
15836
+ return void 0;
15837
+ }
15838
+ }
15839
+ async gatewaySupportsBytes(gateway) {
15840
+ if (typeof gateway?.subscribe !== "function")
15841
+ return false;
15842
+ if (!gateway.capabilities)
15843
+ return true;
15844
+ const capabilities = await this.getGatewayCapabilities(gateway);
15845
+ if (!capabilities)
15846
+ return false;
15847
+ const consumeModes = capabilities.consumeModes;
15848
+ return !consumeModes || consumeModes.includes("bytes");
15849
+ }
15850
+ /**
15851
+ * Detect available transport capabilities
15852
+ */
15853
+ async detectCapabilities() {
15854
+ if (this.capabilities)
15855
+ return this.capabilities;
15856
+ const gateway = this.getWindowMulticastGateway();
15857
+ const hasGatewayBytes = await this.gatewaySupportsBytes(gateway);
15858
+ const win = this.getWindow();
15859
+ this.capabilities = {
15860
+ nativeSSM: hasGatewayBytes,
15861
+ nativeIGMP: hasGatewayBytes,
15862
+ directSockets: typeof win?.UDPSocket !== "undefined",
15863
+ amt: false,
15864
+ driad: true,
15865
+ // DRIAD uses HTTP proxy, always available
15866
+ fecDecode: false
15867
+ };
15868
+ console.log("[Transport] Capabilities:", this.capabilities);
15869
+ return this.capabilities;
15870
+ }
15871
+ /**
15872
+ * Connect using best available transport
15873
+ *
15874
+ * Promotion hierarchy:
15875
+ * 1. window.multicast gateway bytes
15876
+ * 2. AMT proxy (specified or discovered via DRIAD)
15877
+ * 3. MOQ WebTransport (final fallback)
15878
+ */
15879
+ async connect(config) {
15880
+ const generation = ++this.connectionGeneration;
15881
+ this.subscription?.close();
15882
+ this.subscription = null;
15883
+ this.state = {
15884
+ mode: "disconnected",
15885
+ connected: false,
15886
+ packetsReceived: 0,
15887
+ bytesReceived: 0,
15888
+ lastPacketTime: 0
15889
+ };
15890
+ this.onStateChange?.(this.state);
15891
+ const endpoint = normalizeMulticastEndpoint({
15892
+ groupAddress: config.group,
15893
+ sourceAddress: config.source,
15894
+ port: config.port,
15895
+ mode: config.mode,
15896
+ amtRelay: config.amtRelay,
15897
+ amtRelayPort: config.amtRelayPort
15898
+ });
15899
+ if (!endpoint) {
15900
+ const error = new Error("Invalid multicast endpoint configuration");
15901
+ this.onError?.(error);
15902
+ return false;
15903
+ }
15904
+ config = {
15905
+ ...config,
15906
+ group: endpoint.groupAddress,
15907
+ source: endpoint.sourceAddress ?? "",
15908
+ mode: endpoint.mode,
15909
+ amtRelay: endpoint.amtRelay,
15910
+ amtRelayPort: endpoint.amtRelayPort
15911
+ };
15912
+ const caps = await this.detectCapabilities();
15913
+ if (generation !== this.connectionGeneration)
15914
+ return false;
15915
+ if (config.initialQuality) {
15916
+ this.abr = new AdaptiveBitrateController(config.initialQuality);
15917
+ }
15918
+ this.abr.setCallback((quality) => {
15919
+ this.state.quality = quality;
15920
+ this.subscription?.onqualitychange?.(quality);
15921
+ this.onStateChange?.(this.state);
15922
+ });
15923
+ let connected = false;
15924
+ if (caps.nativeSSM || caps.nativeIGMP) {
15925
+ console.log("[Transport] Attempting window.multicast...");
15926
+ connected = await this.connectWindowMulticast(config, generation);
15927
+ if (connected) {
15928
+ if (generation !== this.connectionGeneration)
15929
+ return false;
15930
+ this.state.mode = "multicast";
15931
+ return true;
15932
+ }
15933
+ }
15934
+ if (!connected) {
15935
+ console.log("[Transport] Attempting AMT tunnel...");
15936
+ connected = await this.connectAmt(config, generation);
15937
+ if (connected) {
15938
+ if (generation !== this.connectionGeneration)
15939
+ return false;
15940
+ this.state.mode = "amt";
15941
+ return true;
15942
+ }
15943
+ }
15944
+ console.log("[Transport] All multicast transports failed, falling back to MOQ");
15945
+ return false;
15946
+ }
15947
+ /**
15948
+ * Connect via the lowercase window.multicast bytes gateway.
15949
+ */
15950
+ async connectWindowMulticast(config, generation) {
15951
+ try {
15952
+ const gateway = this.getWindowMulticastGateway();
15953
+ if (typeof gateway?.subscribe !== "function")
15954
+ return false;
15955
+ const lease = await multicastSubscriptionPool.acquire(gateway, config, {
15956
+ onBytes: (data) => {
15957
+ if (generation === this.connectionGeneration)
15958
+ this.handlePacket(data);
15959
+ },
15960
+ onState: (state) => {
15961
+ if (generation !== this.connectionGeneration)
15962
+ return;
15963
+ this.state.connected = state !== "closed";
15964
+ this.onStateChange?.(this.state);
15965
+ },
15966
+ onError: (error) => {
15967
+ if (generation !== this.connectionGeneration)
15968
+ return;
15969
+ console.error("[Transport] window.multicast error:", error);
15970
+ this.onError?.(error);
15971
+ }
15972
+ });
15973
+ if (generation !== this.connectionGeneration) {
15974
+ await lease.release();
15975
+ return false;
15976
+ }
15977
+ this.subscription = {
15978
+ id: lease.key,
15979
+ config,
15980
+ close: () => {
15981
+ void lease.release();
15982
+ }
15983
+ };
15984
+ this.state = {
15985
+ mode: "multicast",
15986
+ connected: true,
15987
+ group: config.group,
15988
+ source: config.source,
15989
+ quality: this.abr.getCurrentQuality(),
15990
+ packetsReceived: 0,
15991
+ bytesReceived: 0,
15992
+ lastPacketTime: 0
15993
+ };
15994
+ console.log(`[Transport] Connected via window.multicast: (${config.source}, ${config.group})`);
15995
+ this.onStateChange?.(this.state);
15996
+ return true;
15997
+ } catch (error) {
15998
+ console.warn("[Transport] window.multicast failed:", error);
15999
+ return false;
16000
+ }
16001
+ }
16002
+ /**
16003
+ * Connect via AMT proxy (with optional DRIAD discovery)
16004
+ */
16005
+ async connectAmt(config, generation) {
16006
+ try {
16007
+ let amtRelay = config.amtRelay;
16008
+ if (!amtRelay && config.driadEnabled !== false && config.source) {
16009
+ console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
16010
+ const relays = await this.driad.discoverRelays(config.source);
16011
+ if (generation !== this.connectionGeneration)
16012
+ return false;
16013
+ const bestRelay = await this.driad.selectBestRelay(relays);
16014
+ if (generation !== this.connectionGeneration)
16015
+ return false;
16016
+ if (bestRelay) {
16017
+ amtRelay = bestRelay.host;
16018
+ this.state.amtRelay = amtRelay;
16019
+ }
16020
+ }
16021
+ if (!amtRelay) {
16022
+ console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
16023
+ return false;
16024
+ }
16025
+ return await this.connectAmtProxy(config, amtRelay, generation);
16026
+ } catch (error) {
16027
+ console.warn("[Transport] AMT connection failed:", error);
16028
+ return false;
16029
+ }
16030
+ }
16031
+ /**
16032
+ * Connect via WebSocket-based AMT proxy (browser fallback)
16033
+ */
16034
+ async connectAmtProxy(config, amtRelay, generation) {
16035
+ try {
16036
+ const relayHost = amtRelay.includes(":") && !amtRelay.startsWith("[") ? `[${amtRelay}]` : amtRelay;
16037
+ const relayAuthority = config.amtRelayPort ? `${relayHost}:${config.amtRelayPort}` : relayHost;
16038
+ const wsUrl = new URL(`wss://${relayAuthority}/amt-proxy`);
16039
+ wsUrl.searchParams.set("group", config.group);
16040
+ wsUrl.searchParams.set("source", config.source || "");
16041
+ wsUrl.searchParams.set("port", String(config.port));
16042
+ const ws = new WebSocket(wsUrl);
16043
+ return new Promise((resolve, reject) => {
16044
+ ws.binaryType = "arraybuffer";
16045
+ const timeout = setTimeout(() => {
16046
+ ws.close();
16047
+ reject(new Error("AMT proxy connection timeout"));
16048
+ }, 1e4);
16049
+ ws.onopen = () => {
16050
+ clearTimeout(timeout);
16051
+ if (generation !== this.connectionGeneration) {
16052
+ ws.close();
16053
+ resolve(false);
16054
+ return;
16055
+ }
16056
+ console.log(`[Transport] Connected to AMT proxy: ${amtRelay}`);
16057
+ this.subscription = {
16058
+ id: `amt-proxy-${Date.now()}`,
16059
+ config,
16060
+ close: () => ws.close()
16061
+ };
16062
+ this.state = {
16063
+ mode: "amt",
16064
+ connected: true,
16065
+ group: config.group,
16066
+ source: config.source,
16067
+ amtRelay,
16068
+ quality: this.abr.getCurrentQuality(),
16069
+ packetsReceived: 0,
16070
+ bytesReceived: 0,
16071
+ lastPacketTime: 0
16072
+ };
16073
+ this.onStateChange?.(this.state);
16074
+ resolve(true);
16075
+ };
16076
+ ws.onmessage = (event) => {
16077
+ if (generation === this.connectionGeneration && event.data instanceof ArrayBuffer) {
16078
+ this.handlePacket(event.data);
16079
+ }
16080
+ };
16081
+ ws.onerror = (error) => {
16082
+ clearTimeout(timeout);
16083
+ if (generation !== this.connectionGeneration) {
16084
+ resolve(false);
16085
+ return;
16086
+ }
16087
+ console.error("[Transport] AMT proxy error:", error);
16088
+ reject(error);
16089
+ };
16090
+ ws.onclose = () => {
16091
+ clearTimeout(timeout);
16092
+ if (generation !== this.connectionGeneration) {
16093
+ resolve(false);
16094
+ return;
16095
+ }
16096
+ this.state.connected = false;
16097
+ this.onStateChange?.(this.state);
16098
+ resolve(false);
16099
+ };
16100
+ });
16101
+ } catch (error) {
16102
+ console.warn("[Transport] AMT proxy failed:", error);
16103
+ return false;
16104
+ }
16105
+ }
16106
+ /**
16107
+ * Handle received packet
16108
+ */
16109
+ handlePacket(data) {
16110
+ this.state.packetsReceived++;
16111
+ this.state.bytesReceived += data.byteLength;
16112
+ this.state.lastPacketTime = Date.now();
16113
+ this.abr.recordSample(data.byteLength, 0);
16114
+ this.onPacket?.(data);
16115
+ }
16116
+ /**
16117
+ * Get current transport state
16118
+ */
16119
+ getState() {
16120
+ return { ...this.state };
16121
+ }
16122
+ /**
16123
+ * Get current quality level
16124
+ */
16125
+ getQuality() {
16126
+ return this.abr.getCurrentQuality();
16127
+ }
16128
+ /**
16129
+ * Force quality level
16130
+ */
16131
+ setQuality(name) {
16132
+ this.abr.setQuality(name);
16133
+ }
16134
+ /** Configures multicast-only ABR while leaving the caller's MoQ ABR untouched. */
16135
+ configureMulticastTiers(options, onCommand) {
16136
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
16137
+ this.multicastOrchestrator = new MulticastOrchestrator(options);
16138
+ this.onOrchestratorCommand = onCommand;
16139
+ return this.multicastOrchestrator.start();
16140
+ }
16141
+ recordMulticastGoodput(bitrate) {
16142
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onGoodput({ bitrate }));
16143
+ }
16144
+ recordMulticastHeadroom(healthy) {
16145
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onHeadroom({ healthy }));
16146
+ }
16147
+ recordMulticastTierPacket(packet) {
16148
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onTierPacket(packet));
16149
+ }
16150
+ pollMulticastTierSwitch() {
16151
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.poll());
16152
+ }
16153
+ /**
16154
+ * Set packet callback
16155
+ */
16156
+ setPacketCallback(callback) {
16157
+ this.onPacket = callback;
16158
+ }
16159
+ /**
16160
+ * Set error callback
16161
+ */
16162
+ setErrorCallback(callback) {
16163
+ this.onError = callback;
16164
+ }
16165
+ /**
16166
+ * Set state change callback
16167
+ */
16168
+ setStateCallback(callback) {
16169
+ this.onStateChange = callback;
16170
+ }
16171
+ /**
16172
+ * Disconnect
16173
+ */
16174
+ disconnect() {
16175
+ this.connectionGeneration++;
16176
+ this.subscription?.close();
16177
+ this.subscription = null;
16178
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
16179
+ this.multicastOrchestrator = null;
16180
+ this.onOrchestratorCommand = void 0;
16181
+ this.state = {
16182
+ mode: "disconnected",
16183
+ connected: false,
16184
+ packetsReceived: 0,
16185
+ bytesReceived: 0,
16186
+ lastPacketTime: 0
16187
+ };
16188
+ this.onStateChange?.(this.state);
16189
+ }
16190
+ dispatchOrchestratorCommand(command) {
16191
+ if (command)
16192
+ this.onOrchestratorCommand?.(command);
16193
+ return command;
16194
+ }
16195
+ };
16196
+ var transportManager = new TransportManager();
16197
+
16198
+ // node_modules/@blockcast/mmt-transport/dist/moqt-priority.js
16199
+ var MAX_MOQT_PRIORITY = 255;
16200
+ function moqtPriority(value, field) {
16201
+ if (!Number.isInteger(value) || value < 0 || value > MAX_MOQT_PRIORITY) {
16202
+ throw new RangeError(`${field} must be an integer in [0, ${MAX_MOQT_PRIORITY}], got ${value}`);
16203
+ }
16204
+ return value;
16205
+ }
16206
+ function moqtSubscriberPriority(value) {
16207
+ return moqtPriority(value, "MOQT subscriber priority");
16208
+ }
16209
+ function moqtPublisherPriority(value) {
16210
+ return moqtPriority(value, "MOQT publisher priority");
16211
+ }
16212
+ var MOQT_SUBSCRIBER_PRIORITY = Object.freeze({
16213
+ catalog: moqtSubscriberPriority(0),
16214
+ deadlineRepair: moqtSubscriberPriority(0),
16215
+ audio: moqtSubscriberPriority(1),
16216
+ video: moqtSubscriberPriority(2),
16217
+ backgroundRepair: moqtSubscriberPriority(3)
16218
+ });
16219
+ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
16220
+ catalog: moqtPublisherPriority(32),
16221
+ source: moqtPublisherPriority(128),
16222
+ repair: moqtPublisherPriority(240)
16223
+ });
16224
+
16225
+ // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
16226
+ var DEFAULT_AMT_PORT = 2268;
16227
+ var AMTGatewayManager = class {
16228
+ constructor() {
16229
+ __publicField(this, "subscriptions", /* @__PURE__ */ new Map());
16230
+ __publicField(this, "messageHandler");
16231
+ __publicField(this, "pendingPackets", /* @__PURE__ */ new Map());
16232
+ __publicField(this, "driad", new DRIADDiscovery());
16233
+ this.messageHandler = (event) => {
16234
+ const data = event.data;
16235
+ console.log(`[AMT] SW message received:`, data.type);
16236
+ if (data.type === "UDP_PACKET") {
16237
+ this.handlePacket(data);
16238
+ } else if (data.type === "SOCKET_ERROR") {
16239
+ this.handleSocketError(data);
16240
+ } else if (data.type === "DEBUG_LOG") {
16241
+ console.log(`[AMT SW Debug] ${data.message}`);
16242
+ }
16243
+ };
16244
+ if (typeof navigator !== "undefined" && navigator.serviceWorker) {
16245
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
16246
+ console.log("[AMT] Registered service worker message handler");
16247
+ } else {
16248
+ console.warn("[AMT] Service worker not available");
16249
+ }
16250
+ }
16251
+ /**
16252
+ * Subscribe via AMT tunnel
16253
+ */
16254
+ async subscribe(config) {
16255
+ const { key } = config;
16256
+ const keyStr = this.getKeyString(key);
16257
+ if (this.subscriptions.has(keyStr)) {
16258
+ console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
16259
+ return keyStr;
16260
+ }
16261
+ try {
16262
+ let relayAddress;
16263
+ let discoveryMethod;
16264
+ const relayPort = config.relayPort || DEFAULT_AMT_PORT;
16265
+ if (config.relayAddress) {
16266
+ relayAddress = config.relayAddress;
16267
+ discoveryMethod = "manual";
16268
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
16269
+ } else if (key.source) {
16270
+ console.log(`[AMT] No relay configured, discovering via DRIAD for source ${key.source}...`);
16271
+ const relays = await this.driad.discoverRelays(key.source);
16272
+ const bestRelay = await this.driad.selectBestRelay(relays);
16273
+ if (!bestRelay) {
16274
+ throw new Error(`AMT relay discovery failed for source ${key.source}. Please specify a relay address in the subscription configuration.`);
16275
+ }
16276
+ relayAddress = bestRelay.host;
16277
+ discoveryMethod = "driad";
16278
+ console.log(`[AMT] Discovered relay via DRIAD: ${relayAddress}:${relayPort}`);
16279
+ } else {
16280
+ throw new Error(`AMT relay discovery requires a source address for SSM (RFC 8777). Please specify either a relay address or source address.`);
16281
+ }
16282
+ const subscriptionId = keyStr;
16283
+ this.pendingPackets.set(subscriptionId, []);
16284
+ const subscription = {
16285
+ key,
16286
+ subscriptionId,
16287
+ config,
16288
+ handshakeComplete: false,
16289
+ relay: {
16290
+ address: relayAddress,
16291
+ port: relayPort,
16292
+ discoveryMethod,
16293
+ discoveredAt: Date.now()
16294
+ }
16295
+ };
16296
+ this.subscriptions.set(keyStr, subscription);
16297
+ console.log(`[AMT] Subscription created for ${keyStr} via ${relayAddress}:${relayPort}`);
16298
+ return keyStr;
16299
+ } catch (error) {
16300
+ const subscription = this.subscriptions.get(keyStr);
16301
+ if (subscription) {
16302
+ this.subscriptions.delete(keyStr);
16303
+ this.pendingPackets.delete(subscription.subscriptionId);
16304
+ }
16305
+ throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
16306
+ }
16307
+ }
16308
+ /**
16309
+ * Unsubscribe from AMT tunnel
16310
+ */
16311
+ async unsubscribe(handle) {
16312
+ const subscription = this.subscriptions.get(handle);
16313
+ if (!subscription) {
16314
+ throw new Error(`Subscription ${handle} not found`);
16315
+ }
16316
+ try {
16317
+ if (subscription.keepAliveTimer) {
16318
+ clearInterval(subscription.keepAliveTimer);
16319
+ }
16320
+ console.log(`[AMT] Unsubscribed from ${handle}`);
16321
+ } catch (error) {
16322
+ console.error("[AMT] Error during unsubscribe:", error);
16323
+ } finally {
16324
+ this.subscriptions.delete(handle);
16325
+ this.pendingPackets.delete(subscription.subscriptionId);
16326
+ }
16327
+ }
16328
+ /**
16329
+ * Get list of active subscriptions
16330
+ */
16331
+ getSubscriptions() {
16332
+ return Array.from(this.subscriptions.keys());
16333
+ }
16334
+ /**
16335
+ * Handle packet from service worker
16336
+ */
16337
+ handlePacket(message) {
16338
+ const { subscriptionId, data } = message;
16339
+ if (!subscriptionId)
16340
+ return;
16341
+ const subscription = this.subscriptions.get(subscriptionId);
16342
+ if (!subscription) {
16343
+ console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
16344
+ return;
16345
+ }
16346
+ if (!subscription.handshakeComplete) {
16347
+ const queue = this.pendingPackets.get(subscriptionId);
16348
+ const packetData2 = data;
16349
+ if (queue) {
16350
+ queue.push({
16351
+ data: packetData2.data,
16352
+ remoteAddress: packetData2.remoteAddress,
16353
+ remotePort: packetData2.remotePort
16354
+ });
16355
+ }
16356
+ return;
16357
+ }
16358
+ const packetData = data;
16359
+ const metadata = {
16360
+ sourceAddress: subscription.relay?.address || "unknown",
16361
+ sourcePort: subscription.relay?.port || 0,
16362
+ transport: "tunnel",
16363
+ timestamp: performance.now()
16364
+ };
16365
+ subscription.config.onPacket(packetData.data, metadata);
16366
+ }
16367
+ /**
16368
+ * Handle socket error from service worker
16369
+ */
16370
+ handleSocketError(message) {
16371
+ const { subscriptionId, error } = message;
16372
+ if (!subscriptionId)
16373
+ return;
16374
+ const subscription = this.subscriptions.get(subscriptionId);
16375
+ if (!subscription) {
16376
+ console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
16377
+ return;
16378
+ }
16379
+ subscription.config.onError(new Error(error || "Unknown error"));
16380
+ }
16381
+ /**
16382
+ * Cleanup on destroy
16383
+ */
16384
+ destroy() {
16385
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
16386
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
16387
+ }
16388
+ const handles = Array.from(this.subscriptions.keys());
16389
+ for (const handle of handles) {
16390
+ this.unsubscribe(handle).catch((err) => {
16391
+ console.error(`[AMT] Error unsubscribing ${handle}:`, err);
16392
+ });
16393
+ }
16394
+ }
16395
+ /**
16396
+ * Get key string for HashMap
16397
+ */
16398
+ getKeyString(key) {
16399
+ const source = key.source ? `@${key.source}` : "";
16400
+ return `${key.group}:${key.port}${source}`;
16401
+ }
16402
+ };
16403
+ var amtGatewayManager = new AMTGatewayManager();
16404
+
16405
+ // src/multicast-transport.ts
16406
+ var MAX_TRACKED_DROPPED_PIDS = 16;
16407
+ function getMulticastGlobals() {
16408
+ return globalThis;
16409
+ }
16410
+ function hasMulticastGateway() {
16411
+ return typeof getMulticastGlobals().multicast?.subscribe === "function";
16412
+ }
16413
+ function normalizeBytesEventDetail(detail) {
16414
+ const value = detail && typeof detail === "object" && "data" in detail ? detail.data : detail;
16415
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
16416
+ if (ArrayBuffer.isView(value)) {
16417
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
16418
+ }
16419
+ return null;
16420
+ }
16421
+ 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;
16422
+ var _MulticastTransport = class _MulticastTransport {
16423
+ constructor(onPacket) {
16424
+ __privateAdd(this, _MulticastTransport_instances);
16425
+ __privateAdd(this, _onPacket);
16426
+ __privateAdd(this, _subscription2, null);
16427
+ __privateAdd(this, _bytesListener, null);
16428
+ __privateAdd(this, _resolvedTransport);
16429
+ __privateAdd(this, _videoConfirmed, false);
16430
+ __privateAdd(this, _audioConfirmed, false);
16431
+ __privateAdd(this, _watchdog, null);
16432
+ __privateAdd(this, _failbackWindowMs, null);
16433
+ __privateAdd(this, _onTakeover, null);
16434
+ __privateAdd(this, _onFailback, null);
16435
+ __privateAdd(this, _disposed4, false);
16436
+ __privateAdd(this, _stats3, {
16437
+ packetsReceived: 0,
16438
+ bytesReceived: 0,
16439
+ packetsDroppedUnregisteredPid: 0,
16440
+ packetsDroppedUnparseable: 0
16441
+ });
16442
+ __privateAdd(this, _droppedPidCounts, /* @__PURE__ */ new Map());
16443
+ __privateAdd(this, _packetIds, null);
16444
+ __privateAdd(this, _joinGeneration, 0);
16445
+ __privateSet(this, _onPacket, onPacket);
16446
+ }
16447
+ static isAvailable() {
16448
+ return hasMulticastGateway();
16449
+ }
16450
+ async join(config, context) {
16451
+ const generation = ++__privateWrapper(this, _joinGeneration)._;
16452
+ __privateMethod(this, _MulticastTransport_instances, releaseSubscription_fn).call(this);
16453
+ if (__privateGet(this, _disposed4)) return false;
16454
+ if (!_MulticastTransport.isAvailable()) {
16455
+ console.warn("[MulticastTransport] Multicast API not available");
16456
+ return false;
16457
+ }
16458
+ try {
16459
+ const packetIds = config.packetIds?.length ? new Set(config.packetIds) : null;
16460
+ console.log(
16461
+ `[MulticastTransport] window.multicast.subscribe(${config.sourceAddress}, ${config.groupAddress}, ${config.port})`
16462
+ );
16463
+ const subscribeConfig = toWindowMulticastSubscribeConfig({
16464
+ source: config.sourceAddress,
16465
+ group: config.groupAddress,
16466
+ port: config.port,
16467
+ mode: config.mode,
16468
+ amtRelay: config.amtRelay,
16469
+ amtRelayPort: config.amtRelayPort,
16470
+ packetIds: config.packetIds,
16471
+ tracks: config.tracks
16472
+ });
16473
+ const subscription = await getMulticastGlobals().multicast.subscribe(subscribeConfig);
16474
+ console.log(`[MulticastTransport] window.multicast.subscribe returned:`, !!subscription);
16475
+ if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) {
16476
+ void subscription.unsubscribe();
16477
+ return false;
16478
+ }
16479
+ if (typeof subscription.addEventListener !== "function") {
16480
+ if (typeof subscription.unsubscribe === "function") {
16481
+ void subscription.unsubscribe();
16482
+ }
16483
+ throw new Error("window.multicast subscription does not support bytes events");
16484
+ }
16485
+ const onBytes = (event) => {
16486
+ if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return;
16487
+ const packet = normalizeBytesEventDetail(event.detail);
16488
+ if (!packet) {
16489
+ __privateGet(this, _stats3).packetsDroppedUnparseable++;
16490
+ return;
16491
+ }
14330
16492
  if (!__privateMethod(this, _MulticastTransport_instances, acceptPacket_fn).call(this, packet)) return;
14331
16493
  __privateGet(this, _stats3).packetsReceived++;
14332
16494
  __privateGet(this, _stats3).bytesReceived += packet.byteLength;
14333
16495
  __privateGet(this, _onPacket).call(this, packet, context);
14334
16496
  __privateMethod(this, _MulticastTransport_instances, resetWatchdog_fn).call(this);
14335
16497
  };
14336
- const onTransportChange = (event) => {
14337
- if (__privateGet(this, _disposed4) || generation !== __privateGet(this, _joinGeneration)) return;
14338
- const transport = normalizeResolvedTransport(event.detail);
14339
- if (transport) __privateSet(this, _resolvedTransport, transport);
14340
- };
14341
16498
  __privateSet(this, _subscription2, subscription);
14342
16499
  __privateSet(this, _bytesListener, onBytes);
14343
- __privateSet(this, _transportListener, onTransportChange);
14344
16500
  __privateSet(this, _packetIds, packetIds);
14345
- __privateSet(this, _resolvedTransport, normalizeResolvedTransport(subscription.transport));
16501
+ __privateSet(this, _resolvedTransport, subscribeConfig.origin === "amt" ? "amt" : "native");
14346
16502
  subscription.addEventListener("bytes", onBytes);
14347
- subscription.addEventListener("transportchange", onTransportChange);
14348
16503
  __privateMethod(this, _MulticastTransport_instances, resetWatchdog_fn).call(this);
14349
16504
  console.log(
14350
16505
  `[MulticastTransport] Joined ${config.groupAddress}:${config.port}`
@@ -14412,7 +16567,6 @@ var _MulticastTransport = class _MulticastTransport {
14412
16567
  _onPacket = new WeakMap();
14413
16568
  _subscription2 = new WeakMap();
14414
16569
  _bytesListener = new WeakMap();
14415
- _transportListener = new WeakMap();
14416
16570
  _resolvedTransport = new WeakMap();
14417
16571
  _videoConfirmed = new WeakMap();
14418
16572
  _audioConfirmed = new WeakMap();
@@ -14433,14 +16587,10 @@ releaseSubscription_fn = function() {
14433
16587
  if (__privateGet(this, _bytesListener)) {
14434
16588
  __privateGet(this, _subscription2).removeEventListener("bytes", __privateGet(this, _bytesListener));
14435
16589
  }
14436
- if (__privateGet(this, _transportListener)) {
14437
- __privateGet(this, _subscription2).removeEventListener("transportchange", __privateGet(this, _transportListener));
14438
- }
14439
16590
  void __privateGet(this, _subscription2).unsubscribe();
14440
16591
  }
14441
16592
  __privateSet(this, _subscription2, null);
14442
16593
  __privateSet(this, _bytesListener, null);
14443
- __privateSet(this, _transportListener, null);
14444
16594
  __privateSet(this, _resolvedTransport, void 0);
14445
16595
  __privateSet(this, _packetIds, null);
14446
16596
  };
@@ -14516,12 +16666,22 @@ function createDefaultRepairLifecycleEvent(detail, options) {
14516
16666
  function isRecord(value) {
14517
16667
  return value !== null && typeof value === "object" && !Array.isArray(value);
14518
16668
  }
14519
- function isRepairBlockIdentity(value) {
16669
+ function isRepairStreamIdentity(value) {
14520
16670
  if (!isRecord(value)) return false;
14521
16671
  const packetId = value["packetId"];
14522
16672
  const catalogTrackName = value["catalogTrackName"];
16673
+ return Number.isSafeInteger(packetId) && packetId >= 0 && (catalogTrackName === null || typeof catalogTrackName === "string" && catalogTrackName.length > 0);
16674
+ }
16675
+ function isRepairBlockIdentity(value) {
16676
+ if (!isRecord(value)) return false;
14523
16677
  const sbn = value["sbn"];
14524
- return Number.isSafeInteger(packetId) && packetId >= 0 && (catalogTrackName === null || typeof catalogTrackName === "string" && catalogTrackName.length > 0) && Number.isSafeInteger(sbn) && sbn >= 0;
16678
+ return isRepairStreamIdentity(value) && Number.isSafeInteger(sbn) && sbn >= 0;
16679
+ }
16680
+ function isDecoderUnavailableReason(value) {
16681
+ return value === "cleared" || value === "disposed";
16682
+ }
16683
+ function isFecFallbackDecoder(value) {
16684
+ return value === "sync" || value === "none";
14525
16685
  }
14526
16686
  function isRepairLifecycleEvent(value) {
14527
16687
  if (!isRecord(value)) return false;
@@ -14529,7 +16689,11 @@ function isRepairLifecycleEvent(value) {
14529
16689
  const type = value["type"];
14530
16690
  const block = value["block"];
14531
16691
  const symbols = value["symbols"];
14532
- if (version !== 1 || type !== "requested" && type !== "recovered" && type !== "failed" || !isRepairBlockIdentity(block)) {
16692
+ if (version !== 1) return false;
16693
+ if (type === "decoder-unavailable") {
16694
+ return isRepairStreamIdentity(value["stream"]) && isDecoderUnavailableReason(value["reason"]) && isFecFallbackDecoder(value["fallbackDecoder"]) && block === void 0 && symbols === void 0;
16695
+ }
16696
+ if (type !== "requested" && type !== "recovered" && type !== "failed" || !isRepairBlockIdentity(block) || value["stream"] !== void 0 || value["reason"] !== void 0 || value["fallbackDecoder"] !== void 0) {
14533
16697
  return false;
14534
16698
  }
14535
16699
  if (type === "requested") return symbols === void 0;
@@ -14548,22 +16712,25 @@ function forwardRepairLifecycleEvents(source, target, options = {}) {
14548
16712
  target.dispatchEvent(forwardedEvent);
14549
16713
  });
14550
16714
  }
14551
- function repairBlockIdentity(packetId, sbn, catalogTrackName) {
16715
+ function repairStreamIdentity(packetId, catalogTrackName) {
14552
16716
  if (!Number.isSafeInteger(packetId) || packetId < 0) {
14553
16717
  throw new TypeError("packetId must be a non-negative safe integer");
14554
16718
  }
14555
- if (!Number.isSafeInteger(sbn) || sbn < 0) {
14556
- throw new TypeError("sbn must be a non-negative safe integer");
14557
- }
14558
16719
  if (catalogTrackName !== void 0 && (typeof catalogTrackName !== "string" || catalogTrackName.length === 0)) {
14559
16720
  throw new TypeError("catalogTrackName must be a non-empty string when provided");
14560
16721
  }
14561
16722
  return {
14562
16723
  packetId,
14563
- catalogTrackName: catalogTrackName ?? null,
14564
- sbn
16724
+ catalogTrackName: catalogTrackName ?? null
14565
16725
  };
14566
16726
  }
16727
+ function repairBlockIdentity(packetId, sbn, catalogTrackName) {
16728
+ const stream = repairStreamIdentity(packetId, catalogTrackName);
16729
+ if (!Number.isSafeInteger(sbn) || sbn < 0) {
16730
+ throw new TypeError("sbn must be a non-negative safe integer");
16731
+ }
16732
+ return { ...stream, sbn };
16733
+ }
14567
16734
  function assertPositiveGeometry(label, value) {
14568
16735
  if (value === void 0) return;
14569
16736
  if (!Number.isFinite(value) || value <= 0) {
@@ -14733,6 +16900,15 @@ var MulticastManager = class {
14733
16900
  }
14734
16901
  });
14735
16902
  };
16903
+ __privateGet(this, _fec).onDecoderUnavailable = (event) => {
16904
+ __privateMethod(this, _MulticastManager_instances, emitRepairLifecycle_fn).call(this, {
16905
+ version: 1,
16906
+ type: "decoder-unavailable",
16907
+ stream: repairStreamIdentity(event.packetId, event.catalogTrackName),
16908
+ reason: event.reason,
16909
+ fallbackDecoder: event.fallbackDecoder
16910
+ });
16911
+ };
14736
16912
  }
14737
16913
  // ---------------------------------------------------------------------------
14738
16914
  // Decomposed component accessors (for new code)
@@ -14787,6 +16963,17 @@ var MulticastManager = class {
14787
16963
  __privateMethod(this, _MulticastManager_instances, configureTrackMapper_fn).call(this, packetId, config);
14788
16964
  __privateGet(this, _router).setPacketIdType(packetId, trackType);
14789
16965
  }
16966
+ /**
16967
+ * Stop routing a stream's symbols to its Worker decoder. Returns false when
16968
+ * none is registered; on success one `decoder-unavailable` repair lifecycle
16969
+ * event with reason 'cleared' reaches every observer, carrying whether a
16970
+ * synchronous WASM decoder still serves the stream. The packet mapping and
16971
+ * track type are untouched: the track still exists, it just has no Worker
16972
+ * decoder. Call this before disposing the client.
16973
+ */
16974
+ clearFecWorker(packetId, catalogTrackName) {
16975
+ return __privateGet(this, _fec).clearFecWorker(packetId, catalogTrackName);
16976
+ }
14790
16977
  /** Register callback for Worker-level FecTrackStats updates. */
14791
16978
  setOnFecStatsUpdate(cb) {
14792
16979
  __privateGet(this, _fec).onFecStatsUpdate = cb;
@@ -14832,8 +17019,9 @@ var MulticastManager = class {
14832
17019
  repairSymbols: config.fecRepairSymbols,
14833
17020
  symbolSize: config.fecSymbolSize,
14834
17021
  mediaUnitsPerSecond: config.fps,
14835
- bandwidthBps: config.bandwidth
14836
- }) + (config.fecReorderToleranceMs ?? 0) : void 0;
17022
+ bandwidthBps: config.bandwidth,
17023
+ jitterBufferMs: config.fecReorderToleranceMs
17024
+ }) : void 0;
14837
17025
  const fecConfig = {
14838
17026
  k: config.fecK,
14839
17027
  symbolSize: config.fecSymbolSize,
@@ -14870,8 +17058,9 @@ var MulticastManager = class {
14870
17058
  repairSymbols: config.fecRepairSymbols,
14871
17059
  symbolSize: config.fecSymbolSize,
14872
17060
  mediaUnitsPerSecond: config.fps,
14873
- bandwidthBps: config.bandwidth
14874
- }) + (config.fecReorderToleranceMs ?? 0) : void 0;
17061
+ bandwidthBps: config.bandwidth,
17062
+ jitterBufferMs: config.fecReorderToleranceMs
17063
+ }) : void 0;
14875
17064
  __privateGet(this, _fec).configure({
14876
17065
  k: config.fecK,
14877
17066
  symbolSize: config.fecSymbolSize,
@@ -15056,34 +17245,35 @@ var MulticastManager = class {
15056
17245
  * a factory returning a distinct decoder per stream.
15057
17246
  */
15058
17247
  configureMultiTrack(catalog, wasmDecoderSource) {
15059
- const explicitRepairNamesByGroup = /* @__PURE__ */ new Map();
17248
+ const repairOwnerGroup = /* @__PURE__ */ new Map();
17249
+ const repairOwnerAltGroup = /* @__PURE__ */ new Map();
17250
+ for (const track of catalog.tracks) {
17251
+ if (track.fec !== void 0 && isFecCatalogConfig(track.fec) && track.fec.repairTrack) {
17252
+ repairOwnerGroup.set(track.fec.repairTrack, altGroupKey(track));
17253
+ repairOwnerAltGroup.set(track.fec.repairTrack, track.altGroup);
17254
+ }
17255
+ }
17256
+ const groupKeyFor = (track) => repairOwnerGroup.get(track.name) ?? altGroupKey(track);
15060
17257
  const trackNamesByGroup = /* @__PURE__ */ new Map();
15061
17258
  for (const track of catalog.tracks) {
15062
- const groupKey = altGroupKey(track);
17259
+ const groupKey = groupKeyFor(track);
15063
17260
  const groupNames = trackNamesByGroup.get(groupKey) ?? [];
15064
17261
  groupNames.push(track.name);
15065
17262
  trackNamesByGroup.set(groupKey, groupNames);
15066
- if (track.fec !== void 0 && isFecCatalogConfig(track.fec) && track.fec.repairTrack) {
15067
- const explicitRepairNames = explicitRepairNamesByGroup.get(groupKey) ?? /* @__PURE__ */ new Set();
15068
- explicitRepairNames.add(track.fec.repairTrack);
15069
- explicitRepairNamesByGroup.set(groupKey, explicitRepairNames);
15070
- }
15071
17263
  }
15072
17264
  const hasSwitchingSetByGroup = /* @__PURE__ */ new Map();
15073
17265
  for (const [groupKey, trackNames] of trackNamesByGroup) {
15074
17266
  hasSwitchingSetByGroup.set(groupKey, hasSwitchingSetRole(trackNames));
15075
17267
  }
15076
17268
  const resolvedRoles = catalog.tracks.map((track) => {
15077
- const groupKey = altGroupKey(track);
15078
- const hasSwitchingSet = hasSwitchingSetByGroup.get(groupKey) ?? false;
15079
- const explicitRepairNames = explicitRepairNamesByGroup.get(groupKey);
15080
- if (explicitRepairNames?.has(track.name)) return "repair";
17269
+ if (repairOwnerGroup.has(track.name)) return "repair";
17270
+ const hasSwitchingSet = hasSwitchingSetByGroup.get(altGroupKey(track)) ?? false;
15081
17271
  if (!hasSwitchingSet) return "single";
15082
17272
  return parseTrackRole(track.name);
15083
17273
  });
15084
17274
  const resolvedRolesByGroup = /* @__PURE__ */ new Map();
15085
17275
  for (let i = 0; i < catalog.tracks.length; i++) {
15086
- const groupKey = altGroupKey(catalog.tracks[i]);
17276
+ const groupKey = groupKeyFor(catalog.tracks[i]);
15087
17277
  const roles = resolvedRolesByGroup.get(groupKey) ?? [];
15088
17278
  roles.push(resolvedRoles[i]);
15089
17279
  resolvedRolesByGroup.set(groupKey, roles);
@@ -15146,10 +17336,11 @@ var MulticastManager = class {
15146
17336
  for (let i = 0; i < catalog.tracks.length; i++) {
15147
17337
  const track = catalog.tracks[i];
15148
17338
  const role = resolvedRoles[i];
15149
- if (track.altGroup !== void 0) {
15150
- const existing = __privateGet(this, _switchingSets).get(track.altGroup) ?? [];
17339
+ const altGroup = repairOwnerAltGroup.has(track.name) ? repairOwnerAltGroup.get(track.name) : track.altGroup;
17340
+ if (altGroup !== void 0) {
17341
+ const existing = __privateGet(this, _switchingSets).get(altGroup) ?? [];
15151
17342
  existing.push(track.name);
15152
- __privateGet(this, _switchingSets).set(track.altGroup, existing);
17343
+ __privateGet(this, _switchingSets).set(altGroup, existing);
15153
17344
  }
15154
17345
  if (track.packetId !== void 0) {
15155
17346
  __privateGet(this, _router).setPacketIdRole(track.packetId, role);
@@ -15388,11 +17579,13 @@ applyStreamGlobalFecTiming_fn = function() {
15388
17579
  };
15389
17580
  _onTrackTypeDiscovered = new WeakMap();
15390
17581
  emitRepairLifecycle_fn = function(event) {
15391
- const immutableEvent = Object.freeze({
15392
- ...event,
15393
- block: Object.freeze({ ...event.block }),
15394
- ...event.type === "requested" ? {} : { symbols: Object.freeze({ ...event.symbols }) }
15395
- });
17582
+ const immutableEvent = Object.freeze(
17583
+ event.type === "decoder-unavailable" ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
17584
+ ...event,
17585
+ block: Object.freeze({ ...event.block }),
17586
+ ...event.type === "requested" ? {} : { symbols: Object.freeze({ ...event.symbols }) }
17587
+ }
17588
+ );
15396
17589
  console.info(
15397
17590
  `${REPAIR_LIFECYCLE_LOG_PREFIX}${JSON.stringify(immutableEvent)}`
15398
17591
  );
@@ -15416,7 +17609,8 @@ async function setupFecWorkerForTrack(opts) {
15416
17609
  sourceSymbols: opts.fecK,
15417
17610
  repairSymbols: opts.fecRepairCount,
15418
17611
  symbolSize: opts.fecSymbolSize,
15419
- mediaUnitsPerSecond: 1e3 / opts.mediaUnitDurationMs
17612
+ mediaUnitsPerSecond: 1e3 / opts.mediaUnitDurationMs,
17613
+ jitterBufferMs: opts.fecReorderToleranceMs
15420
17614
  });
15421
17615
  const origin = typeof location !== "undefined" && location.origin ? location.origin : "http://localhost";
15422
17616
  const workerUrl = new URL(opts.assetUrls.fecWorker, origin);
@@ -15462,15 +17656,23 @@ async function setupFecWorkerForTrack(opts) {
15462
17656
  relayBlockSigEnabled: false
15463
17657
  };
15464
17658
  client.configure(fecTrackConfig, rqWasm, altaKeyBuffer, altaWasmModule);
15465
- opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
15466
- k: opts.fecK,
15467
- symbolSize: opts.fecSymbolSize,
15468
- interleaveDepthMs: opts.fecInterleaveMs,
15469
- // FEC timing is expressed in media units. For audio this is the access-unit
15470
- // cadence (for example 1024/48kHz), not a video-only framerate field.
15471
- fps: 1e3 / opts.mediaUnitDurationMs,
15472
- timeoutMs: deliveryWindowMs
15473
- }, opts.trackName);
17659
+ try {
17660
+ opts.multicastManager.setFecWorker(opts.packetId, client, opts.trackType, {
17661
+ k: opts.fecK,
17662
+ symbolSize: opts.fecSymbolSize,
17663
+ interleaveDepthMs: opts.fecInterleaveMs,
17664
+ // FEC timing is expressed in media units. For audio this is the access-unit
17665
+ // cadence (for example 1024/48kHz), not a video-only framerate field.
17666
+ fps: 1e3 / opts.mediaUnitDurationMs,
17667
+ timeoutMs: deliveryWindowMs
17668
+ }, opts.trackName);
17669
+ } catch (e) {
17670
+ try {
17671
+ client.dispose();
17672
+ } catch {
17673
+ }
17674
+ throw e;
17675
+ }
15474
17676
  let disposed = false;
15475
17677
  return {
15476
17678
  client,
@@ -15478,6 +17680,11 @@ async function setupFecWorkerForTrack(opts) {
15478
17680
  dispose: () => {
15479
17681
  if (disposed) return;
15480
17682
  disposed = true;
17683
+ if (!opts.multicastManager.clearFecWorker(opts.packetId, opts.trackName)) {
17684
+ console.warn(
17685
+ `[fec-worker-setup] packetId=${opts.packetId} track=${opts.trackName} Worker was not registered when disposed`
17686
+ );
17687
+ }
15481
17688
  try {
15482
17689
  client.dispose();
15483
17690
  } catch {
@@ -16361,7 +18568,7 @@ _readIndex = new WeakMap();
16361
18568
  _stalled = new WeakMap();
16362
18569
 
16363
18570
  // src/mmtp-decode-pipeline.ts
16364
- var _parser2, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _gateDropped, _gateEmitted, _fedObjects, _warnedNoParser, _feedOutcomes, _MmtpDecodePipeline_instances, gatedEmit_fn;
18571
+ var _parser2, _fecClient, _frameCb2, _initCb2, _needsKeyframe, _codec, _trackType, _gateDropped, _gateEmitted, _fedObjects2, _warnedNoParser, _feedOutcomes2, _MmtpDecodePipeline_instances, tag_fn, gatedEmit_fn;
16365
18572
  var MmtpDecodePipeline = class {
16366
18573
  constructor() {
16367
18574
  __privateAdd(this, _MmtpDecodePipeline_instances);
@@ -16370,14 +18577,18 @@ var MmtpDecodePipeline = class {
16370
18577
  __privateAdd(this, _frameCb2, null);
16371
18578
  __privateAdd(this, _initCb2, null);
16372
18579
  __privateAdd(this, _needsKeyframe, false);
16373
- __privateAdd(this, _codec, "");
18580
+ __privateAdd(this, _codec, null);
18581
+ /** Set together with #codec at configure(). Also the diagnostic label: a
18582
+ * player builds one pipeline per track, and codec alone does not say which
18583
+ * role a line belongs to at a glance. */
18584
+ __privateAdd(this, _trackType, null);
16374
18585
  /** Diagnostic counters. The keyframe gate drops silently, so a parser that
16375
18586
  * never marks a frame as a keyframe stalls the whole pipeline with no
16376
18587
  * output anywhere: frames are fed, frames are parsed, and nothing is
16377
18588
  * emitted. Bounded logging only — these gate nothing. */
16378
18589
  __privateAdd(this, _gateDropped, 0);
16379
18590
  __privateAdd(this, _gateEmitted, 0);
16380
- __privateAdd(this, _fedObjects, 0);
18591
+ __privateAdd(this, _fedObjects2, 0);
16381
18592
  /** Warned-once latch for feeds arriving with no parser. Kept separate from
16382
18593
  * #fedObjects so that counter stays a pure monotonic count. */
16383
18594
  __privateAdd(this, _warnedNoParser, false);
@@ -16386,19 +18597,20 @@ var MmtpDecodePipeline = class {
16386
18597
  * so a packet that fails header parse, fails MFU extraction, or accumulates
16387
18598
  * forever as an unreassembled fragment is indistinguishable from one that
16388
18599
  * produced a frame. Tally the kinds instead of guessing. */
16389
- __privateAdd(this, _feedOutcomes, /* @__PURE__ */ new Map());
18600
+ __privateAdd(this, _feedOutcomes2, /* @__PURE__ */ new Map());
16390
18601
  }
16391
18602
  /** Configure the inner parser. Call before feedMoqObject(). */
16392
18603
  configure(config) {
16393
18604
  __privateGet(this, _parser2)?.flush();
16394
18605
  __privateGet(this, _parser2)?.dispose();
16395
- __privateSet(this, _fedObjects, 0);
18606
+ __privateSet(this, _fedObjects2, 0);
16396
18607
  __privateSet(this, _gateDropped, 0);
16397
18608
  __privateSet(this, _gateEmitted, 0);
16398
- __privateGet(this, _feedOutcomes).clear();
18609
+ __privateGet(this, _feedOutcomes2).clear();
16399
18610
  __privateSet(this, _warnedNoParser, false);
16400
18611
  __privateSet(this, _codec, config.codec);
16401
18612
  const trackType = isVideoCodec(config.codec) ? "video" : "audio";
18613
+ __privateSet(this, _trackType, trackType);
16402
18614
  const trackInfo = {
16403
18615
  type: trackType,
16404
18616
  codec: config.codec,
@@ -16442,6 +18654,24 @@ var MmtpDecodePipeline = class {
16442
18654
  get reorderStats() {
16443
18655
  return __privateGet(this, _parser2)?.reorderStats ?? null;
16444
18656
  }
18657
+ /**
18658
+ * Feed tallies for this track. A fresh snapshot per call, not a live view.
18659
+ *
18660
+ * Unlike reorderStats this never returns null: the counters belong to the
18661
+ * pipeline rather than the parser, so they survive dispose(). That is
18662
+ * deliberate — a wedged pipeline is usually read after teardown, which is
18663
+ * exactly when the parser is already gone.
18664
+ */
18665
+ get feedStats() {
18666
+ return {
18667
+ trackType: __privateGet(this, _trackType),
18668
+ codec: __privateGet(this, _codec),
18669
+ fedObjects: __privateGet(this, _fedObjects2),
18670
+ emitted: __privateGet(this, _gateEmitted),
18671
+ gateDropped: __privateGet(this, _gateDropped),
18672
+ outcomes: Object.fromEntries(__privateGet(this, _feedOutcomes2))
18673
+ };
18674
+ }
16445
18675
  /**
16446
18676
  * Feed a raw MoQ object payload (one MMTP packet per MoQ object).
16447
18677
  * Optionally feeds source symbols to FEC client before parsing.
@@ -16450,33 +18680,37 @@ var MmtpDecodePipeline = class {
16450
18680
  if (!__privateGet(this, _parser2)) {
16451
18681
  if (!__privateGet(this, _warnedNoParser)) {
16452
18682
  __privateSet(this, _warnedNoParser, true);
16453
- console.warn("[mmtp-pipeline] feedMoqObject called with NO PARSER configured \u2014 packet dropped");
18683
+ console.warn(`[mmtp-pipeline] feedMoqObject called with NO PARSER configured ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} \u2014 packet dropped`);
16454
18684
  }
16455
18685
  return;
16456
18686
  }
16457
- __privateSet(this, _fedObjects, __privateGet(this, _fedObjects) + 1);
16458
- if (__privateGet(this, _fedObjects) === 1) {
16459
- console.log(`[mmtp-pipeline] first object fed codec=${__privateGet(this, _codec)} bytes=${packet.length}`);
18687
+ __privateSet(this, _fedObjects2, __privateGet(this, _fedObjects2) + 1);
18688
+ if (__privateGet(this, _fedObjects2) === 1) {
18689
+ console.log(`[mmtp-pipeline] first object fed ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${packet.length}`);
16460
18690
  }
16461
- if (__privateGet(this, _fecClient)?.addSourceSymbol) {
16462
- const info = __privateGet(this, _parser2).parseHeader(packet);
16463
- if (info?.fecPayloadId) {
16464
- __privateGet(this, _fecClient).addSourceSymbol(info.fecPayloadId.ssId, packet);
18691
+ let outcomeKind = "threw";
18692
+ try {
18693
+ if (__privateGet(this, _fecClient)?.addSourceSymbol) {
18694
+ const info = __privateGet(this, _parser2).parseHeader(packet);
18695
+ if (info?.fecPayloadId) {
18696
+ __privateGet(this, _fecClient).addSourceSymbol(info.fecPayloadId.ssId, packet);
18697
+ }
18698
+ }
18699
+ const record = __privateGet(this, _parser2).feed(packet);
18700
+ outcomeKind = record?.kind ?? "null(parse-or-extract-failed)";
18701
+ } finally {
18702
+ const seen = (__privateGet(this, _feedOutcomes2).get(outcomeKind) ?? 0) + 1;
18703
+ __privateGet(this, _feedOutcomes2).set(outcomeKind, seen);
18704
+ if (seen === 1) {
18705
+ console.log(
18706
+ `[mmtp-pipeline] feed outcome FIRST '${outcomeKind}' ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} at object #${__privateGet(this, _fedObjects2)} bytes=${packet.length}`
18707
+ );
16465
18708
  }
16466
18709
  }
16467
- const record = __privateGet(this, _parser2).feed(packet);
16468
- const kind = record?.kind ?? "null(parse-or-extract-failed)";
16469
- const seen = (__privateGet(this, _feedOutcomes).get(kind) ?? 0) + 1;
16470
- __privateGet(this, _feedOutcomes).set(kind, seen);
16471
- if (seen === 1) {
16472
- console.log(
16473
- `[mmtp-pipeline] feed outcome FIRST '${kind}' at object #${__privateGet(this, _fedObjects)} bytes=${packet.length}`
16474
- );
16475
- }
16476
- if (__privateGet(this, _fedObjects) % 200 === 0) {
16477
- const hist = [...__privateGet(this, _feedOutcomes)].map(([k, v]) => `${k}=${v}`).join(" ");
18710
+ if (__privateGet(this, _fedObjects2) % 200 === 0) {
18711
+ const hist = [...__privateGet(this, _feedOutcomes2)].map(([k, v]) => `${k}=${v}`).join(" ");
16478
18712
  console.log(
16479
- `[mmtp-pipeline] feed histogram @${__privateGet(this, _fedObjects)}: ${hist} | emitted=${__privateGet(this, _gateEmitted)} gateDropped=${__privateGet(this, _gateDropped)}`
18713
+ `[mmtp-pipeline] feed histogram ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} @${__privateGet(this, _fedObjects2)}: ${hist} | emitted=${__privateGet(this, _gateEmitted)} gateDropped=${__privateGet(this, _gateDropped)}`
16480
18714
  );
16481
18715
  }
16482
18716
  }
@@ -16496,7 +18730,10 @@ var MmtpDecodePipeline = class {
16496
18730
  ...meta.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: meta.mmtpTimestamp },
16497
18731
  keyframe: meta.keyframe,
16498
18732
  packetId: meta.packetId,
16499
- trackType: isVideoCodec(__privateGet(this, _codec)) ? "video" : "audio",
18733
+ // Same derivation as configure(), read from the field it set rather than
18734
+ // recomputed. Pre-configure the parser is null and routeFrame below is a
18735
+ // no-op, so the fallback is unreachable in practice.
18736
+ trackType: __privateGet(this, _trackType) ?? "audio",
16500
18737
  packetSequenceNumber: meta.packetSequenceNumber
16501
18738
  };
16502
18739
  if (meta.sourceDiscontinuity) frameMeta.sourceDiscontinuity = true;
@@ -16522,7 +18759,7 @@ var MmtpDecodePipeline = class {
16522
18759
  const droppedFrames = (__privateGet(this, _parser2)?.reorderStats.droppedOnLiveDispose ?? droppedBefore) - droppedBefore;
16523
18760
  if (droppedFrames > 0) {
16524
18761
  console.warn(
16525
- `[MmtpDecodePipeline] live dispose dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
18762
+ `[MmtpDecodePipeline] live dispose ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} dropped ${droppedFrames} buffered frame(s); finite inputs must use dispose({ flush: true })`
16526
18763
  );
16527
18764
  }
16528
18765
  __privateSet(this, _parser2, null);
@@ -16537,12 +18774,19 @@ _frameCb2 = new WeakMap();
16537
18774
  _initCb2 = new WeakMap();
16538
18775
  _needsKeyframe = new WeakMap();
16539
18776
  _codec = new WeakMap();
18777
+ _trackType = new WeakMap();
16540
18778
  _gateDropped = new WeakMap();
16541
18779
  _gateEmitted = new WeakMap();
16542
- _fedObjects = new WeakMap();
18780
+ _fedObjects2 = new WeakMap();
16543
18781
  _warnedNoParser = new WeakMap();
16544
- _feedOutcomes = new WeakMap();
18782
+ _feedOutcomes2 = new WeakMap();
16545
18783
  _MmtpDecodePipeline_instances = new WeakSet();
18784
+ /** Identity prefix for diagnostics: one pipeline per track means two
18785
+ * instances write to the same console, and unlabelled lines interleave into
18786
+ * a single unreadable stream. */
18787
+ tag_fn = function() {
18788
+ return `track=${__privateGet(this, _trackType) ?? "unconfigured"} codec=${__privateGet(this, _codec) ?? "none"}`;
18789
+ };
16546
18790
  gatedEmit_fn = function(data, meta) {
16547
18791
  var _a;
16548
18792
  let sourceDiscontinuity = false;
@@ -16551,7 +18795,7 @@ gatedEmit_fn = function(data, meta) {
16551
18795
  __privateSet(this, _gateDropped, __privateGet(this, _gateDropped) + 1);
16552
18796
  if (__privateGet(this, _gateDropped) <= 3 || __privateGet(this, _gateDropped) % 200 === 0) {
16553
18797
  console.warn(
16554
- `[mmtp-pipeline] keyframe gate DROP #${__privateGet(this, _gateDropped)} codec=${__privateGet(this, _codec)} bytes=${data.length} fed=${__privateGet(this, _fedObjects)} emitted=${__privateGet(this, _gateEmitted)}`
18798
+ `[mmtp-pipeline] keyframe gate DROP #${__privateGet(this, _gateDropped)} ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length} fed=${__privateGet(this, _fedObjects2)} emitted=${__privateGet(this, _gateEmitted)}`
16555
18799
  );
16556
18800
  }
16557
18801
  return;
@@ -16559,12 +18803,12 @@ gatedEmit_fn = function(data, meta) {
16559
18803
  __privateSet(this, _needsKeyframe, false);
16560
18804
  sourceDiscontinuity = true;
16561
18805
  console.log(
16562
- `[mmtp-pipeline] keyframe gate OPENED codec=${__privateGet(this, _codec)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects)}`
18806
+ `[mmtp-pipeline] keyframe gate OPENED ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} after ${__privateGet(this, _gateDropped)} drops, fed=${__privateGet(this, _fedObjects2)}`
16563
18807
  );
16564
18808
  }
16565
18809
  __privateSet(this, _gateEmitted, __privateGet(this, _gateEmitted) + 1);
16566
18810
  if (__privateGet(this, _gateEmitted) === 1) {
16567
- console.log(`[mmtp-pipeline] first frame emitted codec=${__privateGet(this, _codec)} bytes=${data.length}`);
18811
+ console.log(`[mmtp-pipeline] first frame emitted ${__privateMethod(this, _MmtpDecodePipeline_instances, tag_fn).call(this)} bytes=${data.length}`);
16568
18812
  }
16569
18813
  const outMeta = sourceDiscontinuity ? { ...meta, sourceDiscontinuity: true } : meta;
16570
18814
  (_a = __privateGet(this, _frameCb2)) == null ? void 0 : _a.call(this, data, outMeta);
@@ -17238,12 +19482,140 @@ emit_fn = function(params) {
17238
19482
  };
17239
19483
 
17240
19484
  // src/catalog-fec-params.ts
19485
+ var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
19486
+ function timescaleHz(value) {
19487
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
19488
+ }
19489
+ function catalogGroupDurationMs(rendition) {
19490
+ if (!rendition) return void 0;
19491
+ const ticks = numericField(rendition.groupDurationTicks);
19492
+ const ms = numericField(rendition.groupDurationMs);
19493
+ const timescale = timescaleHz(rendition.container?.kind === "mmtp" ? rendition.container.timescale : void 0) ?? timescaleHz(rendition.timescale);
19494
+ if (ticks !== void 0 && timescale !== void 0 && Number.isSafeInteger(ticks) && ticks <= timescale * MAX_SAFE_TICKS_PER_HZ) {
19495
+ return resolveGroupDurationMs({ groupDurationTicks: ticks }, timescale);
19496
+ }
19497
+ return ms;
19498
+ }
19499
+ function resolveCatalogTrackGroupDurationMs(catalog, track) {
19500
+ const renditions = track.type === "audio" ? catalog?.audio?.renditions : catalog?.video?.renditions;
19501
+ return catalogGroupDurationMs(renditions?.[track.name]);
19502
+ }
17241
19503
  var NO_FEC = {
17242
19504
  fecK: 0,
17243
19505
  fecRepairCount: 0,
19506
+ fecTotalRepairCount: 0,
17244
19507
  fecSymbolSize: 0,
17245
19508
  fecInterleaveMs: 0
17246
19509
  };
19510
+ function recordOf(value) {
19511
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
19512
+ }
19513
+ function msfTracks(catalog) {
19514
+ const raw = catalog.tracks;
19515
+ if (!Array.isArray(raw)) return void 0;
19516
+ const common = recordOf(catalog.commonTrackFields) ?? {};
19517
+ return { tracks: raw.map((t) => recordOf(t) ?? {}), common };
19518
+ }
19519
+ function resolveRepairLayers(catalog, source) {
19520
+ if (!catalog) return void 0;
19521
+ const sourceName = typeof source === "string" ? source : source.name;
19522
+ const hang = catalog;
19523
+ const roles = typeof source === "string" ? ["video", "audio"] : source.type === "audio" ? ["audio"] : source.type === "video" ? ["video"] : ["video", "audio"];
19524
+ const role = roles.find((r) => recordOf(hang[r]?.renditions?.[sourceName]) !== void 0);
19525
+ if (role !== void 0) {
19526
+ const renditionPath = `$.${role}.renditions[${JSON.stringify(sourceName)}]`;
19527
+ const rendition = recordOf(hang[role].renditions[sourceName]);
19528
+ rejectRepairFieldsOnMediaTrack(renditionPath, rendition, throwRepairContractError);
19529
+ const repairRenditions = recordOf(hang.repair?.renditions) ?? {};
19530
+ const descriptors2 = Object.entries(repairRenditions).map(([name, entry]) => {
19531
+ const path = `$.repair.renditions[${JSON.stringify(name)}]`;
19532
+ const fields = recordOf(entry);
19533
+ if (fields === void 0) {
19534
+ throwRepairContractError("track_repair_layer", path, "a repair rendition must be an object");
19535
+ }
19536
+ rejectRepairTrackGeometry(path, fields, throwRepairContractError);
19537
+ return describeRepairTrack(name, path, fields);
19538
+ });
19539
+ const fecOfRendition = (entry) => {
19540
+ const fec2 = recordOf(recordOf(entry)?.["fec"]);
19541
+ return fec2 !== void 0 && fec2["algorithm"] !== "none" ? fec2 : void 0;
19542
+ };
19543
+ const mediaRenditions = [
19544
+ ...Object.values(recordOf(hang.video?.renditions) ?? {}),
19545
+ ...Object.values(recordOf(hang.audio?.renditions) ?? {})
19546
+ ];
19547
+ const reachability2 = repairReachability(mediaRenditions.map((entry) => recordOf(entry)?.["fec"]));
19548
+ for (const d of descriptors2) {
19549
+ validateRepairTrackFields(d, throwRepairContractError);
19550
+ assertRepairTrackReachable(d, reachability2, throwRepairContractError);
19551
+ const target = dependsTarget(d);
19552
+ if (target === void 0) continue;
19553
+ const targetFec = fecOfRendition(hang.video?.renditions?.[target]) ?? fecOfRendition(hang.audio?.renditions?.[target]);
19554
+ if (targetFec === void 0) {
19555
+ throwRepairContractError(
19556
+ "track_repair_depends",
19557
+ `${d.path}.depends`,
19558
+ `${JSON.stringify(target)} is not a video or audio rendition with FEC`
19559
+ );
19560
+ }
19561
+ }
19562
+ return assembleRepairLayers(
19563
+ geometryOf(sourceName, `${renditionPath}.fec`, recordOf(rendition["fec"])),
19564
+ descriptors2,
19565
+ throwRepairContractError
19566
+ );
19567
+ }
19568
+ const msf = msfTracks(catalog);
19569
+ const msfIndex = msf ? msf.tracks.findIndex((t) => t["name"] === sourceName) : -1;
19570
+ if (!msf || msfIndex < 0) return void 0;
19571
+ const track = msf.tracks[msfIndex];
19572
+ const fec = recordOf(track["fec"]);
19573
+ const packagingOf = (t) => t["packaging"] ?? msf.common["packaging"];
19574
+ const fecOfTrack = (t) => {
19575
+ const trackFec = recordOf(t?.["fec"]);
19576
+ return trackFec !== void 0 && trackFec["algorithm"] !== "none" ? trackFec : void 0;
19577
+ };
19578
+ const descriptors = [];
19579
+ const mediaTracks = [];
19580
+ msf.tracks.forEach((t, i) => {
19581
+ const path = `$.tracks[${i}]`;
19582
+ if (packagingOf(t) === "fec-repair") {
19583
+ rejectRepairTrackGeometry(path, t, throwRepairContractError);
19584
+ if (typeof t["name"] === "string") descriptors.push(describeRepairTrack(t["name"], path, t));
19585
+ return;
19586
+ }
19587
+ rejectRepairFieldsOnMediaTrack(path, t, throwRepairContractError);
19588
+ mediaTracks.push(t);
19589
+ });
19590
+ const reachability = repairReachability(mediaTracks.map((t) => t["fec"]));
19591
+ for (const d of descriptors) {
19592
+ validateRepairTrackFields(d, throwRepairContractError);
19593
+ assertRepairTrackReachable(d, reachability, throwRepairContractError);
19594
+ const target = dependsTarget(d);
19595
+ if (target === void 0) continue;
19596
+ const targetTrack = msf.tracks.find((t) => t["name"] === target);
19597
+ if (targetTrack === void 0 || packagingOf(targetTrack) !== "mmtp" || fecOfTrack(targetTrack) === void 0) {
19598
+ throwRepairContractError(
19599
+ "track_repair_depends",
19600
+ `${d.path}.depends`,
19601
+ `${JSON.stringify(target)} is not an mmtp track with FEC`
19602
+ );
19603
+ }
19604
+ }
19605
+ return assembleRepairLayers(geometryOf(sourceName, `$.tracks[${msfIndex}].fec`, fec), descriptors, throwRepairContractError, {
19606
+ layerZeroMustBeDeclared: true
19607
+ });
19608
+ }
19609
+ function geometryOf(name, path, fec) {
19610
+ return {
19611
+ name,
19612
+ path,
19613
+ algorithm: fec?.["algorithm"],
19614
+ sourceSymbols: fec?.["sourceSymbols"],
19615
+ repairSymbols: fec?.["repairSymbols"],
19616
+ repairTrack: fec?.["repairTrack"]
19617
+ };
19618
+ }
17247
19619
  function numericField(value) {
17248
19620
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
17249
19621
  return Number.isFinite(n) && n > 0 ? n : void 0;
@@ -17252,13 +19624,16 @@ function nonNegativeField(value) {
17252
19624
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
17253
19625
  return Number.isFinite(n) && n >= 0 ? n : void 0;
17254
19626
  }
17255
- function fecParams(rendition, fps, sampleRate) {
19627
+ function fecParams(catalog, track, rendition, fps, sampleRate) {
17256
19628
  const mediaRate = sampleRate === void 0 ? { fps } : { fps, sampleRate };
17257
19629
  const fec = rendition?.fec;
17258
19630
  if (!fec) return { ...NO_FEC, ...mediaRate };
19631
+ const repair = track ? resolveRepairLayers(catalog, track) : void 0;
17259
19632
  return {
17260
19633
  fecK: fec.sourceSymbols ?? 0,
17261
19634
  fecRepairCount: fec.repairSymbols ?? 0,
19635
+ // The wire RSB_length: every base layer's packets carry the base total (§7.1).
19636
+ fecTotalRepairCount: repair?.totalBaseRepairSymbols ?? fec.repairSymbols ?? 0,
17262
19637
  fecSymbolSize: fec.symbolSize ?? 0,
17263
19638
  // interleaveDepthMs is the FEC block span in MILLISECONDS (§5.1) — the
17264
19639
  // only interleave key the catalog carries post-BLO-14526. Receivers
@@ -17270,6 +19645,8 @@ function fecParams(rendition, fps, sampleRate) {
17270
19645
  // so it cannot be reused here — a declared 0 is a legitimate value.
17271
19646
  fecReorderToleranceMs: nonNegativeField(fec.reorderToleranceMs),
17272
19647
  repairTrackName: fec.repairTrack,
19648
+ repairLayers: repair?.baseLayers,
19649
+ repairOverlays: repair?.overlays,
17273
19650
  ...mediaRate
17274
19651
  };
17275
19652
  }
@@ -17283,8 +19660,14 @@ function resolveCatalogTrackFec(catalog, tracks) {
17283
19660
  const catalogFps = numericField(video?.framerate);
17284
19661
  const sampleRate = numericField(audio?.sampleRate ?? audio?.samplerate);
17285
19662
  const audioFps = sampleRate ? sampleRate / 1024 : void 0;
17286
- const videoParams = fecParams(video, catalogFps);
17287
- const audioParams = fecParams(audio, audioFps, sampleRate);
19663
+ const videoParams = fecParams(catalog, videoTrackName ? { name: videoTrackName, type: "video" } : void 0, video, catalogFps);
19664
+ const audioParams = fecParams(
19665
+ catalog,
19666
+ audioTrackName ? { name: audioTrackName, type: "audio" } : void 0,
19667
+ audio,
19668
+ audioFps,
19669
+ sampleRate
19670
+ );
17288
19671
  return {
17289
19672
  videoTrackName,
17290
19673
  audioTrackName,
@@ -17320,8 +19703,10 @@ function catalogAmtNetworkSource(networkSource) {
17320
19703
  // src/repair-fetch.ts
17321
19704
  function wireRepairFetch(mc, opts) {
17322
19705
  const inFlight = /* @__PURE__ */ new Map();
19706
+ const warnedNoTarget = /* @__PURE__ */ new Set();
17323
19707
  let disposed = false;
17324
19708
  const requestKey = (sbn, packetId, catalogTrackName) => JSON.stringify([packetId, catalogTrackName ?? null, sbn]);
19709
+ const noTargetKey = (packetId, catalogTrackName) => JSON.stringify([packetId, catalogTrackName ?? null]);
17325
19710
  const removeResetObserver = mc.addTrackResetObserver(
17326
19711
  (packetId, catalogTrackName) => {
17327
19712
  for (const [key, request] of inFlight) {
@@ -17330,6 +19715,7 @@ function wireRepairFetch(mc, opts) {
17330
19715
  inFlight.delete(key);
17331
19716
  }
17332
19717
  }
19718
+ warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
17333
19719
  }
17334
19720
  );
17335
19721
  const timeoutFor = (sbn, packetId, catalogTrackName) => opts.timeoutMsForPacket?.(packetId) ?? mc.fecManager.repairFetchTimeoutMsForBlock(
@@ -17368,6 +19754,13 @@ function wireRepairFetch(mc, opts) {
17368
19754
  }
17369
19755
  const target = opts.resolveTarget(packetId, catalogTrackName);
17370
19756
  if (!target) {
19757
+ const warnKey = noTargetKey(packetId, catalogTrackName);
19758
+ if (!warnedNoTarget.has(warnKey)) {
19759
+ warnedNoTarget.add(warnKey);
19760
+ console.warn(
19761
+ `[RepairFetch] no repair target for pid=${packetId} sbn=${sbn}${catalogTrackName === void 0 ? "" : ` track=${catalogTrackName}`}; releasing without a fetch`
19762
+ );
19763
+ }
17371
19764
  clearRepair(sbn, packetId, catalogTrackName);
17372
19765
  return;
17373
19766
  }
@@ -17437,6 +19830,7 @@ export {
17437
19830
  CmafGroupBatcher,
17438
19831
  CmcdProducer,
17439
19832
  CmsfCatalogValidationError,
19833
+ DEFAULT_REPAIR_PRIORITY,
17440
19834
  FECManager,
17441
19835
  FEC_ESI_MAX,
17442
19836
  FEC_SBN_MAX,
@@ -17444,6 +19838,10 @@ export {
17444
19838
  FecStarvationDetector,
17445
19839
  KEYFRAME_LOST_TIMEOUT_SLACK,
17446
19840
  LOCHeaderExtensionId,
19841
+ MAX_ENCODING_SYMBOL_ID,
19842
+ MAX_RAPTORQ_SOURCE_SYMBOLS,
19843
+ MAX_REPAIR_SYMBOLS,
19844
+ MAX_TAKEOVER_DEADLINE_MS,
17447
19845
  MFUReassembler,
17448
19846
  MediaRouter,
17449
19847
  MfuReassemblyError,
@@ -17458,7 +19856,12 @@ export {
17458
19856
  NoneCodec,
17459
19857
  REPAIR_LIFECYCLE_EVENT_TYPE,
17460
19858
  REPAIR_LIFECYCLE_LOG_PREFIX,
19859
+ REPAIR_PRIORITY_MAX,
19860
+ REPAIR_PRIORITY_MIN,
19861
+ REPAIR_TRACK_GEOMETRY_KEYS,
19862
+ REPAIR_TRACK_ONLY_KEYS,
17461
19863
  ReedSolomonCodec,
19864
+ RepairContractError,
17462
19865
  SampleCombineError,
17463
19866
  SampleCombiner,
17464
19867
  SessionManager,
@@ -17469,11 +19872,14 @@ export {
17469
19872
  WasmMfuReassembler,
17470
19873
  annexBToAvcc,
17471
19874
  asSeconds,
19875
+ assembleRepairLayers,
19876
+ assertRepairTrackReachable,
17472
19877
  avccToAnnexB,
17473
19878
  buildAudioInitSegment,
17474
19879
  buildVideoInitSegment,
17475
19880
  catalogAmtNetworkSource,
17476
19881
  catalogFecInterleaveMs,
19882
+ catalogGroupDurationMs,
17477
19883
  classifyH264Keyframe,
17478
19884
  classifyPacket,
17479
19885
  codecStringFromAvcC,
@@ -17488,6 +19894,8 @@ export {
17488
19894
  decodeLocHeader,
17489
19895
  decodeLocTimestamp,
17490
19896
  decodeTimestamp,
19897
+ dependsTarget,
19898
+ describeRepairTrack,
17491
19899
  detectH264Keyframe,
17492
19900
  driftCheck,
17493
19901
  encodeDataSegment,
@@ -17541,12 +19949,17 @@ export {
17541
19949
  parseAacSampleRate,
17542
19950
  parseOpusFrameSamples,
17543
19951
  processMMTPWithReassembly,
19952
+ rejectRepairFieldsOnMediaTrack,
19953
+ rejectRepairTrackGeometry,
17544
19954
  reliableMoqMfuReassembly,
17545
19955
  removeEmulationPrevention,
19956
+ repairReachability,
17546
19957
  resolveCatalogTrackFec,
19958
+ resolveCatalogTrackGroupDurationMs,
17547
19959
  resolveGlobalMmtWasmBindings,
17548
19960
  resolveGroupDurationMs,
17549
19961
  resolveGroupDurationTicks,
19962
+ resolveRepairLayers,
17550
19963
  secondsFromTicks,
17551
19964
  setupFecWorkerForTrack,
17552
19965
  setupTrackPipeline,
@@ -17556,6 +19969,7 @@ export {
17556
19969
  unwrapMulticastPacket,
17557
19970
  validateCmsfMmtpCatalog,
17558
19971
  validateMulticastContainerContract,
19972
+ validateRepairTrackFields,
17559
19973
  validateSwitchingSetTiming,
17560
19974
  wireRepairFetch,
17561
19975
  wrapAdtsFrame