@blockcast/mmt-container 0.1.0-main.ce3c8aeb7f68 → 0.1.0-main.cf0df54ddcf4

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 (104) hide show
  1. package/README.md +44 -3
  2. package/dist/block-policy.d.ts +314 -0
  3. package/dist/block-policy.d.ts.map +1 -0
  4. package/dist/block-policy.js +466 -0
  5. package/dist/block-policy.js.map +7 -0
  6. package/dist/browser-runtime.js +2796 -573
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/catalog-fec-params.d.ts +28 -4
  9. package/dist/catalog-fec-params.d.ts.map +1 -1
  10. package/dist/catalog-fec-params.js +28 -1
  11. package/dist/catalog-fec-params.js.map +3 -3
  12. package/dist/cmaf-block-assembler.d.ts +25 -11
  13. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  14. package/dist/cmaf-block-assembler.js +76 -177
  15. package/dist/cmaf-block-assembler.js.map +3 -3
  16. package/dist/cmaf-group-batcher.js.map +1 -1
  17. package/dist/cmcd-producer.d.ts.map +1 -1
  18. package/dist/cmcd-producer.js +0 -3
  19. package/dist/cmcd-producer.js.map +2 -2
  20. package/dist/conceal-timeline.d.ts +123 -0
  21. package/dist/conceal-timeline.d.ts.map +1 -0
  22. package/dist/conceal-timeline.js +122 -0
  23. package/dist/conceal-timeline.js.map +7 -0
  24. package/dist/duplicate-ledger.d.ts +197 -0
  25. package/dist/duplicate-ledger.d.ts.map +1 -0
  26. package/dist/duplicate-ledger.js +226 -0
  27. package/dist/duplicate-ledger.js.map +7 -0
  28. package/dist/fec-manager.d.ts +113 -23
  29. package/dist/fec-manager.d.ts.map +1 -1
  30. package/dist/fec-manager.js +879 -131
  31. package/dist/fec-manager.js.map +4 -4
  32. package/dist/fec-worker-setup.js +0 -8
  33. package/dist/fec-worker-setup.js.map +2 -2
  34. package/dist/index.d.ts +7 -5
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +27 -3
  37. package/dist/index.js.map +2 -2
  38. package/dist/media-router.d.ts +5 -2
  39. package/dist/media-router.d.ts.map +1 -1
  40. package/dist/media-router.js +13 -1
  41. package/dist/media-router.js.map +2 -2
  42. package/dist/mmtp-container-parser.d.ts +85 -0
  43. package/dist/mmtp-container-parser.d.ts.map +1 -1
  44. package/dist/mmtp-container-parser.js +271 -4
  45. package/dist/mmtp-container-parser.js.map +2 -2
  46. package/dist/mmtp-container-parser.no-modules.js +273 -5
  47. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  48. package/dist/mmtp-decode-pipeline.d.ts +7 -1
  49. package/dist/mmtp-decode-pipeline.d.ts.map +1 -1
  50. package/dist/mmtp-decode-pipeline.js +279 -8
  51. package/dist/mmtp-decode-pipeline.js.map +2 -2
  52. package/dist/mmtp-router.d.ts +88 -12
  53. package/dist/mmtp-router.d.ts.map +1 -1
  54. package/dist/mmtp-router.js +1031 -247
  55. package/dist/mmtp-router.js.map +3 -3
  56. package/dist/mmtp-to-cmaf.d.ts +0 -12
  57. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  58. package/dist/mmtp-to-cmaf.js +0 -62
  59. package/dist/mmtp-to-cmaf.js.map +2 -2
  60. package/dist/multicast-manager.d.ts +148 -16
  61. package/dist/multicast-manager.d.ts.map +1 -1
  62. package/dist/multicast-manager.js +2445 -477
  63. package/dist/multicast-manager.js.map +4 -4
  64. package/dist/multicast-transport.d.ts.map +1 -1
  65. package/dist/multicast-transport.js +119 -22
  66. package/dist/multicast-transport.js.map +3 -3
  67. package/dist/no-modules.js +271 -4
  68. package/dist/no-modules.js.map +2 -2
  69. package/dist/repair-fetch.d.ts +172 -23
  70. package/dist/repair-fetch.d.ts.map +1 -1
  71. package/dist/repair-fetch.js +235 -85
  72. package/dist/repair-fetch.js.map +4 -4
  73. package/dist/wasm-mmtp-container-parser.js +271 -4
  74. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  75. package/node_modules/@blockcast/fec-worker/README.md +4 -4
  76. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +0 -2
  77. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -1
  78. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +0 -8
  79. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -1
  80. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +1 -7
  81. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -1
  82. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +4 -33
  83. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +2 -2
  84. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +0 -9
  85. package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +1 -4
  86. package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +15 -51
  87. package/package.json +14 -6
  88. package/schemas/catalog.schema.json +5 -0
  89. package/src/block-policy.ts +903 -0
  90. package/src/catalog-fec-params.ts +62 -5
  91. package/src/cmaf-block-assembler.ts +60 -151
  92. package/src/cmcd-producer.ts +0 -5
  93. package/src/conceal-timeline.ts +255 -0
  94. package/src/duplicate-ledger.ts +372 -0
  95. package/src/fec-manager.ts +742 -139
  96. package/src/index.ts +53 -1
  97. package/src/media-router.ts +22 -4
  98. package/src/mmtp-container-parser.ts +421 -1
  99. package/src/mmtp-decode-pipeline.ts +23 -6
  100. package/src/mmtp-router.ts +701 -93
  101. package/src/mmtp-to-cmaf.ts +1 -101
  102. package/src/multicast-manager.ts +587 -89
  103. package/src/multicast-transport.ts +108 -19
  104. package/src/repair-fetch.ts +491 -153
@@ -46,7 +46,6 @@ var init_fec_worker_client = __esm({
46
46
  #onFrame = null;
47
47
  #onSnapshot = null;
48
48
  #onBlockUpdate = null;
49
- #onGreenFill = null;
50
49
  #onCleanupComplete = null;
51
50
  #onError = null;
52
51
  #cleanupInFlight = null;
@@ -246,10 +245,6 @@ var init_fec_worker_client = __esm({
246
245
  this.#blockUpdatesSubscribed = true;
247
246
  this.#worker.postMessage({ type: "subscribeBlockUpdates" });
248
247
  }
249
- /** Register callback for green-fill frames. */
250
- onGreenFill(cb) {
251
- this.#onGreenFill = cb;
252
- }
253
248
  /** Register callback fired after the Worker drains all commands queued before cleanup. */
254
249
  onCleanupComplete(cb) {
255
250
  this.#onCleanupComplete = cb;
@@ -321,9 +316,6 @@ var init_fec_worker_client = __esm({
321
316
  case "blockUpdate":
322
317
  this.#onBlockUpdate?.(event.block);
323
318
  break;
324
- case "greenFill":
325
- this.#onGreenFill?.(event.sbn, event.data);
326
- break;
327
319
  case "cleanupComplete":
328
320
  for (const sbn of event.sbns) {
329
321
  this.#onCleanupComplete?.(sbn);
@@ -6283,13 +6275,13 @@ function resolveGroupDurationMs(timing, timescale) {
6283
6275
  if (timing.groupDurationTicks === void 0) {
6284
6276
  return timing.groupDurationMs;
6285
6277
  }
6286
- const durationMs = timing.groupDurationTicks / timescale * 1e3;
6287
- if (!Number.isFinite(durationMs) || durationMs <= 0 || durationMs > Number.MAX_SAFE_INTEGER) {
6278
+ const durationMs2 = timing.groupDurationTicks / timescale * 1e3;
6279
+ if (!Number.isFinite(durationMs2) || durationMs2 <= 0 || durationMs2 > Number.MAX_SAFE_INTEGER) {
6288
6280
  throw new Error(
6289
6281
  `[carp-catalog] resolveGroupDurationMs: groupDurationTicks=${timing.groupDurationTicks} at timescale=${timescale} cannot be represented as a positive safe millisecond duration`
6290
6282
  );
6291
6283
  }
6292
- return durationMs;
6284
+ return durationMs2;
6293
6285
  }
6294
6286
  var CmsfCatalogValidationError = class extends Error {
6295
6287
  constructor(code, path, message) {
@@ -7320,67 +7312,6 @@ function encodeMultiSampleSegment(samples, baseDecodeTime, sequence, trackId = 1
7320
7312
  result.set(mdat, moof.length);
7321
7313
  return result;
7322
7314
  }
7323
- function generateGreenFillNAL(avcC, width, height) {
7324
- if (avcC.length < 8) return new Uint8Array(0);
7325
- const lengthSize = (avcC[4] & 3) + 1;
7326
- let offset = 5;
7327
- const numSPS = avcC[offset++] & 31;
7328
- const nals = [];
7329
- for (let i = 0; i < numSPS; i++) {
7330
- if (offset + 2 > avcC.length) break;
7331
- const spsLen = avcC[offset] << 8 | avcC[offset + 1];
7332
- offset += 2;
7333
- if (offset + spsLen > avcC.length) break;
7334
- const sps = avcC.subarray(offset, offset + spsLen);
7335
- const framed = new Uint8Array(4 + sps.length);
7336
- new DataView(framed.buffer).setUint32(0, sps.length);
7337
- framed.set(sps, 4);
7338
- nals.push(framed);
7339
- offset += spsLen;
7340
- }
7341
- if (offset < avcC.length) {
7342
- const numPPS = avcC[offset++];
7343
- for (let i = 0; i < numPPS; i++) {
7344
- if (offset + 2 > avcC.length) break;
7345
- const ppsLen = avcC[offset] << 8 | avcC[offset + 1];
7346
- offset += 2;
7347
- if (offset + ppsLen > avcC.length) break;
7348
- const pps = avcC.subarray(offset, offset + ppsLen);
7349
- const framed = new Uint8Array(4 + pps.length);
7350
- new DataView(framed.buffer).setUint32(0, pps.length);
7351
- framed.set(pps, 4);
7352
- nals.push(framed);
7353
- offset += ppsLen;
7354
- }
7355
- }
7356
- const mbWidth = Math.ceil(width / 16);
7357
- const mbHeight = Math.ceil(height / 16);
7358
- const totalMBs = mbWidth * mbHeight;
7359
- const idrSlice = new Uint8Array([
7360
- 101,
7361
- // nal_ref_idc=3, nal_type=5 (IDR)
7362
- 136,
7363
- // slice header: first_mb_in_slice=0, slice_type=7 (I)
7364
- 128,
7365
- // pps_id=0, frame_num=0, idr_pic_id=0
7366
- 64
7367
- // slice data: mb_skip_run covering remaining MBs
7368
- // Truncated — decoder will error-conceal remaining MBs as green/gray
7369
- ]);
7370
- const idrFramed = new Uint8Array(4 + idrSlice.length);
7371
- new DataView(idrFramed.buffer).setUint32(0, idrSlice.length);
7372
- idrFramed.set(idrSlice, 4);
7373
- nals.push(idrFramed);
7374
- let totalLen = 0;
7375
- for (const n of nals) totalLen += n.length;
7376
- const result = new Uint8Array(totalLen);
7377
- let p = 0;
7378
- for (const n of nals) {
7379
- result.set(n, p);
7380
- p += n.length;
7381
- }
7382
- return result;
7383
- }
7384
7315
  function generateSilenceFrame(codec, sampleRate, channels) {
7385
7316
  if (codec.startsWith("opus") || codec.startsWith("Opus")) {
7386
7317
  return generateSilenceOpus(channels);
@@ -7997,6 +7928,123 @@ function classifyPacket(mmtpPacket) {
7997
7928
  }
7998
7929
  }
7999
7930
 
7931
+ // src/conceal-timeline.ts
7932
+ function videoConcealModeForCodec(codec) {
7933
+ const lower = codec.toLowerCase();
7934
+ if (lower.startsWith("avc1") || lower.startsWith("avc3")) return "feed-through";
7935
+ return "hold-to-rap";
7936
+ }
7937
+ var U32_MAX = 0xffffffffn;
7938
+ var HoldLastTimeline = class {
7939
+ #concealMode;
7940
+ #held = null;
7941
+ #dropping = false;
7942
+ #compositionOffsets = false;
7943
+ #stats = { droppedFrames: 0, extendedHolds: 0 };
7944
+ constructor(options) {
7945
+ this.#concealMode = options.concealMode;
7946
+ }
7947
+ get stats() {
7948
+ return { ...this.#stats };
7949
+ }
7950
+ push(sample) {
7951
+ if (sample.dts !== sample.pts) this.#compositionOffsets = true;
7952
+ if (this.#dropping) {
7953
+ if (!sample.keyframe) {
7954
+ this.#stats.droppedFrames++;
7955
+ return [];
7956
+ }
7957
+ this.#dropping = false;
7958
+ return this.#accept(sample);
7959
+ }
7960
+ if (this.#dropsUntilRap(sample)) {
7961
+ this.#dropping = true;
7962
+ this.#stats.droppedFrames++;
7963
+ return this.#compositionOffsets ? this.#releaseHeld() : [];
7964
+ }
7965
+ return this.#accept(sample);
7966
+ }
7967
+ /** Release the held sample with its authored duration (end of stream). */
7968
+ flush() {
7969
+ return this.#releaseHeld();
7970
+ }
7971
+ /** Drop all state for a new epoch. */
7972
+ reset() {
7973
+ this.#held = null;
7974
+ this.#dropping = false;
7975
+ this.#compositionOffsets = false;
7976
+ }
7977
+ #accept(sample) {
7978
+ if (this.#compositionOffsets) {
7979
+ const out2 = this.#releaseHeld();
7980
+ out2.push(this.#emit(sample, sample.duration));
7981
+ return out2;
7982
+ }
7983
+ const out = [];
7984
+ const held = this.#held;
7985
+ if (held) out.push(this.#emit(held, this.#durationTo(held, sample.dts)));
7986
+ this.#held = sample;
7987
+ return out;
7988
+ }
7989
+ #dropsUntilRap(sample) {
7990
+ const gap = sample.gapBefore;
7991
+ if (!gap || gap.trackKind !== "video" || sample.keyframe) return false;
7992
+ if (gap.action === "stall") return true;
7993
+ return this.#concealMode === "hold-to-rap" && gap.reason !== "rap-next";
7994
+ }
7995
+ #durationTo(held, target) {
7996
+ if (target <= held.dts) return held.duration;
7997
+ const span = target - held.dts;
7998
+ if (span > U32_MAX) return held.duration;
7999
+ const duration = Number(span);
8000
+ if (duration !== held.duration) this.#stats.extendedHolds++;
8001
+ return duration;
8002
+ }
8003
+ #releaseHeld() {
8004
+ const held = this.#held;
8005
+ this.#held = null;
8006
+ return held ? [this.#emit(held, held.duration)] : [];
8007
+ }
8008
+ #emit(sample, duration) {
8009
+ return {
8010
+ payload: sample.payload,
8011
+ dts: sample.dts,
8012
+ pts: sample.pts,
8013
+ duration,
8014
+ keyframe: sample.keyframe
8015
+ };
8016
+ }
8017
+ };
8018
+ var AudioGapConcealer = class {
8019
+ #last = null;
8020
+ /** Record a good access unit as it is emitted. */
8021
+ note(au) {
8022
+ this.#last = au;
8023
+ }
8024
+ plan(decision, next) {
8025
+ if (!decision || decision.trackKind !== "audio") return { kind: "none" };
8026
+ if (decision.reason !== "audio-gap" || decision.missingFrames === null) {
8027
+ return { kind: "re-anchor", pts: next.pts };
8028
+ }
8029
+ const last = this.#last;
8030
+ const missing = decision.missingFrames;
8031
+ if (last === null || last.duration <= 0) return { kind: "re-anchor", pts: next.pts };
8032
+ const duration = BigInt(last.duration);
8033
+ const repeat = [];
8034
+ for (let slot = 1; slot <= missing; slot++) {
8035
+ repeat.push({
8036
+ payload: last.payload,
8037
+ pts: last.pts + BigInt(slot) * duration,
8038
+ duration: last.duration
8039
+ });
8040
+ }
8041
+ return { kind: "conceal", repeat, silenceTicks: BigInt(missing) * duration };
8042
+ }
8043
+ reset() {
8044
+ this.#last = null;
8045
+ }
8046
+ };
8047
+
8000
8048
  // src/authored-timing.ts
8001
8049
  function scaleAuthoredTicks(ticks, mediaTimescale, targetTimescale) {
8002
8050
  if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0 || !Number.isSafeInteger(targetTimescale) || targetTimescale <= 0) return null;
@@ -8030,12 +8078,11 @@ var INT32_MIN2 = -2147483648;
8030
8078
  var INT32_MAX2 = 2147483647;
8031
8079
  var CmafBlockAssembler = class {
8032
8080
  constructor(config) {
8033
- this.#blocks = /* @__PURE__ */ new Map();
8034
- this.#pendingFlush = /* @__PURE__ */ new Set();
8035
8081
  this.#pendingRecovered = /* @__PURE__ */ new Map();
8036
8082
  this.#sequence = 1;
8037
8083
  this.#baseTs = -1;
8038
- this.#lastDecodableAudioFrame = null;
8084
+ /** Last decoder-proven audio AU, repeated into slots a gap decision names. */
8085
+ this.#audioConcealer = new AudioGapConcealer();
8039
8086
  this.#lastEmittedTs = -1;
8040
8087
  this.#lastSourceTs = -1;
8041
8088
  this.#sampleReorderWindow = 0;
@@ -8070,11 +8117,6 @@ var CmafBlockAssembler = class {
8070
8117
  // every frame is independently decodable. SBR-only AAC, USAC, or HE-AAC v2
8071
8118
  // with PCE re-entry would need a similar gate.
8072
8119
  this.#armedVideo = false;
8073
- // Legacy SBN emission watermark for the old block-buffered path. Direct
8074
- // source emission is now timestamp-ordered instead; recovered frames are
8075
- // queued by media timestamp so they can fill gaps without racing ahead of
8076
- // source frames.
8077
- this.#lastEmittedSbn = -1;
8078
8120
  // Cumulative emit counters (see emitStats). They replace the BLO-3035 L4
8079
8121
  // diagnostics, which hashed and hex-dumped every video keyframe and ran a
8080
8122
  // 1 s setInterval console aggregate on the MSE path (BLO-36599).
@@ -8101,11 +8143,6 @@ var CmafBlockAssembler = class {
8101
8143
  } else {
8102
8144
  this.#frameDuration = 33333;
8103
8145
  }
8104
- if (config.trackType === "video" && config.avcC && config.width && config.height) {
8105
- this.#fillFrame = generateGreenFillNAL(config.avcC, config.width, config.height);
8106
- } else {
8107
- this.#fillFrame = new Uint8Array(0);
8108
- }
8109
8146
  const sampleReorderWindow = config.sampleReorderWindow ?? 0;
8110
8147
  if (!Number.isFinite(sampleReorderWindow) || sampleReorderWindow < 0) {
8111
8148
  throw new Error("[CmafBlockAssembler] sampleReorderWindow must be finite and non-negative");
@@ -8145,13 +8182,10 @@ var CmafBlockAssembler = class {
8145
8182
  this._audioConfig = config.trackType === "audio" && config.sampleRate && config.channels ? { sampleRate: config.sampleRate, channels: config.channels, asc: config.asc } : null;
8146
8183
  }
8147
8184
  #config;
8148
- #blocks;
8149
- #pendingFlush;
8150
8185
  #pendingRecovered;
8151
8186
  #sequence;
8152
8187
  #baseTs;
8153
- #fillFrame;
8154
- #lastDecodableAudioFrame;
8188
+ #audioConcealer;
8155
8189
  #frameDuration;
8156
8190
  #lastEmittedTs;
8157
8191
  #lastSourceTs;
@@ -8164,15 +8198,6 @@ var CmafBlockAssembler = class {
8164
8198
  #validateH264Keyframes;
8165
8199
  #keyframeRejectDumpCount;
8166
8200
  #armedVideo;
8167
- #lastEmittedSbn;
8168
- /** Attempt to claim emission for `sbn`. Returns true if `sbn` is past
8169
- * the watermark (and advances it); false if this sbn has already been
8170
- * claimed or is older (caller should drop). */
8171
- #claimSbnEmission(sbn) {
8172
- if (sbn <= this.#lastEmittedSbn) return false;
8173
- this.#lastEmittedSbn = sbn;
8174
- return true;
8175
- }
8176
8201
  /** Truncate `frames` to start at the first keyframe for video tracks before
8177
8202
  * the first emission. Returns the (possibly spliced) frames, or null to
8178
8203
  * drop the block entirely. Audio + already-armed video: identity. */
@@ -8234,7 +8259,7 @@ var CmafBlockAssembler = class {
8234
8259
  if (reference < 0) return timestamp;
8235
8260
  return timestamp + Math.round((reference - timestamp) / wrapPeriod) * wrapPeriod;
8236
8261
  }
8237
- #emitSample(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic) {
8262
+ #emitSample(data, timestamp, duration, keyframe, advancesHorizon, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, synthetic, gapBefore) {
8238
8263
  if (authoredTiming !== void 0 && !this.#config.admitAuthoredTiming) {
8239
8264
  this.#sampleOrderStats.unadmittedAuthoredSamples++;
8240
8265
  return;
@@ -8277,7 +8302,8 @@ var CmafBlockAssembler = class {
8277
8302
  ...sampleNumber === void 0 ? {} : { sampleNumber },
8278
8303
  ...catalogTrackName === void 0 ? {} : { catalogTrackName },
8279
8304
  ...deliveryProvenance === void 0 ? {} : { deliveryProvenance },
8280
- ...synthetic === void 0 ? {} : { synthetic }
8305
+ ...synthetic === void 0 ? {} : { synthetic },
8306
+ ...gapBefore === void 0 ? {} : { gapBefore }
8281
8307
  });
8282
8308
  if (advancesHorizon && unwrappedTimestamp > this.#lastSourceTs) {
8283
8309
  this.#lastSourceTs = unwrappedTimestamp;
@@ -8377,7 +8403,7 @@ var CmafBlockAssembler = class {
8377
8403
  this.#sampleOrderStats.staleSamples++;
8378
8404
  return;
8379
8405
  }
8380
- this.#emitAudioGapFillNowBefore(sample.timestamp);
8406
+ this.#concealAudioGapBefore(sample);
8381
8407
  this.#writeSampleNow(sample, true);
8382
8408
  }
8383
8409
  #writeSampleNow(sample, rememberAudio) {
@@ -8386,7 +8412,7 @@ var CmafBlockAssembler = class {
8386
8412
  if (this.#config.trackType === "video" && keyframe) this.#armedVideo = true;
8387
8413
  const data = this.#normalizeSampleData(sample.data);
8388
8414
  if (this.#config.trackType === "audio" && rememberAudio && data.length > 0) {
8389
- this.#lastDecodableAudioFrame = data.slice();
8415
+ this.#audioConcealer.note({ payload: data, pts: BigInt(Math.round(timestamp)), duration });
8390
8416
  }
8391
8417
  if (this.onSample) {
8392
8418
  this.onSample(data === sample.data ? sample : { ...sample, data });
@@ -8404,17 +8430,26 @@ var CmafBlockAssembler = class {
8404
8430
  this.onSegment?.(segment);
8405
8431
  }
8406
8432
  }
8407
- #emitAudioGapFillNowBefore(timestamp) {
8408
- if (this.#config.trackType !== "audio" || this.#lastEmittedTs < 0 || this.#lastDecodableAudioFrame === null) return;
8409
- const gap = timestamp - this.#lastEmittedTs;
8410
- if (gap <= this.#frameDuration * 1.5) return;
8411
- const missingFrames = Math.max(0, Math.round(gap / this.#frameDuration) - 1);
8412
- for (let i = 0; i < missingFrames; i++) {
8413
- const fillTs = this.#lastEmittedTs + this.#frameDuration;
8433
+ /**
8434
+ * Repeat the last good AU into exactly the slots an `audio-gap` decision
8435
+ * names. A synthesised AAC access unit is not portable across every
8436
+ * AudioSpecificConfig, so only known-good encoded audio is repeated; with
8437
+ * no good AU yet, or on `audio-discontinuity`, the sink re-anchors at the
8438
+ * next sample and nothing is written.
8439
+ */
8440
+ #concealAudioGapBefore(sample) {
8441
+ if (this.#config.trackType !== "audio" || !sample.gapBefore) return;
8442
+ const plan = this.#audioConcealer.plan(sample.gapBefore, {
8443
+ pts: BigInt(Math.round(sample.timestamp))
8444
+ });
8445
+ if (plan.kind !== "conceal") return;
8446
+ for (const slot of plan.repeat) {
8447
+ const slotTimestamp = Number(slot.pts);
8448
+ if (slotTimestamp <= this.#lastEmittedTs || slotTimestamp >= sample.timestamp) continue;
8414
8449
  this.#writeSampleNow({
8415
- data: this.#lastDecodableAudioFrame.slice(),
8416
- timestamp: fillTs,
8417
- duration: this.#frameDuration,
8450
+ data: slot.payload.slice(),
8451
+ timestamp: slotTimestamp,
8452
+ duration: slot.duration,
8418
8453
  keyframe: true,
8419
8454
  synthetic: true
8420
8455
  }, false);
@@ -8450,7 +8485,8 @@ var CmafBlockAssembler = class {
8450
8485
  f.mmtpTimestamp,
8451
8486
  f.movieFragmentSequenceNumber,
8452
8487
  f.sampleNumber,
8453
- f.synthetic
8488
+ f.synthetic,
8489
+ f.gapBefore
8454
8490
  );
8455
8491
  }
8456
8492
  }
@@ -8483,7 +8519,7 @@ var CmafBlockAssembler = class {
8483
8519
  * is guarded by the per-frame `lastEmittedTs` check (also enforced in
8484
8520
  * `#emitPerSample`). The `sbn`/`esi` parameters are kept for the call-site
8485
8521
  * signature but no longer affect routing. */
8486
- addFrame(sbn, esi, data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
8522
+ addFrame(sbn, esi, data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, gapBefore) {
8487
8523
  void sbn;
8488
8524
  void esi;
8489
8525
  this.#emitStats.addedFrames++;
@@ -8504,7 +8540,8 @@ var CmafBlockAssembler = class {
8504
8540
  mmtpTimestamp,
8505
8541
  movieFragmentSequenceNumber,
8506
8542
  sampleNumber,
8507
- void 0
8543
+ void 0,
8544
+ gapBefore
8508
8545
  );
8509
8546
  this.#countEmit([{ keyframe }]);
8510
8547
  }
@@ -8514,23 +8551,20 @@ var CmafBlockAssembler = class {
8514
8551
  void sbn;
8515
8552
  this.#emitStats.completedBlocks++;
8516
8553
  }
8517
- /** Handle block timeout — emit whatever frames we have + fill for missing slots. */
8554
+ /**
8555
+ * Record an unrecoverable block. Nothing is synthesised: the release gate
8556
+ * attaches the stall/conceal decision to the next released frame, and the
8557
+ * sink holds the last good frame (video) or repeats the last good AU into
8558
+ * the decided slots (audio).
8559
+ */
8518
8560
  failBlock(sbn) {
8561
+ void sbn;
8519
8562
  this.#emitStats.failedBlocks++;
8520
- this.#pendingFlush.delete(sbn);
8521
- const block = this.#blocks.get(sbn);
8522
- if (!block || block.size === 0) {
8523
- this.#blocks.delete(sbn);
8524
- return;
8525
- }
8526
- this.#flushBlockWithFill(sbn);
8527
8563
  }
8528
8564
  /** Add all frames from a FEC-recovered block at once and emit immediately. */
8529
8565
  addRecoveredBlock(sbn, frames) {
8530
8566
  void sbn;
8531
8567
  this.#emitStats.recoveredBlocks++;
8532
- this.#pendingFlush.delete(sbn);
8533
- this.#blocks.delete(sbn);
8534
8568
  if (frames.length === 0) return;
8535
8569
  const normalized = this.#normalizeVideoKeyframes(frames);
8536
8570
  this.#countEmit(normalized);
@@ -8547,7 +8581,7 @@ var CmafBlockAssembler = class {
8547
8581
  }
8548
8582
  }
8549
8583
  /** Emit a single frame immediately as a one-sample segment (for oversized packets bypassing FEC). */
8550
- addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber) {
8584
+ addBypassFrame(data, timestamp, keyframe, catalogTrackName, mpuSequenceNumber, packetSequenceNumber, packetSequenceNumbers, repairedPacketSequenceNumbers, authoredTiming, deliveryProvenance, mmtpTimestamp, movieFragmentSequenceNumber, sampleNumber, gapBefore) {
8551
8585
  if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp);
8552
8586
  this.#emitSample(
8553
8587
  data,
@@ -8565,7 +8599,8 @@ var CmafBlockAssembler = class {
8565
8599
  mmtpTimestamp,
8566
8600
  movieFragmentSequenceNumber,
8567
8601
  sampleNumber,
8568
- void 0
8602
+ void 0,
8603
+ gapBefore
8569
8604
  );
8570
8605
  }
8571
8606
  /** Build and emit init segment from catalog config. */
@@ -8607,17 +8642,14 @@ var CmafBlockAssembler = class {
8607
8642
  }
8608
8643
  /** Drop all queued state and begin a fresh timestamp epoch. */
8609
8644
  reset() {
8610
- this.#blocks.clear();
8611
- this.#pendingFlush.clear();
8612
8645
  this.#pendingRecovered.clear();
8613
8646
  this.#sequence = 1;
8614
8647
  this.#baseTs = -1;
8615
8648
  this.#lastEmittedTs = -1;
8616
8649
  this.#lastSourceTs = -1;
8617
8650
  this.#recoveredHorizonTs = -1;
8618
- this.#lastDecodableAudioFrame = null;
8651
+ this.#audioConcealer.reset();
8619
8652
  this.#armedVideo = false;
8620
- this.#lastEmittedSbn = -1;
8621
8653
  this.#sampleReorderQueue = [];
8622
8654
  }
8623
8655
  dispose() {
@@ -8669,67 +8701,12 @@ var CmafBlockAssembler = class {
8669
8701
  frame.mmtpTimestamp,
8670
8702
  frame.movieFragmentSequenceNumber,
8671
8703
  frame.sampleNumber,
8672
- frame.synthetic
8704
+ frame.synthetic,
8705
+ frame.gapBefore
8673
8706
  );
8674
8707
  this.#countEmit([frame]);
8675
8708
  }
8676
8709
  }
8677
- /** Flush a block's buffered frames as a multi-sample CMAF segment. */
8678
- #flushBlock(sbn) {
8679
- const block = this.#blocks.get(sbn);
8680
- if (!block || block.size === 0) {
8681
- this.#blocks.delete(sbn);
8682
- return;
8683
- }
8684
- const entries = [...block.entries()].sort((a, b) => a[0] - b[0]);
8685
- const sortedFrames = entries.map(([, f]) => f);
8686
- this.#blocks.delete(sbn);
8687
- if (!this.#claimSbnEmission(sbn)) return;
8688
- const frames = this.#applyVideoKeyframeGate(sortedFrames);
8689
- if (!frames) return;
8690
- this.#countEmit(frames);
8691
- this.#emitPerSample(frames);
8692
- }
8693
- /** Flush a block with fill frames for missing ESI slots (FEC timeout path). */
8694
- #flushBlockWithFill(sbn) {
8695
- const block = this.#blocks.get(sbn);
8696
- if (!block) return;
8697
- const k = this.#config.k;
8698
- const isVideo = this.#config.trackType === "video";
8699
- const firstAudioFrame = !isVideo ? [...block.values()].sort((a, b) => a.timestamp - b.timestamp)[0]?.data : void 0;
8700
- const audioConcealmentFrame = this.#lastDecodableAudioFrame ?? firstAudioFrame;
8701
- const allFrames = [];
8702
- let lastRealTs = -1;
8703
- let firstRealTs = -1;
8704
- for (const [, f] of block) {
8705
- if (firstRealTs < 0 || f.timestamp < firstRealTs) firstRealTs = f.timestamp;
8706
- if (f.timestamp > lastRealTs) lastRealTs = f.timestamp;
8707
- }
8708
- const estimatedBlockDuration = block.size > 1 ? (lastRealTs - firstRealTs) / (block.size - 1) * k : this.#frameDuration * k;
8709
- for (let esi = 0; esi < k; esi++) {
8710
- const real = block.get(esi);
8711
- if (real) {
8712
- allFrames.push(real);
8713
- } else {
8714
- const interpolatedTs = firstRealTs >= 0 ? firstRealTs + Math.round(esi * estimatedBlockDuration / k) : this.#lastEmittedTs >= 0 ? this.#lastEmittedTs + this.#frameDuration * (esi + 1) : 0;
8715
- allFrames.push({
8716
- // A synthesized AAC access unit is not portable across every
8717
- // AudioSpecificConfig. Repeat known-good encoded audio instead;
8718
- // if this is the first block, use its earliest received sample.
8719
- data: isVideo ? this.#fillFrame : audioConcealmentFrame?.slice() ?? new Uint8Array(0),
8720
- timestamp: interpolatedTs,
8721
- // Video: first fill is keyframe (IDR). Audio: all fill marked keyframe.
8722
- keyframe: isVideo ? !block.has(0) && esi === 0 : true,
8723
- synthetic: true
8724
- });
8725
- }
8726
- }
8727
- this.#blocks.delete(sbn);
8728
- if (!this.#claimSbnEmission(sbn)) return;
8729
- const gatedFrames = this.#applyVideoKeyframeGate(allFrames);
8730
- if (!gatedFrames) return;
8731
- this.#emitPerSample(gatedFrames);
8732
- }
8733
8710
  };
8734
8711
  function isH264Codec(codec) {
8735
8712
  const c = codec?.toLowerCase();
@@ -9780,6 +9757,464 @@ var SessionManager = class {
9780
9757
  }
9781
9758
  };
9782
9759
 
9760
+ // src/block-policy.ts
9761
+ function repairPriorityForClass(blockClass) {
9762
+ switch (blockClass) {
9763
+ case "keyframe":
9764
+ case "unknown":
9765
+ return 0;
9766
+ case "audio":
9767
+ return 1;
9768
+ case "delta":
9769
+ return 2;
9770
+ }
9771
+ }
9772
+ function exactInteger(numerator, denominator) {
9773
+ if (!Number.isFinite(numerator) || !Number.isFinite(denominator) || denominator === 0) {
9774
+ return null;
9775
+ }
9776
+ const quotient = numerator / denominator;
9777
+ const rounded = Math.round(quotient);
9778
+ if (rounded < 1) return null;
9779
+ const representationError = 2 * Number.EPSILON * Math.abs(quotient);
9780
+ return Math.abs(quotient - rounded) <= representationError ? rounded : null;
9781
+ }
9782
+ function isPositiveFinite(value) {
9783
+ return value !== void 0 && Number.isFinite(value) && value > 0;
9784
+ }
9785
+ function deriveBlockClassifierGeometry(input) {
9786
+ if (!isPositiveFinite(input.interleaveDepthMs)) {
9787
+ throw new Error(
9788
+ `[BlockPolicy] interleaveDepthMs=${input.interleaveDepthMs} is not a positive block span; the catalog validator rejects this`
9789
+ );
9790
+ }
9791
+ if (input.trackKind === "audio") return { trackKind: "audio" };
9792
+ if (!isPositiveFinite(input.framerate)) {
9793
+ return { trackKind: "video", mode: "all-protected", reason: "framerate-absent" };
9794
+ }
9795
+ const framerate = input.framerate;
9796
+ let keyframeInterval;
9797
+ if (isPositiveFinite(input.keyframeIntervalTicks) && isPositiveFinite(input.timescale)) {
9798
+ keyframeInterval = { ticks: input.keyframeIntervalTicks, timescale: input.timescale };
9799
+ } else if (isPositiveFinite(input.keyframeIntervalMs)) {
9800
+ keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1e3 };
9801
+ } else {
9802
+ return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
9803
+ }
9804
+ const gopFrames = exactInteger(keyframeInterval.ticks * framerate, keyframeInterval.timescale);
9805
+ if (gopFrames === null) {
9806
+ return {
9807
+ trackKind: "video",
9808
+ mode: "all-protected",
9809
+ reason: "keyframe-interval-not-integral"
9810
+ };
9811
+ }
9812
+ const frameDurationMs = 1e3 / framerate;
9813
+ const interleaveUnits = deriveFecInterleaveDepth(input.interleaveDepthMs, frameDurationMs);
9814
+ if (interleaveUnits >= gopFrames) {
9815
+ return { trackKind: "video", mode: "all-protected", reason: "block-spans-gop" };
9816
+ }
9817
+ return {
9818
+ trackKind: "video",
9819
+ mode: "classifying",
9820
+ frameDurationMs,
9821
+ interleaveUnits,
9822
+ gopFrames,
9823
+ keyframeInterval
9824
+ };
9825
+ }
9826
+ function keyframeIntervalMediaTicks(geometry, mediaTimescale) {
9827
+ if (geometry.trackKind !== "video" || geometry.mode !== "classifying") return null;
9828
+ if (!Number.isSafeInteger(mediaTimescale) || mediaTimescale <= 0) return null;
9829
+ const { ticks, timescale } = geometry.keyframeInterval;
9830
+ if (!Number.isSafeInteger(ticks) || !Number.isSafeInteger(timescale)) return null;
9831
+ const scaled = BigInt(ticks) * BigInt(mediaTimescale);
9832
+ const divisor = BigInt(timescale);
9833
+ if (scaled % divisor !== 0n) return null;
9834
+ return scaled / divisor;
9835
+ }
9836
+ function compareDataUnitStarts(a, b) {
9837
+ return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
9838
+ }
9839
+ var BlockClassifier = class {
9840
+ #geometry;
9841
+ #mode;
9842
+ #reason;
9843
+ /**
9844
+ * False once the stream showed that an MPU boundary does not bound its
9845
+ * RAPs (a RAP inside an MPU, or an MPU longer than a GOP). Recorded in
9846
+ * every mode: the stall/conceal decision relies on it even when the
9847
+ * catalog geometry already runs the classifier `all-protected`.
9848
+ */
9849
+ #mpuBoundsRaps = true;
9850
+ #blocks = /* @__PURE__ */ new Map();
9851
+ /**
9852
+ * P1 ledger, kept for the MPUs within the classification horizon (the
9853
+ * highest MPU seen and the one before it): the SBN span of every source
9854
+ * packet of each MPU, and each MPU's data-unit starts in authored order.
9855
+ * Valid only within one continuous SBN sequence; a source discontinuity
9856
+ * clears it (`noteSourceDiscontinuity`).
9857
+ */
9858
+ #mpuSbnSpans = /* @__PURE__ */ new Map();
9859
+ #dataUnitStarts = /* @__PURE__ */ new Map();
9860
+ #highestMpu = null;
9861
+ /** MPU → movie_fragment_sequence_number observed in it. */
9862
+ #mpuFragments = /* @__PURE__ */ new Map();
9863
+ #lastRap = null;
9864
+ constructor(geometry) {
9865
+ this.#geometry = geometry;
9866
+ this.#mode = "classifying";
9867
+ this.#reason = null;
9868
+ this.reset(geometry);
9869
+ }
9870
+ get geometry() {
9871
+ return this.#geometry;
9872
+ }
9873
+ get mode() {
9874
+ return this.#mode;
9875
+ }
9876
+ get reason() {
9877
+ return this.#reason;
9878
+ }
9879
+ /**
9880
+ * Whether "same MPU on both sides of a gap" still proves the gap held no
9881
+ * RAP. It stops holding for the rest of the epoch once a RAP was received
9882
+ * inside an MPU or an MPU ran longer than a GOP.
9883
+ */
9884
+ get mpuBoundsRaps() {
9885
+ return this.#mpuBoundsRaps;
9886
+ }
9887
+ /** Begin a fresh epoch (catalog change or track reset). */
9888
+ reset(geometry = this.#geometry) {
9889
+ this.#geometry = geometry;
9890
+ this.#blocks.clear();
9891
+ this.#clearContiguityLedger();
9892
+ this.#mpuFragments.clear();
9893
+ this.#lastRap = null;
9894
+ this.#mpuBoundsRaps = true;
9895
+ if (geometry.trackKind === "video" && geometry.mode === "all-protected") {
9896
+ this.#mode = "all-protected";
9897
+ this.#reason = geometry.reason;
9898
+ } else {
9899
+ this.#mode = "classifying";
9900
+ this.#reason = null;
9901
+ }
9902
+ }
9903
+ /**
9904
+ * Retire this classifier (its stream moves to a new catalog epoch). Every
9905
+ * block it had classified `delta` loses the evidence behind that class and
9906
+ * reads `unknown` from now on; the returned changes say so.
9907
+ */
9908
+ retire() {
9909
+ const changes = [];
9910
+ for (const [sbn, block] of this.#blocks) {
9911
+ if (block.cls !== "delta") continue;
9912
+ block.cls = "unknown";
9913
+ changes.push({
9914
+ kind: "reclassified",
9915
+ sbn,
9916
+ from: "delta",
9917
+ to: "unknown",
9918
+ evidence: "classifier-disabled"
9919
+ });
9920
+ }
9921
+ return changes;
9922
+ }
9923
+ /**
9924
+ * The stream's SBN sequence restarted (FECManager source discontinuity:
9925
+ * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
9926
+ * order are comparable only within one continuous sequence, so the P1
9927
+ * ledger starts again.
9928
+ */
9929
+ noteSourceDiscontinuity() {
9930
+ this.#clearContiguityLedger();
9931
+ }
9932
+ /** Register a block that exists without evidence (a vanished block). */
9933
+ touch(sbn) {
9934
+ this.#blockFor(sbn);
9935
+ }
9936
+ /** Forget a resolved block. */
9937
+ forget(sbn) {
9938
+ this.#blocks.delete(sbn);
9939
+ }
9940
+ classOf(sbn) {
9941
+ if (this.#geometry.trackKind === "audio") return "audio";
9942
+ return this.#blocks.get(sbn)?.cls ?? "unknown";
9943
+ }
9944
+ /** Record one first-arrival source symbol's evidence for block `sbn`. */
9945
+ observe(sbn, evidence) {
9946
+ if (this.#geometry.trackKind === "audio") return [];
9947
+ const changes = [];
9948
+ const block = this.#blockFor(sbn);
9949
+ if (evidence.rap) block.rapSeen = true;
9950
+ if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
9951
+ if (evidence.idx !== void 0) {
9952
+ block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
9953
+ block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
9954
+ }
9955
+ if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
9956
+ this.#mpuBoundsRaps = false;
9957
+ }
9958
+ const violation = this.#checkInvariants(sbn, block, evidence);
9959
+ if (violation !== null) changes.push(...this.#disable(violation));
9960
+ const next = this.#classify(block);
9961
+ if (next !== block.cls && this.#allowed(block.cls, next)) {
9962
+ changes.push({
9963
+ kind: "reclassified",
9964
+ sbn,
9965
+ from: block.cls,
9966
+ to: next,
9967
+ evidence: this.#evidenceFor(block, next)
9968
+ });
9969
+ block.cls = next;
9970
+ }
9971
+ return changes;
9972
+ }
9973
+ /**
9974
+ * Record a RAP frame released in order. Released MPU-start RAPs of MPUs m
9975
+ * and m+n must be exactly n keyframe intervals apart in the media
9976
+ * timescale, compared as integers.
9977
+ *
9978
+ * Comparing only consecutive MPUs would miss exactly the case the window
9979
+ * rule cannot survive: a short MPU whose successor's RAP was lost (that
9980
+ * RAP-bearing block is the one a wrong G calls delta), because the next
9981
+ * released RAP then belongs to m+2. Every MPU is one interval long, so the
9982
+ * span to any later released RAP proves or refutes all MPUs in between.
9983
+ */
9984
+ noteReleasedRap(mpu, presentationTime, mediaTimescale) {
9985
+ if (this.#geometry.trackKind === "audio" || this.#mode === "all-protected") {
9986
+ return [];
9987
+ }
9988
+ const interval = keyframeIntervalMediaTicks(this.#geometry, mediaTimescale);
9989
+ if (interval === null) return this.#disable("keyframe-interval-not-media-integral");
9990
+ const previous = this.#lastRap;
9991
+ if (previous !== null && previous.mpu === mpu && previous.mediaTimescale === mediaTimescale) {
9992
+ return [];
9993
+ }
9994
+ this.#lastRap = { mpu, presentationTime, mediaTimescale };
9995
+ if (previous === null || mpu < previous.mpu || previous.mediaTimescale !== mediaTimescale) {
9996
+ return [];
9997
+ }
9998
+ if (presentationTime - previous.presentationTime === interval * BigInt(mpu - previous.mpu)) {
9999
+ return [];
10000
+ }
10001
+ return this.#disable("rap-spacing-mismatch");
10002
+ }
10003
+ #blockFor(sbn) {
10004
+ let block = this.#blocks.get(sbn);
10005
+ if (!block) {
10006
+ block = { rapSeen: false, mpus: /* @__PURE__ */ new Set(), cls: "unknown" };
10007
+ this.#blocks.set(sbn, block);
10008
+ }
10009
+ return block;
10010
+ }
10011
+ #checkInvariants(sbn, block, evidence) {
10012
+ if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
10013
+ const geometry = this.#geometry;
10014
+ if (geometry.mode !== "classifying") return null;
10015
+ if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
10016
+ return "rap-not-mpu-start";
10017
+ }
10018
+ if (evidence.idx !== void 0 && evidence.idx >= geometry.gopFrames) {
10019
+ return "mpu-longer-than-gop";
10020
+ }
10021
+ if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry.interleaveUnits) {
10022
+ return "block-wider-than-interleave";
10023
+ }
10024
+ if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
10025
+ const fragment = this.#mpuFragments.get(evidence.mpu);
10026
+ if (fragment === void 0) {
10027
+ this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
10028
+ for (const mpu of this.#mpuFragments.keys()) {
10029
+ if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
10030
+ }
10031
+ } else if (fragment !== evidence.movieFragment) {
10032
+ return "mpu-multiple-fragments";
10033
+ }
10034
+ }
10035
+ if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
10036
+ return "block-not-contiguous";
10037
+ }
10038
+ return null;
10039
+ }
10040
+ #clearContiguityLedger() {
10041
+ this.#mpuSbnSpans.clear();
10042
+ this.#dataUnitStarts.clear();
10043
+ this.#highestMpu = null;
10044
+ }
10045
+ /**
10046
+ * P1 check for one source packet of MPU `mpu` in block `sbn`, then record
10047
+ * it. True when some recorded packet's authored order and SBN order
10048
+ * disagree with this one's (see the class comment). Only positions the
10049
+ * wire states are compared: MPU order for every packet, and data-unit
10050
+ * order for packets that carry a DU header. A packet of one data unit
10051
+ * that continues into the next block carries no DU header and so only
10052
+ * takes part through its MPU, which is exactly what makes an adjacent
10053
+ * straddle consistent.
10054
+ */
10055
+ #contradictsAuthoredOrder(sbn, mpu, evidence) {
10056
+ for (const [other, span2] of this.#mpuSbnSpans) {
10057
+ if (other < mpu && span2.max > sbn) return true;
10058
+ if (other > mpu && span2.min < sbn) return true;
10059
+ }
10060
+ const inHorizon = this.#highestMpu === null || mpu + 1 >= this.#highestMpu;
10061
+ let insertAt = -1;
10062
+ let starts;
10063
+ let start;
10064
+ if (evidence.idx !== void 0) {
10065
+ start = {
10066
+ movieFragment: evidence.movieFragment ?? 0,
10067
+ idx: evidence.idx,
10068
+ offset: evidence.offset ?? 0,
10069
+ sbn
10070
+ };
10071
+ starts = this.#dataUnitStarts.get(mpu);
10072
+ if (starts !== void 0) {
10073
+ let lo = 0;
10074
+ let hi = starts.length;
10075
+ while (lo < hi) {
10076
+ const mid = lo + hi >>> 1;
10077
+ if (compareDataUnitStarts(starts[mid], start) < 0) lo = mid + 1;
10078
+ else hi = mid;
10079
+ }
10080
+ const at = starts[lo];
10081
+ if (at !== void 0 && compareDataUnitStarts(at, start) === 0) {
10082
+ if (at.sbn !== sbn) return true;
10083
+ } else {
10084
+ const before = starts[lo - 1];
10085
+ if (before !== void 0 && before.sbn > sbn) return true;
10086
+ if (at !== void 0 && at.sbn < sbn) return true;
10087
+ insertAt = lo;
10088
+ }
10089
+ }
10090
+ }
10091
+ if (!inHorizon) return false;
10092
+ const span = this.#mpuSbnSpans.get(mpu);
10093
+ if (span === void 0) this.#mpuSbnSpans.set(mpu, { min: sbn, max: sbn });
10094
+ else {
10095
+ if (sbn < span.min) span.min = sbn;
10096
+ if (sbn > span.max) span.max = sbn;
10097
+ }
10098
+ if (start !== void 0) {
10099
+ if (starts === void 0) this.#dataUnitStarts.set(mpu, [start]);
10100
+ else if (insertAt >= 0) starts.splice(insertAt, 0, start);
10101
+ }
10102
+ if (this.#highestMpu === null || mpu > this.#highestMpu) {
10103
+ this.#highestMpu = mpu;
10104
+ for (const other of [...this.#mpuSbnSpans.keys()]) {
10105
+ if (other + 1 < mpu) {
10106
+ this.#mpuSbnSpans.delete(other);
10107
+ this.#dataUnitStarts.delete(other);
10108
+ }
10109
+ }
10110
+ }
10111
+ return false;
10112
+ }
10113
+ #disable(reason) {
10114
+ if (reason === "rap-not-mpu-start" || reason === "mpu-longer-than-gop") {
10115
+ this.#mpuBoundsRaps = false;
10116
+ }
10117
+ if (this.#mode === "all-protected") return [];
10118
+ this.#mode = "all-protected";
10119
+ this.#reason = reason;
10120
+ const changes = [{ kind: "mode", mode: "all-protected", reason }];
10121
+ for (const [sbn, block] of this.#blocks) {
10122
+ if (block.cls !== "delta") continue;
10123
+ block.cls = "unknown";
10124
+ changes.push({
10125
+ kind: "reclassified",
10126
+ sbn,
10127
+ from: "delta",
10128
+ to: "unknown",
10129
+ evidence: "classifier-disabled"
10130
+ });
10131
+ }
10132
+ return changes;
10133
+ }
10134
+ #classify(block) {
10135
+ if (block.rapSeen || block.mpus.size >= 2) return "keyframe";
10136
+ if (this.#mode === "all-protected") return "unknown";
10137
+ const geometry = this.#geometry;
10138
+ if (geometry.trackKind !== "video" || geometry.mode !== "classifying") return "unknown";
10139
+ if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
10140
+ const span = geometry.interleaveUnits - 1;
10141
+ if (block.idxMax - span >= 1 && block.idxMin + span <= geometry.gopFrames - 1) {
10142
+ return "delta";
10143
+ }
10144
+ }
10145
+ return "unknown";
10146
+ }
10147
+ #allowed(from, to) {
10148
+ if (from === "keyframe") return false;
10149
+ if (from === "unknown") return to === "delta" || to === "keyframe";
10150
+ if (from === "delta") return to === "keyframe";
10151
+ return false;
10152
+ }
10153
+ #evidenceFor(block, to) {
10154
+ if (to === "delta") return "window";
10155
+ return block.rapSeen ? "rap" : "mpu-span";
10156
+ }
10157
+ };
10158
+ function durationMs(units, before) {
10159
+ if (before.durationTicks === void 0 || before.timescale === void 0 || before.timescale <= 0) {
10160
+ return null;
10161
+ }
10162
+ return units * before.durationTicks * 1e3 / before.timescale;
10163
+ }
10164
+ function decideGap(input) {
10165
+ const { before, after } = input;
10166
+ let action;
10167
+ let reason;
10168
+ let missingFrames = null;
10169
+ if (input.trackKind === "audio") {
10170
+ action = "conceal";
10171
+ reason = "audio-discontinuity";
10172
+ if (!input.discontinuity && before.pts !== void 0 && after.pts !== void 0 && before.durationTicks !== void 0 && Number.isSafeInteger(before.durationTicks) && before.durationTicks > 0) {
10173
+ const auDuration = BigInt(before.durationTicks);
10174
+ const missingTicks = after.pts - before.pts - auDuration;
10175
+ const bound = input.maxMissingUnits;
10176
+ if (missingTicks > 0n && missingTicks % auDuration === 0n && bound !== null && missingTicks / auDuration <= BigInt(bound)) {
10177
+ reason = "audio-gap";
10178
+ missingFrames = Number(missingTicks / auDuration);
10179
+ }
10180
+ }
10181
+ } else if (input.discontinuity) {
10182
+ action = "stall";
10183
+ reason = "discontinuity";
10184
+ } else if (after.rap) {
10185
+ action = "conceal";
10186
+ reason = "rap-next";
10187
+ } else if (before.mpu === void 0 || after.mpu === void 0) {
10188
+ action = "stall";
10189
+ reason = "rap-unknown";
10190
+ } else if (before.mpu !== after.mpu) {
10191
+ action = "stall";
10192
+ reason = "rap-lost";
10193
+ } else {
10194
+ action = "conceal";
10195
+ reason = "delta-lost";
10196
+ if (before.idx !== void 0 && after.idx !== void 0) {
10197
+ const missing = after.idx - before.idx - 1;
10198
+ missingFrames = missing > 0 ? missing : null;
10199
+ }
10200
+ }
10201
+ return Object.freeze({
10202
+ version: 2,
10203
+ type: "gap",
10204
+ stream: Object.freeze({
10205
+ packetId: input.stream.packetId,
10206
+ catalogTrackName: input.stream.catalogTrackName
10207
+ }),
10208
+ trackKind: input.trackKind,
10209
+ action,
10210
+ reason,
10211
+ blocks: Object.freeze([...input.blocks]),
10212
+ missingFrames,
10213
+ missingMs: missingFrames === null ? null : durationMs(missingFrames, before),
10214
+ epoch: input.epoch
10215
+ });
10216
+ }
10217
+
9783
10218
  // src/fec-manager.ts
9784
10219
  var MIN_INTERLEAVE_DEPTH_MS = 33;
9785
10220
  var WORKER_ERROR_LOG_CAP = 5;
@@ -9793,8 +10228,7 @@ function newFecCounters() {
9793
10228
  duplicateSymbols: 0,
9794
10229
  blocksClean: 0,
9795
10230
  blocksRecovered: 0,
9796
- blocksFailed: 0,
9797
- greenFillFrames: 0
10231
+ blocksFailed: 0
9798
10232
  };
9799
10233
  }
9800
10234
  function dropOldest(collection, count) {
@@ -9857,6 +10291,13 @@ var FECManager = class {
9857
10291
  // Failure remains pending until cleanupComplete acknowledges that queue drain.
9858
10292
  this.#pendingWorkerCleanups = /* @__PURE__ */ new Set();
9859
10293
  this.#pendingWorkerCleanupClients = /* @__PURE__ */ new Map();
10294
+ // One bound per owed cleanup: the acknowledgement is awaited for at most one
10295
+ // catalog-derived block lifetime (fail bound plus repair grace).
10296
+ // A Worker that hangs or drops one message must not leave the block
10297
+ // 'pending' forever, which would park every later frame of its stream in
10298
+ // the in-order release gate. Each entry owns its handle; the callback
10299
+ // checks it still owns the key, so a settled or reset key is never touched.
10300
+ this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
9860
10301
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
9861
10302
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
9862
10303
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
@@ -9874,8 +10315,8 @@ var FECManager = class {
9874
10315
  // WASM removes blocks after recovery; late symbols create empty blocks returning null,
9875
10316
  // which would falsely start new timeouts without this guard.
9876
10317
  //
9877
- // Every insertion goes through #markTerminal, which retires the key one
9878
- // catalog-derived block lifetime later (terminalRetentionMsForPacket). The
10318
+ // Every insertion goes through #markTerminal, which retires the key once its
10319
+ // catalog-derived retention window (terminalRetentionMsForPacket) passes. The
9879
10320
  // previous bound (trim to 500 at 1000) lived in cancelBlockTimeout alone, so
9880
10321
  // a stream whose blocks only failed grew this set without limit (BLO-36599).
9881
10322
  this.#completedBlocks = /* @__PURE__ */ new Set();
@@ -9949,6 +10390,33 @@ var FECManager = class {
9949
10390
  // Worker recovery emits all K source symbols. Track recovery once per block
9950
10391
  // while routing only ESI slots that were absent from the direct source path.
9951
10392
  this.#workerRecoveredBlocks = /* @__PURE__ */ new Set();
10393
+ // ── Keyframe-protected repair policy (block-policy.ts) ──
10394
+ // One classifier per physical stream, built from that stream's geometry.
10395
+ this.#classifiers = /* @__PURE__ */ new Map();
10396
+ // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
10397
+ // rungs can share a packetId with a different framerate or GOP, so the
10398
+ // packet-level geometry is only the geometry of a packet whose streams
10399
+ // were never configured apart (see #geometryFor).
10400
+ this.#streamGeometries = /* @__PURE__ */ new Map();
10401
+ // Terminal outcomes retained for in-order frame release: a failed block is
10402
+ // resolved-with-loss, a completed one resolved-clean.
10403
+ this.#failedBlocks = /* @__PURE__ */ new Set();
10404
+ // A block's class at resolution, so events emitted after the classifier
10405
+ // forgot the block (the router counts a recovery after cancelling the
10406
+ // block) still carry it.
10407
+ this.#resolvedBlockClasses = /* @__PURE__ */ new Map();
10408
+ // Blocks already reported through onBlockRepaired (once per block).
10409
+ this.#repairedBlocks = /* @__PURE__ */ new Set();
10410
+ // Blocks created without any symbol because every symbol vanished.
10411
+ this.#materializedBlocks = /* @__PURE__ */ new Set();
10412
+ // Highest SBN seen per stream and when, for vanished-block detection.
10413
+ this.#highestSbn = /* @__PURE__ */ new Map();
10414
+ // The latest source symbol per stream that carried its MMTP
10415
+ // packet_sequence_number: the anchor that bounds how many blocks the
10416
+ // producer can have started before a later source symbol.
10417
+ this.#sourceAnchors = /* @__PURE__ */ new Map();
10418
+ // Catalog/reset epoch per packetId. Gap decisions carry it for fencing.
10419
+ this.#packetEpochs = /* @__PURE__ */ new Map();
9952
10420
  // Framerate detection state
9953
10421
  this.#fpsDetected = false;
9954
10422
  this.#fecInterleaveDepthMs = 0;
@@ -9970,6 +10438,7 @@ var FECManager = class {
9970
10438
  // arrives via onBlockRecovered callback.
9971
10439
  this.onBlockStarted = null;
9972
10440
  this.onBlockComplete = null;
10441
+ /** A block reached its fail bound. `blockClass` is its class at failure. */
9973
10442
  this.onBlockFailed = null;
9974
10443
  /**
9975
10444
  * Fired once per stream when its Worker decoder stops being routable.
@@ -9993,10 +10462,25 @@ var FECManager = class {
9993
10462
  // (MulticastManager.clearRepairForBlock) can be released and logged.
9994
10463
  this.onRepairNeeded = null;
9995
10464
  this.onRepairResolved = null;
10465
+ /**
10466
+ * A block that could not complete from its first-arrival source symbols
10467
+ * alone was completed anyway: by FEC decode (in-band or QUIC repair
10468
+ * symbols) or, after a D-28 request, by late symbols. Fired once per block.
10469
+ */
10470
+ this.onBlockRepaired = null;
10471
+ /** A block's class changed on new evidence or when classification was disabled. */
10472
+ this.onBlockReclassified = null;
10473
+ /** A video stream's classifier mode was established or changed. */
10474
+ this.onClassifierMode = null;
10475
+ /** A block every symbol of which vanished was created by SBN evidence. */
10476
+ this.onBlockVanished = null;
10477
+ /** A block reached a terminal state (completed, recovered, or failed). */
10478
+ this.onBlockResolved = null;
10479
+ /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
10480
+ this.onSourceDiscontinuity = null;
9996
10481
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
9997
10482
  this.onBlockRecovered = null;
9998
10483
  this.onFecStatsUpdate = null;
9999
- this.onGreenFill = null;
10000
10484
  }
10001
10485
  #fecDecoders;
10002
10486
  #workerClients;
@@ -10015,6 +10499,7 @@ var FECManager = class {
10015
10499
  #lifecycleTrace;
10016
10500
  #pendingWorkerCleanups;
10017
10501
  #pendingWorkerCleanupClients;
10502
+ #pendingWorkerCleanupBounds;
10018
10503
  #blockSourceCounts;
10019
10504
  #blockSourceEsis;
10020
10505
  #blockAuthoredLengths;
@@ -10046,6 +10531,15 @@ var FECManager = class {
10046
10531
  #repairDeadlines;
10047
10532
  #repairDeadlineAtMs;
10048
10533
  #workerRecoveredBlocks;
10534
+ #classifiers;
10535
+ #streamGeometries;
10536
+ #failedBlocks;
10537
+ #resolvedBlockClasses;
10538
+ #repairedBlocks;
10539
+ #materializedBlocks;
10540
+ #highestSbn;
10541
+ #sourceAnchors;
10542
+ #packetEpochs;
10049
10543
  #fpsDetected;
10050
10544
  #fecFps;
10051
10545
  #fecInterleaveDepthMs;
@@ -10128,10 +10622,10 @@ var FECManager = class {
10128
10622
  }
10129
10623
  /**
10130
10624
  * Make `key` terminal: late symbols for it are duplicates from now on. The
10131
- * key is retired one block lifetime later, when no copy of any of its
10132
- * symbols can still be in flight on either transport (see
10133
- * terminalRetentionMsForPacket). Retirement is swept lazily here, on the
10134
- * stream's own terminal events, so it needs no timer.
10625
+ * key is retired terminalRetentionMsForPacket later, when no copy of any of
10626
+ * its symbols can still be in flight on either transport and no frame can
10627
+ * still be held behind it. Retirement is swept lazily here, on the stream's
10628
+ * own terminal events, so it needs no timer.
10135
10629
  */
10136
10630
  #markTerminal(key, sbn, packetId, clean) {
10137
10631
  const nowMs = performance.now();
@@ -10159,6 +10653,9 @@ var FECManager = class {
10159
10653
  this.#completedBlocks.delete(record.key);
10160
10654
  this.#cleanlyCompletedBlocks.delete(record.key);
10161
10655
  this.#workerRecoveredBlocks.delete(record.key);
10656
+ this.#failedBlocks.delete(record.key);
10657
+ this.#resolvedBlockClasses.delete(record.key);
10658
+ this.#repairedBlocks.delete(record.key);
10162
10659
  this.#unindexBlockKey(record.key);
10163
10660
  }
10164
10661
  }
@@ -10311,11 +10808,203 @@ var FECManager = class {
10311
10808
  Math.max(1, Math.ceil(Math.max(now, currentDeadline) + graceMs - now))
10312
10809
  );
10313
10810
  this.#traceLifecycle("repair-requested", sbn, packetId, catalogTrackName);
10314
- if (catalogTrackName === void 0) {
10315
- this.onRepairNeeded(sbn, packetId);
10811
+ this.onRepairNeeded(
10812
+ sbn,
10813
+ packetId,
10814
+ catalogTrackName,
10815
+ this.blockClassFor(sbn, packetId, catalogTrackName)
10816
+ );
10817
+ }
10818
+ // ── Keyframe-protected repair policy ──
10819
+ /**
10820
+ * The classifier geometry of one stream. A stream-scoped configuration
10821
+ * wins. Once any stream of a packetId was configured with its own geometry,
10822
+ * a sibling stream without one has none that provably belongs to it: the
10823
+ * packet-level geometry may be another rung's (a different framerate or
10824
+ * GOP), so it runs all-protected (`stream-geometry-absent`).
10825
+ */
10826
+ #geometryFor(packetId, catalogTrackName) {
10827
+ const own = this.#streamGeometries.get(this.#streamKey(packetId, catalogTrackName));
10828
+ if (own) return own;
10829
+ const config = this.#trackConfigs.get(packetId);
10830
+ if (config?.trackKind === "audio") return { trackKind: "audio" };
10831
+ for (const key of this.#streamGeometries.keys()) {
10832
+ if (this.#belongsToPacket(key, packetId)) {
10833
+ return { trackKind: "video", mode: "all-protected", reason: "stream-geometry-absent" };
10834
+ }
10835
+ }
10836
+ if (config?.geometry) return config.geometry;
10837
+ return { trackKind: "video", mode: "all-protected", reason: "keyframe-cadence-absent" };
10838
+ }
10839
+ #classifierFor(packetId, catalogTrackName) {
10840
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
10841
+ let classifier = this.#classifiers.get(streamKey);
10842
+ if (!classifier) {
10843
+ classifier = new BlockClassifier(this.#geometryFor(packetId, catalogTrackName));
10844
+ this.#classifiers.set(streamKey, classifier);
10845
+ if (classifier.geometry.trackKind === "video") {
10846
+ this.onClassifierMode?.(packetId, catalogTrackName, classifier.mode, classifier.reason);
10847
+ }
10848
+ }
10849
+ return classifier;
10850
+ }
10851
+ #applyClassifierChanges(packetId, catalogTrackName, changes) {
10852
+ for (const change of changes) {
10853
+ if (change.kind === "mode") {
10854
+ this.onClassifierMode?.(packetId, catalogTrackName, change.mode, change.reason);
10855
+ } else {
10856
+ this.onBlockReclassified?.(
10857
+ change.sbn,
10858
+ packetId,
10859
+ catalogTrackName,
10860
+ change.from,
10861
+ change.to,
10862
+ change.evidence
10863
+ );
10864
+ }
10865
+ }
10866
+ }
10867
+ /**
10868
+ * Freeze a block's class at resolution and drop its classifier state. The
10869
+ * frozen class answers every later query (a recovery counted after the
10870
+ * block was cancelled, a failure event) exactly.
10871
+ */
10872
+ #retireBlockClass(key, sbn, packetId, catalogTrackName) {
10873
+ const frozen = this.#resolvedBlockClasses.get(key);
10874
+ if (frozen !== void 0) return frozen;
10875
+ const blockClass = this.#peekClass(sbn, packetId, catalogTrackName);
10876
+ this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.forget(sbn);
10877
+ this.#resolvedBlockClasses.set(key, blockClass);
10878
+ this.#materializedBlocks.delete(key);
10879
+ return blockClass;
10880
+ }
10881
+ /** A block's live class without creating classifier state for the stream. */
10882
+ #peekClass(sbn, packetId, catalogTrackName) {
10883
+ const classifier = this.#classifiers.get(this.#streamKey(packetId, catalogTrackName));
10884
+ if (classifier) return classifier.classOf(sbn);
10885
+ return this.#geometryFor(packetId, catalogTrackName).trackKind === "audio" ? "audio" : "unknown";
10886
+ }
10887
+ #viaFor(key) {
10888
+ return (this.#blockPathCounts.get(key)?.moqSymbols ?? 0) > 0 ? "quic" : "inband";
10889
+ }
10890
+ #noteBlockRepaired(key, sbn, packetId, catalogTrackName) {
10891
+ if (this.#repairedBlocks.has(key)) return;
10892
+ this.#repairedBlocks.add(key);
10893
+ this.onBlockRepaired?.(
10894
+ sbn,
10895
+ packetId,
10896
+ catalogTrackName,
10897
+ this.blockClassFor(sbn, packetId, catalogTrackName),
10898
+ this.#viaFor(key)
10899
+ );
10900
+ }
10901
+ #liveWindowBlocks(config) {
10902
+ if (config.interleaveDepthMs < MIN_INTERLEAVE_DEPTH_MS || config.timeoutMs <= 0) return null;
10903
+ return Math.ceil(config.timeoutMs / config.interleaveDepthMs);
10904
+ }
10905
+ /**
10906
+ * Record that a symbol for block `sbn` arrived and materialise any blocks
10907
+ * that vanished entirely between the stream's highest SBN and this one.
10908
+ *
10909
+ * The newest ceil(timeoutMs / interleaveDepthMs) vanished blocks may still
10910
+ * be repairable, so they get the normal repair and fail deadlines, armed
10911
+ * from now. Older ones are already past their fail bound and fail now, as
10912
+ * class `unknown`. A SOURCE symbol whose SBN goes back further than one
10913
+ * live window, or jumps further than the stream could have produced since
10914
+ * its last symbol, is a source discontinuity, not loss. A repair symbol can
10915
+ * only advance the frontier: a D-28 fetch legitimately answers for an old
10916
+ * block, so it never signals a discontinuity.
10917
+ *
10918
+ * The producer closes a block at its Dth media-unit boundary OR when K
10919
+ * source symbols filled it, so one interleave span can start several
10920
+ * blocks (every large keyframe does). What bounds a forward jump is
10921
+ * therefore packet evidence, not a block rate: with the MMTP
10922
+ * packet_sequence_number (contiguous per packet_id, ISO/IEC 23008-1) of
10923
+ * both source symbols, every block strictly between them holds at least one
10924
+ * of the packets sent strictly between them, and K-closes can add at most
10925
+ * one block per K of those packets on top of the D-closes elapsed time
10926
+ * allows. Without it, only the D-close rate is known.
10927
+ */
10928
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber) {
10929
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
10930
+ const now = performance.now();
10931
+ const previous = this.#highestSbn.get(streamKey);
10932
+ const anchor = this.#sourceAnchors.get(streamKey);
10933
+ const psn = symbol === "source" && packetSequenceNumber !== void 0 && Number.isSafeInteger(packetSequenceNumber) && packetSequenceNumber >= 0 && packetSequenceNumber <= 4294967295 ? packetSequenceNumber : void 0;
10934
+ const anchorHere = () => {
10935
+ if (psn !== void 0 && (anchor === void 0 || sbn >= anchor.sbn)) {
10936
+ this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
10937
+ }
10938
+ };
10939
+ const discontinuity = () => {
10940
+ this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
10941
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
10942
+ if (psn === void 0) this.#sourceAnchors.delete(streamKey);
10943
+ else this.#sourceAnchors.set(streamKey, { sbn, psn, atMs: now });
10944
+ this.onSourceDiscontinuity?.(packetId, catalogTrackName);
10945
+ };
10946
+ if (previous === void 0) {
10947
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
10948
+ anchorHere();
10949
+ return;
10950
+ }
10951
+ const config = this.#resolveTrackConfig(packetId);
10952
+ const window2 = this.#liveWindowBlocks(config);
10953
+ if (sbn <= previous.sbn) {
10954
+ if (symbol === "source" && window2 !== null && sbn + window2 < previous.sbn) {
10955
+ discontinuity();
10956
+ return;
10957
+ }
10958
+ anchorHere();
10959
+ return;
10960
+ }
10961
+ const missing = sbn - previous.sbn - 1;
10962
+ let plausible = true;
10963
+ if (window2 !== null) {
10964
+ if (psn !== void 0 && anchor !== void 0 && anchor.sbn < sbn && psn !== anchor.psn) {
10965
+ const sent = psn - anchor.psn >>> 0;
10966
+ const between = sbn - anchor.sbn - 1;
10967
+ const dCloses = window2 + Math.ceil((now - anchor.atMs) / config.interleaveDepthMs);
10968
+ const kCloses = config.k > 0 ? Math.ceil(sent / config.k) : sent;
10969
+ plausible = sent <= 2147483647 && between <= sent - 1 && between <= dCloses + kCloses;
10970
+ } else {
10971
+ plausible = missing <= window2 + Math.ceil((now - previous.atMs) / config.interleaveDepthMs);
10972
+ }
10973
+ }
10974
+ if (!plausible) {
10975
+ if (symbol === "repair") return;
10976
+ discontinuity();
10977
+ return;
10978
+ }
10979
+ this.#highestSbn.set(streamKey, { sbn, atMs: now });
10980
+ anchorHere();
10981
+ if (missing <= 0 || window2 === null) return;
10982
+ for (let vanished = previous.sbn + 1; vanished < sbn; vanished++) {
10983
+ this.#materializeBlock(vanished, packetId, catalogTrackName, sbn - vanished <= window2);
10984
+ }
10985
+ }
10986
+ #materializeBlock(sbn, packetId, catalogTrackName, repairable) {
10987
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
10988
+ if (this.#blockResolutionFor(key) !== "untracked") return;
10989
+ this.#materializedBlocks.add(key);
10990
+ this.#classifierFor(packetId, catalogTrackName).touch(sbn);
10991
+ this.onBlockVanished?.(sbn, packetId, catalogTrackName);
10992
+ if (repairable) {
10993
+ this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
10316
10994
  } else {
10317
- this.onRepairNeeded(sbn, packetId, catalogTrackName);
10995
+ this.#failBlock(sbn, packetId, catalogTrackName);
10996
+ }
10997
+ }
10998
+ #blockResolutionFor(key) {
10999
+ if (this.#failedBlocks.has(key)) return "failed";
11000
+ if (this.#completedBlocks.has(key)) return "complete";
11001
+ if (this.#activeBlocks.has(key) || this.#pendingWorkerCleanups.has(key) || this.#repairDeadlines.has(key) || this.#blockSourceCounts.has(key) || this.#blockRepairRsIds.has(key) || this.#materializedBlocks.has(key)) {
11002
+ return "pending";
10318
11003
  }
11004
+ return "untracked";
11005
+ }
11006
+ #bumpEpoch(packetId) {
11007
+ this.#packetEpochs.set(packetId, (this.#packetEpochs.get(packetId) ?? 0) + 1);
10319
11008
  }
10320
11009
  #traceLifecycle(event, sbn, packetId, catalogTrackName, rsId) {
10321
11010
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -10376,6 +11065,10 @@ var FECManager = class {
10376
11065
  }
10377
11066
  return halfFailBoundMs;
10378
11067
  }
11068
+ /** One block lifetime: the inactivity fail bound plus the D-28 repair grace. */
11069
+ #blockLifetimeMs(config) {
11070
+ return config.timeoutMs + this.#repairGraceMs(config);
11071
+ }
10379
11072
  #repairGraceMs(config) {
10380
11073
  return Math.max(1, config.timeoutMs - this.#repairDeadlineMs(config));
10381
11074
  }
@@ -10402,24 +11095,29 @@ var FECManager = class {
10402
11095
  this.#activeBlocks.delete(key);
10403
11096
  this.#activeBlockDeadlinesMs.delete(key);
10404
11097
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
11098
+ if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
11099
+ this.#failBlock(sbn, packetId, catalogTrackName);
11100
+ return;
11101
+ }
10405
11102
  const syncOwner = this.#syncDecoderBlockOwners.get(key);
10406
11103
  if (syncOwner) {
10407
11104
  this.#routeSyncCleanup(syncOwner, sbn, packetId);
10408
- this.#failBlock(sbn, packetId, false, catalogTrackName);
11105
+ this.#failBlock(sbn, packetId, catalogTrackName);
10409
11106
  return;
10410
11107
  }
10411
11108
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
10412
11109
  if (workerClient) {
10413
11110
  this.#pendingWorkerCleanups.add(key);
10414
11111
  this.#pendingWorkerCleanupClients.set(key, workerClient);
11112
+ this.#boundOwedCleanup(key, packetId, workerClient);
10415
11113
  workerClient.cleanup(sbn);
10416
11114
  } else {
10417
11115
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
10418
11116
  if (decoder) {
10419
11117
  this.#routeSyncCleanup(decoder, sbn, packetId);
10420
- this.#failBlock(sbn, packetId, false, catalogTrackName);
11118
+ this.#failBlock(sbn, packetId, catalogTrackName);
10421
11119
  } else {
10422
- this.#failBlock(sbn, packetId, false, catalogTrackName);
11120
+ this.#failBlock(sbn, packetId, catalogTrackName);
10423
11121
  }
10424
11122
  }
10425
11123
  };
@@ -10427,18 +11125,50 @@ var FECManager = class {
10427
11125
  this.#activeBlocks.set(key, timer);
10428
11126
  this.#indexBlockKey(key, sbn, packetId);
10429
11127
  }
10430
- #upsertTrackConfig(packetId, config) {
11128
+ /**
11129
+ * Upsert one packetId's track configuration. With `catalogTrackName`, the
11130
+ * classifier geometry in `config` is that stream's own and is kept per
11131
+ * stream; every other field stays per packetId.
11132
+ */
11133
+ #upsertTrackConfig(packetId, config, catalogTrackName) {
10431
11134
  const previous = this.#trackConfigs.get(packetId) ?? this.#defaultTrackConfig();
11135
+ const streamScopedGeometry = catalogTrackName !== void 0 && config.geometry !== void 0 ? config.geometry : void 0;
11136
+ if (streamScopedGeometry !== void 0) {
11137
+ const { geometry: _streamGeometry, ...packetLevel } = config;
11138
+ config = packetLevel;
11139
+ }
10432
11140
  const timingChanged = config.k !== void 0 || config.interleaveDepthMs !== void 0 || config.fps !== void 0;
10433
11141
  const next = {
10434
11142
  k: config.k ?? previous.k,
10435
11143
  symbolSize: config.symbolSize != null && config.symbolSize > 0 ? config.symbolSize : previous.symbolSize,
10436
11144
  interleaveDepthMs: config.interleaveDepthMs ?? previous.interleaveDepthMs,
10437
11145
  fps: config.fps ?? previous.fps,
10438
- timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs)
11146
+ timeoutMs: config.timeoutMs ?? (timingChanged ? 0 : previous.timeoutMs),
11147
+ ...(config.trackKind ?? previous.trackKind) === void 0 ? {} : { trackKind: config.trackKind ?? previous.trackKind },
11148
+ ...(config.codec ?? previous.codec) === void 0 ? {} : { codec: config.codec ?? previous.codec },
11149
+ ...(config.geometry ?? previous.geometry) === void 0 ? {} : { geometry: config.geometry ?? previous.geometry }
10439
11150
  };
10440
11151
  next.timeoutMs = this.#computeTimeout(next);
10441
11152
  this.#trackConfigs.set(packetId, next);
11153
+ let policyChanged = config.geometry !== void 0 && JSON.stringify(config.geometry) !== JSON.stringify(previous.geometry) || config.trackKind !== void 0 && config.trackKind !== previous.trackKind;
11154
+ if (streamScopedGeometry !== void 0) {
11155
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
11156
+ if (JSON.stringify(streamScopedGeometry) !== JSON.stringify(this.#streamGeometries.get(streamKey))) {
11157
+ this.#streamGeometries.set(streamKey, streamScopedGeometry);
11158
+ policyChanged = true;
11159
+ }
11160
+ }
11161
+ if (policyChanged) {
11162
+ this.#bumpEpoch(packetId);
11163
+ for (const [key, classifier] of [...this.#classifiers]) {
11164
+ if (!this.#belongsToPacket(key, packetId)) continue;
11165
+ const stream = this.#parseStreamKey(key);
11166
+ const geometry = this.#geometryFor(stream.packetId, stream.catalogTrackName);
11167
+ if (JSON.stringify(geometry) === JSON.stringify(classifier.geometry)) continue;
11168
+ this.#classifiers.delete(key);
11169
+ this.#applyClassifierChanges(stream.packetId, stream.catalogTrackName, classifier.retire());
11170
+ }
11171
+ }
10442
11172
  return next;
10443
11173
  }
10444
11174
  #normalizeSymbolData(packetId, data) {
@@ -10588,6 +11318,9 @@ var FECManager = class {
10588
11318
  resetMap(this.#repairDeadlineAtMs);
10589
11319
  resetMap(this.#terminalExpiryMs);
10590
11320
  resetMap(this.#pendingWorkerCleanupClients);
11321
+ for (const key of [...this.#pendingWorkerCleanupBounds.keys()]) {
11322
+ if (this.#belongsToStream(key, packetId, catalogTrackName)) this.#clearOwedCleanupBound(key);
11323
+ }
10591
11324
  resetMap(this.#blockSourceCounts);
10592
11325
  resetMap(this.#blockSourceEsis);
10593
11326
  resetMap(this.#blockAuthoredLengths);
@@ -10606,6 +11339,14 @@ var FECManager = class {
10606
11339
  resetSet(this.#startupRepairReadyPackets);
10607
11340
  resetSet(this.#startupRepairFailOpenPackets);
10608
11341
  resetSet(this.#seenSymbols);
11342
+ resetSet(this.#failedBlocks);
11343
+ resetSet(this.#repairedBlocks);
11344
+ resetSet(this.#materializedBlocks);
11345
+ resetMap(this.#resolvedBlockClasses);
11346
+ resetMap(this.#highestSbn);
11347
+ resetMap(this.#sourceAnchors);
11348
+ this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
11349
+ this.#bumpEpoch(packetId);
10609
11350
  for (const [sbn, keys] of this.#blockKeysBySbn) {
10610
11351
  for (const key of keys.keys()) {
10611
11352
  if (this.#belongsToStream(key, packetId, catalogTrackName)) keys.delete(key);
@@ -10808,17 +11549,25 @@ var FECManager = class {
10808
11549
  return this.#repairDeadlineMs(this.#resolveTrackConfig(packetId));
10809
11550
  }
10810
11551
  /**
10811
- * How long a terminal (clean, recovered or failed) block stays authoritative
10812
- * for late symbols: one full block lifetime, i.e. the inactivity fail bound
10813
- * plus the D-28 repair grace a repair-requested block may be granted. No
10814
- * copy of a block's symbols is useful, or awaited, beyond the moment the
10815
- * block itself would have been failed, so a copy arriving later is dropped
10816
- * by the other bounded ledgers rather than by this one. Both terms come from
10817
- * the track's catalog geometry; there is no separate cap.
11552
+ * One block lifetime: the longest a block stays open after its last symbol
11553
+ * (inactivity fail bound plus D-28 repair grace).
11554
+ */
11555
+ blockLifetimeMsForPacket(packetId) {
11556
+ return this.#blockLifetimeMs(this.#resolveTrackConfig(packetId));
11557
+ }
11558
+ /**
11559
+ * How long a terminal (clean, recovered or failed) block stays authoritative,
11560
+ * for late symbols and for the in-order release gate. It is also the gate's
11561
+ * hold ceiling (MmtpRouter's holdLimitMs): a retired block reads back as
11562
+ * untracked, which the gate counts as lost, so no frame may still be waiting
11563
+ * on a block that can retire. The window is one interleave depth for a gap's
11564
+ * last block to finish arriving, one block lifetime to fail it, and one more
11565
+ * for an owed Worker cleanup that can keep a failing block pending. Every
11566
+ * term comes from the track's catalog geometry; there is no separate cap.
10818
11567
  */
10819
11568
  terminalRetentionMsForPacket(packetId) {
10820
11569
  const config = this.#resolveTrackConfig(packetId);
10821
- return config.timeoutMs + this.#repairGraceMs(config);
11570
+ return config.interleaveDepthMs + 2 * this.#blockLifetimeMs(config);
10822
11571
  }
10823
11572
  /** Remaining fetch budget for a specific repair-requested block. */
10824
11573
  repairFetchTimeoutMsForBlock(sbn, packetId, catalogTrackName) {
@@ -10831,14 +11580,85 @@ var FECManager = class {
10831
11580
  const trackConfig = this.#resolveTrackConfig(packetId);
10832
11581
  return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
10833
11582
  }
10834
- // -----------------------------------------------------------------------
10835
- // Configuration
10836
- // -----------------------------------------------------------------------
10837
- /** Configure FEC parameters. */
10838
- configure(config) {
10839
- if (config.k != null) this.#fecK = config.k;
10840
- if (config.symbolSize != null && config.symbolSize > 0) this.#fecSymbolSize = config.symbolSize;
10841
- if (config.interleaveDepthMs != null) this.#fecInterleaveDepthMs = config.interleaveDepthMs;
11583
+ /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
11584
+ isTrackConfigured(packetId) {
11585
+ return this.#trackConfigs.has(packetId);
11586
+ }
11587
+ /** Catalog/reset epoch of a packet's streams; gap decisions carry it. */
11588
+ epochFor(packetId) {
11589
+ return this.#packetEpochs.get(packetId) ?? 0;
11590
+ }
11591
+ /** Configured media kind of a packetId, when known. */
11592
+ trackKindFor(packetId) {
11593
+ return this.#trackConfigs.get(packetId)?.trackKind;
11594
+ }
11595
+ /** Configured codec of a packetId, when known. */
11596
+ codecFor(packetId) {
11597
+ return this.#trackConfigs.get(packetId)?.codec;
11598
+ }
11599
+ /**
11600
+ * Block classifier geometry of one stream: its own stream-scoped geometry,
11601
+ * else the packet's (fail-closed when absent, or when a sibling stream of
11602
+ * the packet has its own geometry and this one has none).
11603
+ */
11604
+ geometryFor(packetId, catalogTrackName) {
11605
+ return this.#geometryFor(packetId, catalogTrackName);
11606
+ }
11607
+ /** Current classifier mode of a stream. */
11608
+ classifierModeFor(packetId, catalogTrackName) {
11609
+ const classifier = this.#classifierFor(packetId, catalogTrackName);
11610
+ return { mode: classifier.mode, reason: classifier.reason };
11611
+ }
11612
+ /**
11613
+ * Whether an MPU boundary still bounds this stream's RAPs (see
11614
+ * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
11615
+ * it does not. A stream with no classifier yet has shown nothing against it.
11616
+ */
11617
+ mpuBoundsRapsFor(packetId, catalogTrackName) {
11618
+ return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
11619
+ }
11620
+ /** A block's class now, or frozen at its resolution. */
11621
+ blockClassFor(sbn, packetId, catalogTrackName) {
11622
+ const frozen = this.#resolvedBlockClasses.get(this.#blockKey(sbn, packetId, catalogTrackName));
11623
+ if (frozen !== void 0) return frozen;
11624
+ return this.#peekClass(sbn, packetId, catalogTrackName);
11625
+ }
11626
+ /**
11627
+ * Lifecycle resolution of one block for in-order frame release: `pending`
11628
+ * while it can still complete, `complete`/`failed` once terminal, and
11629
+ * `untracked` when no symbol of it was ever accepted.
11630
+ */
11631
+ blockResolution(sbn, packetId, catalogTrackName) {
11632
+ return this.#blockResolutionFor(this.#blockKey(sbn, packetId, catalogTrackName));
11633
+ }
11634
+ /** Highest SBN any symbol of this stream carried in the current epoch. */
11635
+ highestSbn(packetId, catalogTrackName) {
11636
+ return this.#highestSbn.get(this.#streamKey(packetId, catalogTrackName))?.sbn;
11637
+ }
11638
+ /**
11639
+ * Record a RAP frame released in order, for the classifier's RAP-spacing
11640
+ * invariant (consecutive MPUs exactly one keyframe interval apart).
11641
+ */
11642
+ noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
11643
+ if (!this.#trackConfigs.has(packetId)) return;
11644
+ this.#applyClassifierChanges(
11645
+ packetId,
11646
+ catalogTrackName,
11647
+ this.#classifierFor(packetId, catalogTrackName).noteReleasedRap(
11648
+ mpu,
11649
+ presentationTime,
11650
+ mediaTimescale
11651
+ )
11652
+ );
11653
+ }
11654
+ // -----------------------------------------------------------------------
11655
+ // Configuration
11656
+ // -----------------------------------------------------------------------
11657
+ /** Configure FEC parameters. */
11658
+ configure(config) {
11659
+ if (config.k != null) this.#fecK = config.k;
11660
+ if (config.symbolSize != null && config.symbolSize > 0) this.#fecSymbolSize = config.symbolSize;
11661
+ if (config.interleaveDepthMs != null) this.#fecInterleaveDepthMs = config.interleaveDepthMs;
10842
11662
  if (config.fps != null && Number.isFinite(config.fps) && config.fps > 0) {
10843
11663
  this.#fecFps = config.fps;
10844
11664
  }
@@ -10861,9 +11681,14 @@ var FECManager = class {
10861
11681
  }
10862
11682
  }
10863
11683
  }
10864
- /** Configure FEC parameters for one packetId without changing legacy defaults. */
10865
- configureTrack(packetId, config) {
10866
- this.#upsertTrackConfig(packetId, config);
11684
+ /**
11685
+ * Configure FEC parameters for one packetId without changing legacy
11686
+ * defaults. With `catalogTrackName`, `config.geometry` is that stream's
11687
+ * own classifier geometry (ABR rungs that share a packetId each get
11688
+ * theirs); K, T, timing, kind and codec stay per packetId.
11689
+ */
11690
+ configureTrack(packetId, config, catalogTrackName) {
11691
+ this.#upsertTrackConfig(packetId, config, catalogTrackName);
10867
11692
  }
10868
11693
  /** Register a FEC decoder for a specific packetId (track). */
10869
11694
  setFecDecoder(packetId, client, k, config, catalogTrackName) {
@@ -10874,7 +11699,7 @@ var FECManager = class {
10874
11699
  [...this.#fecDecoders].map(([key, entry]) => [key, entry.client]),
10875
11700
  "decoder"
10876
11701
  );
10877
- const trackConfig = this.#upsertTrackConfig(packetId, { ...config, k });
11702
+ const trackConfig = this.#upsertTrackConfig(packetId, { ...config, k }, catalogTrackName);
10878
11703
  this.#fecDecoders.set(streamKey, { client, k: trackConfig.k });
10879
11704
  }
10880
11705
  /**
@@ -10909,7 +11734,7 @@ var FECManager = class {
10909
11734
  `[FECManager] stream ${streamKey} already routes to a Worker; call clearFecWorker before registering another`
10910
11735
  );
10911
11736
  }
10912
- if (config) this.#upsertTrackConfig(packetId, config);
11737
+ if (config) this.#upsertTrackConfig(packetId, config, catalogTrackName);
10913
11738
  const workerK = this.#resolveTrackConfig(packetId).k;
10914
11739
  this.#workerClients.set(streamKey, client);
10915
11740
  client.onFrame((data, meta) => {
@@ -10955,6 +11780,7 @@ var FECManager = class {
10955
11780
  if (this.#workerRecoveredBlocks.size > 1e3) {
10956
11781
  dropOldest(this.#workerRecoveredBlocks, 500);
10957
11782
  }
11783
+ this.#noteBlockRepaired(blockKey, meta.sbn, packetId, recoveredCatalogTrackName);
10958
11784
  }
10959
11785
  const symbolKey = `${blockKey}:${esi}`;
10960
11786
  if (!this.#seenSymbols.has(symbolKey)) {
@@ -11000,11 +11826,6 @@ var FECManager = class {
11000
11826
  }
11001
11827
  }
11002
11828
  });
11003
- client.onGreenFill((sbn, data) => {
11004
- this.#fecStats.greenFillFrames++;
11005
- this.#statsForPacket(packetId).greenFillFrames++;
11006
- this.onGreenFill?.(sbn, packetId, data);
11007
- });
11008
11829
  client.onCleanupComplete((sbn) => {
11009
11830
  const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
11010
11831
  const block = this.#parseBlockKey(key);
@@ -11073,18 +11894,46 @@ var FECManager = class {
11073
11894
  for (const key of owed) this.#settleOwedCleanup(key, "decoder-unavailable");
11074
11895
  this.#decoderBlockOwners.delete(client);
11075
11896
  }
11897
+ /**
11898
+ * Bound the wait for one Worker cleanup acknowledgement by the block's
11899
+ * catalog-derived terminal lifetime. When it elapses with the cleanup still
11900
+ * owed to the same client, the block fails as if the ack had arrived: its
11901
+ * fail deadline already passed, so failing it is the decision that deadline
11902
+ * made. A late ack then finds nothing owed and is a no-op.
11903
+ */
11904
+ #boundOwedCleanup(key, packetId, client) {
11905
+ this.#clearOwedCleanupBound(key);
11906
+ const bound = {
11907
+ handle: setTimeout(() => {
11908
+ if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
11909
+ this.#pendingWorkerCleanupBounds.delete(key);
11910
+ if (!this.#pendingWorkerCleanups.has(key) || this.#pendingWorkerCleanupClients.get(key) !== client) {
11911
+ return;
11912
+ }
11913
+ this.#settleOwedCleanup(key, "cleanup-ack-timeout");
11914
+ }, Math.ceil(this.#blockLifetimeMs(this.#resolveTrackConfig(packetId))))
11915
+ };
11916
+ this.#pendingWorkerCleanupBounds.set(key, bound);
11917
+ }
11918
+ #clearOwedCleanupBound(key) {
11919
+ const bound = this.#pendingWorkerCleanupBounds.get(key);
11920
+ if (!bound) return;
11921
+ clearTimeout(bound.handle);
11922
+ this.#pendingWorkerCleanupBounds.delete(key);
11923
+ }
11076
11924
  /**
11077
11925
  * Resolve one owed Worker cleanup: drop the pending entry and fail the block
11078
11926
  * unless it already completed. Shared by the cleanup acknowledgement and by
11079
11927
  * Worker retirement, so the two paths cannot drift in their bookkeeping.
11080
11928
  */
11081
11929
  #settleOwedCleanup(key, event) {
11930
+ this.#clearOwedCleanupBound(key);
11082
11931
  this.#pendingWorkerCleanups.delete(key);
11083
11932
  this.#pendingWorkerCleanupClients.delete(key);
11084
11933
  if (this.#completedBlocks.has(key)) return;
11085
11934
  const block = this.#parseBlockKey(key);
11086
11935
  this.#traceLifecycle(event, block.sbn, block.packetId, block.catalogTrackName);
11087
- this.#failBlock(block.sbn, block.packetId, false, block.catalogTrackName);
11936
+ this.#failBlock(block.sbn, block.packetId, block.catalogTrackName);
11088
11937
  }
11089
11938
  /** Evict a disposed client under every stream key that still maps to it. */
11090
11939
  #evictDisposedWorker(client) {
@@ -11208,6 +12057,7 @@ var FECManager = class {
11208
12057
  const k = this.kForPacket(packetId);
11209
12058
  if (ssbLength <= 0 || ssbLength > k || ssStart % k !== 0) return null;
11210
12059
  const sbn = Math.floor(ssStart / k);
12060
+ this.#noteSbnSeen(sbn, packetId, catalogTrackName, "repair");
11211
12061
  this.noteBlockActivity(sbn, packetId, catalogTrackName);
11212
12062
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
11213
12063
  if (this.#completedBlocks.has(blockKey)) return null;
@@ -11261,7 +12111,7 @@ var FECManager = class {
11261
12111
  }
11262
12112
  const sourceEsis = this.#blockSourceEsis.get(blockKey);
11263
12113
  if (sourceEsis && [...sourceEsis].some((esi) => esi >= ssbLength)) {
11264
- this.#failBlock(sbn, packetId, false, catalogTrackName);
12114
+ this.#failBlock(sbn, packetId, catalogTrackName);
11265
12115
  return false;
11266
12116
  }
11267
12117
  this.#blockAuthoredLengths.set(blockKey, ssbLength);
@@ -11292,53 +12142,47 @@ var FECManager = class {
11292
12142
  if (recovered) this.#syncDecoderBlockOwners.delete(blockKey);
11293
12143
  return recovered;
11294
12144
  }
11295
- #routeSyncCleanup(decoder, sbn, packetId) {
11296
- let framed;
12145
+ #routeSyncCleanup(decoder, sbn, _packetId) {
11297
12146
  try {
11298
- framed = decoder.cleanup_blocks_detailed(Uint32Array.of(sbn));
12147
+ decoder.cleanup_blocks_detailed(Uint32Array.of(sbn));
11299
12148
  } catch (error) {
11300
12149
  console.warn(`[FECManager] Scoped cleanup failed for SBN ${sbn}:`, error);
11301
- return;
11302
- }
11303
- const view2 = new DataView(framed.buffer, framed.byteOffset, framed.byteLength);
11304
- let offset = 0;
11305
- while (offset < framed.byteLength) {
11306
- if (framed.byteLength - offset < 8) {
11307
- console.warn(`[FECManager] Scoped cleanup returned a truncated record for SBN ${sbn}`);
11308
- return;
11309
- }
11310
- const fillSbn = view2.getUint32(offset, false);
11311
- const length = view2.getUint32(offset + 4, false);
11312
- offset += 8;
11313
- if (length > framed.byteLength - offset) {
11314
- console.warn(`[FECManager] Scoped cleanup returned a truncated payload for SBN ${sbn}`);
11315
- return;
11316
- }
11317
- const data = framed.slice(offset, offset + length).buffer;
11318
- offset += length;
11319
- this.#fecStats.greenFillFrames++;
11320
- this.#statsForPacket(packetId).greenFillFrames++;
11321
- this.onGreenFill?.(fillSbn, packetId, data);
11322
12150
  }
11323
12151
  }
11324
12152
  // -----------------------------------------------------------------------
11325
12153
  // Block lifecycle
11326
12154
  // -----------------------------------------------------------------------
11327
12155
  /**
11328
- * Track a source symbol for an FEC block. Refreshes the inactivity deadline
11329
- * on each symbol and marks the block clean when all of its authored source
11330
- * symbols arrived: the SSB_length a repair symbol declared, otherwise K.
12156
+ * Track a first-arrival network source symbol for an FEC block. Refreshes
12157
+ * the inactivity deadline on each symbol, records the symbol's in-band
12158
+ * classification evidence, and marks the block clean when all of its
12159
+ * authored source symbols arrived: the SSB_length a repair symbol declared,
12160
+ * otherwise K.
12161
+ *
12162
+ * Throws for a packetId that was never configured, so a classified block
12163
+ * never reads the manager-global K or timeout.
11331
12164
  */
11332
- trackBlock(sbn, packetId, catalogTrackName, esi) {
12165
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
12166
+ const trackConfig = this.#trackConfigs.get(packetId);
12167
+ if (trackConfig === void 0) {
12168
+ throw new Error(
12169
+ `[FECManager] trackBlock for packetId=${packetId}, which was never configured; configure the track from its catalog (configureTrack/setFecWorker/setFecDecoder) first`
12170
+ );
12171
+ }
11333
12172
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
11334
- const trackConfig = this.#resolveTrackConfig(packetId);
11335
12173
  const k = trackConfig.k;
11336
12174
  if (this.#completedBlocks.has(key)) return;
12175
+ this.#noteSbnSeen(sbn, packetId, catalogTrackName, "source", evidence.packetSequenceNumber);
11337
12176
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
11338
12177
  if (Number.isInteger(esi) && esi >= authoredLength) {
11339
- this.#failBlock(sbn, packetId, false, catalogTrackName);
12178
+ this.#failBlock(sbn, packetId, catalogTrackName);
11340
12179
  return;
11341
12180
  }
12181
+ this.#applyClassifierChanges(
12182
+ packetId,
12183
+ catalogTrackName,
12184
+ this.#classifierFor(packetId, catalogTrackName).observe(sbn, evidence)
12185
+ );
11342
12186
  const count = (this.#blockSourceCounts.get(key) ?? 0) + 1;
11343
12187
  this.#blockSourceCounts.set(key, count);
11344
12188
  if (count === 1) this.#indexBlockKey(key, sbn, packetId);
@@ -11388,7 +12232,9 @@ var FECManager = class {
11388
12232
  if (this.#repairRequestedBlocks.has(key)) return;
11389
12233
  const trackConfig = this.#resolveTrackConfig(packetId);
11390
12234
  const timeoutMs = trackConfig.timeoutMs;
11391
- if (timeoutMs <= 0) return;
12235
+ if (!(timeoutMs > 0)) {
12236
+ throw new Error(`[FECManager] packetId=${packetId} has no positive fail bound (timeoutMs=${timeoutMs})`);
12237
+ }
11392
12238
  const repairDeadline = this.#repairDeadlines.get(key);
11393
12239
  if (this.onRepairNeeded && (repairDeadline === void 0 || sourceProgress)) {
11394
12240
  this.#armRepairDeadline(
@@ -11401,17 +12247,14 @@ var FECManager = class {
11401
12247
  }
11402
12248
  this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
11403
12249
  }
11404
- #failBlock(sbn, packetId, countGreenFill, catalogTrackName) {
12250
+ #failBlock(sbn, packetId, catalogTrackName) {
11405
12251
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
11406
12252
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
11407
12253
  this.#clearRepairDeadline(key);
11408
12254
  this.#clearBlockTimer(key);
12255
+ const blockClass = this.#retireBlockClass(key, sbn, packetId, catalogTrackName);
11409
12256
  if (this.#repairRequestedBlocks.delete(key)) {
11410
- if (catalogTrackName === void 0) {
11411
- this.onRepairResolved?.(sbn, packetId, "failed");
11412
- } else {
11413
- this.onRepairResolved?.(sbn, packetId, "failed", catalogTrackName);
11414
- }
12257
+ this.onRepairResolved?.(sbn, packetId, "failed", catalogTrackName, null);
11415
12258
  }
11416
12259
  this.#blockSourceCounts.delete(key);
11417
12260
  this.#blockSourceEsis.delete(key);
@@ -11419,18 +12262,43 @@ var FECManager = class {
11419
12262
  this.#blockRepairRsIds.delete(key);
11420
12263
  this.#syncDecoderBlockOwners.delete(key);
11421
12264
  this.#markTerminal(key, sbn, packetId, false);
12265
+ this.#failedBlocks.add(key);
11422
12266
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
11423
12267
  this.#fecStats.blocksFailed++;
11424
12268
  this.#statsForPacket(packetId).blocksFailed++;
11425
- if (countGreenFill) {
11426
- this.#fecStats.greenFillFrames++;
11427
- this.#statsForPacket(packetId).greenFillFrames++;
11428
- }
11429
- if (catalogTrackName === void 0) {
11430
- this.onBlockFailed?.(sbn, packetId);
11431
- } else {
11432
- this.onBlockFailed?.(sbn, packetId, catalogTrackName);
12269
+ this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
12270
+ this.onBlockResolved?.(sbn, packetId, catalogTrackName);
12271
+ }
12272
+ /**
12273
+ * Resolve a block as completed (clean, recovered, or externally marked).
12274
+ * A block that had a D-28 repair outstanding counts as repaired: it was
12275
+ * short of its source at the repair deadline and completed anyway.
12276
+ */
12277
+ #resolveCompleted(key) {
12278
+ const block = this.#parseBlockKey(key);
12279
+ this.#markTerminal(key, block.sbn, block.packetId, false);
12280
+ this.#clearOwedCleanupBound(key);
12281
+ this.#pendingWorkerCleanups.delete(key);
12282
+ this.#pendingWorkerCleanupClients.delete(key);
12283
+ this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName);
12284
+ this.#clearRepairDeadline(key);
12285
+ if (this.#repairRequestedBlocks.delete(key)) {
12286
+ this.#noteBlockRepaired(key, block.sbn, block.packetId, block.catalogTrackName);
12287
+ this.onRepairResolved?.(
12288
+ block.sbn,
12289
+ block.packetId,
12290
+ "completed",
12291
+ block.catalogTrackName,
12292
+ this.#viaFor(key)
12293
+ );
11433
12294
  }
12295
+ this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
12296
+ this.#blockSourceCounts.delete(key);
12297
+ this.#blockSourceEsis.delete(key);
12298
+ this.#blockAuthoredLengths.delete(key);
12299
+ this.#blockRepairRsIds.delete(key);
12300
+ this.#clearBlockTimer(key);
12301
+ this.onBlockResolved?.(block.sbn, block.packetId, block.catalogTrackName);
11434
12302
  }
11435
12303
  /** Check whether a block has already been completed (clean or recovered). */
11436
12304
  isBlockCompleted(sbn, packetId, catalogTrackName) {
@@ -11439,35 +12307,25 @@ var FECManager = class {
11439
12307
  /** Mark a block as completed externally (e.g., after routing recovered data). */
11440
12308
  markBlockCompleted(sbn, packetId, catalogTrackName) {
11441
12309
  for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
11442
- const block = this.#parseBlockKey(key);
11443
- this.#markTerminal(key, block.sbn, block.packetId, false);
11444
- this.#pendingWorkerCleanups.delete(key);
11445
- this.#pendingWorkerCleanupClients.delete(key);
11446
- this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName);
11447
- this.#clearRepairDeadline(key);
11448
- if (this.#repairRequestedBlocks.delete(key)) {
11449
- if (block.catalogTrackName === void 0) {
11450
- this.onRepairResolved?.(block.sbn, block.packetId, "completed");
11451
- } else {
11452
- this.onRepairResolved?.(
11453
- block.sbn,
11454
- block.packetId,
11455
- "completed",
11456
- block.catalogTrackName
11457
- );
11458
- }
11459
- }
11460
- this.#blockSourceCounts.delete(key);
11461
- this.#blockSourceEsis.delete(key);
11462
- this.#blockAuthoredLengths.delete(key);
11463
- this.#blockRepairRsIds.delete(key);
11464
- this.#clearBlockTimer(key);
12310
+ this.#resolveCompleted(key);
11465
12311
  }
11466
12312
  }
11467
- /** Increment blocksRecovered stat (called by MmtpRouter after routing recovery). */
11468
- countRecovery(packetId) {
12313
+ /**
12314
+ * Increment blocksRecovered (called by MmtpRouter after routing a
12315
+ * synchronous recovery). With the block's coordinates the recovery is also
12316
+ * reported through onBlockRepaired, once per block.
12317
+ */
12318
+ countRecovery(packetId, sbn, catalogTrackName) {
11469
12319
  this.#fecStats.blocksRecovered++;
11470
12320
  if (packetId != null) this.#statsForPacket(packetId).blocksRecovered++;
12321
+ if (packetId != null && sbn != null) {
12322
+ this.#noteBlockRepaired(
12323
+ this.#blockKey(sbn, packetId, catalogTrackName),
12324
+ sbn,
12325
+ packetId,
12326
+ catalogTrackName
12327
+ );
12328
+ }
11471
12329
  }
11472
12330
  /**
11473
12331
  * Strict delivery provenance for one FEC block.
@@ -11497,29 +12355,7 @@ var FECManager = class {
11497
12355
  /** Cancel block timeout (block completed via clean reception or FEC recovery). */
11498
12356
  cancelBlockTimeout(sbn, packetId, catalogTrackName) {
11499
12357
  for (const key of this.#blockKeysFor(sbn, packetId, catalogTrackName)) {
11500
- const block = this.#parseBlockKey(key);
11501
- this.#markTerminal(key, block.sbn, block.packetId, false);
11502
- this.#pendingWorkerCleanups.delete(key);
11503
- this.#pendingWorkerCleanupClients.delete(key);
11504
- this.#markPathBlockComplete(block.sbn, block.packetId, block.catalogTrackName);
11505
- this.#clearRepairDeadline(key);
11506
- if (this.#repairRequestedBlocks.delete(key)) {
11507
- if (block.catalogTrackName === void 0) {
11508
- this.onRepairResolved?.(block.sbn, block.packetId, "completed");
11509
- } else {
11510
- this.onRepairResolved?.(
11511
- block.sbn,
11512
- block.packetId,
11513
- "completed",
11514
- block.catalogTrackName
11515
- );
11516
- }
11517
- }
11518
- this.#blockSourceCounts.delete(key);
11519
- this.#blockSourceEsis.delete(key);
11520
- this.#blockAuthoredLengths.delete(key);
11521
- this.#blockRepairRsIds.delete(key);
11522
- this.#clearBlockTimer(key);
12358
+ this.#resolveCompleted(key);
11523
12359
  }
11524
12360
  }
11525
12361
  // -----------------------------------------------------------------------
@@ -11533,6 +12369,8 @@ var FECManager = class {
11533
12369
  this.#activeBlockDeadlinesMs.clear();
11534
12370
  this.#pendingWorkerCleanups.clear();
11535
12371
  this.#pendingWorkerCleanupClients.clear();
12372
+ for (const bound of this.#pendingWorkerCleanupBounds.values()) clearTimeout(bound.handle);
12373
+ this.#pendingWorkerCleanupBounds.clear();
11536
12374
  for (const timer of this.#repairDeadlines.values()) {
11537
12375
  if (timer?.handle != null) clearTimeout(timer.handle);
11538
12376
  }
@@ -11559,6 +12397,14 @@ var FECManager = class {
11559
12397
  this.#seenSymbols.clear();
11560
12398
  this.#blockPathCounts.clear();
11561
12399
  this.#blockCatalogTrackNames.clear();
12400
+ this.#classifiers.clear();
12401
+ this.#streamGeometries.clear();
12402
+ this.#failedBlocks.clear();
12403
+ this.#resolvedBlockClasses.clear();
12404
+ this.#repairedBlocks.clear();
12405
+ this.#materializedBlocks.clear();
12406
+ this.#highestSbn.clear();
12407
+ this.#sourceAnchors.clear();
11562
12408
  this.#trackConfigs.clear();
11563
12409
  this.#fecDecoders.clear();
11564
12410
  for (const client of new Set(this.#workerClients.values())) client.dispose();
@@ -12377,6 +13223,199 @@ var FrameSequencer = class {
12377
13223
  return true;
12378
13224
  }
12379
13225
  };
13226
+ function authoredAdjacent(before, after) {
13227
+ const a = before.authoredTiming;
13228
+ const b = after.authoredTiming;
13229
+ if (!a || !b || a.mediaTimescale !== b.mediaTimescale) return false;
13230
+ return b.decodeTime === a.decodeTime + BigInt(a.durationTicks);
13231
+ }
13232
+ function authoredGap(before, after) {
13233
+ const a = before.authoredTiming;
13234
+ const b = after.authoredTiming;
13235
+ if (!a || !b || a.mediaTimescale !== b.mediaTimescale) return false;
13236
+ return b.decodeTime > a.decodeTime + BigInt(a.durationTicks);
13237
+ }
13238
+ var FecReleaseSequencer = class {
13239
+ #streams = /* @__PURE__ */ new Map();
13240
+ #gate;
13241
+ #emit;
13242
+ #recordStat;
13243
+ constructor(gate, emit, recordStat) {
13244
+ this.#gate = gate;
13245
+ this.#emit = emit;
13246
+ this.#recordStat = recordStat;
13247
+ }
13248
+ get buffered() {
13249
+ let total = 0;
13250
+ for (const stream of this.#streams.values()) total += stream.buf.length;
13251
+ return total;
13252
+ }
13253
+ push(streamKey, data, meta, seq) {
13254
+ const frame = { data, meta: { ...meta }, seq, arrivedAtMs: performance.now() };
13255
+ const stream = this.#streamFor(streamKey, meta);
13256
+ if (meta.sourceDiscontinuity) {
13257
+ this.#recordStat("publisherResets");
13258
+ this.#recordStat("droppedOnPublisherReset", stream.buf.length);
13259
+ stream.buf = [];
13260
+ stream.last = null;
13261
+ stream.lastSbn = void 0;
13262
+ stream.discontinuity = false;
13263
+ }
13264
+ if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
13265
+ this.#recordStat("droppedStale");
13266
+ return;
13267
+ }
13268
+ if (stream.last === null) {
13269
+ if (meta.trackType === "video" && !meta.keyframe) {
13270
+ this.#recordStat("droppedBeforeStartupKeyframe");
13271
+ return;
13272
+ }
13273
+ this.#release(stream, frame, void 0);
13274
+ this.#drain(stream);
13275
+ return;
13276
+ }
13277
+ let lo = 0;
13278
+ let hi = stream.buf.length;
13279
+ while (lo < hi) {
13280
+ const mid = lo + hi >>> 1;
13281
+ if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
13282
+ else hi = mid;
13283
+ }
13284
+ stream.buf.splice(lo, 0, frame);
13285
+ this.#drain(stream);
13286
+ }
13287
+ /** Re-evaluate held gaps after FEC state changed. */
13288
+ poke(streamKey) {
13289
+ if (streamKey !== void 0) {
13290
+ const stream = this.#streams.get(streamKey);
13291
+ if (stream) this.#drain(stream);
13292
+ return;
13293
+ }
13294
+ for (const stream of this.#streams.values()) this.#drain(stream);
13295
+ }
13296
+ /**
13297
+ * The source restarted: the next release stalls with `discontinuity`.
13298
+ * Only marks the stream. Frames held behind the restart are released by
13299
+ * the next `poke` (or push), so the caller decides when the drain runs; a
13300
+ * drain from inside FEC bookkeeping would re-enter it mid-update.
13301
+ */
13302
+ markDiscontinuity(streamKey) {
13303
+ const stream = this.#streams.get(streamKey);
13304
+ if (!stream || stream.last === null) return;
13305
+ stream.discontinuity = true;
13306
+ }
13307
+ /** Release everything buffered, in order (finite inputs). */
13308
+ flush() {
13309
+ for (const stream of this.#streams.values()) {
13310
+ this.#drain(stream);
13311
+ while (stream.buf.length > 0) {
13312
+ const head = stream.buf[0];
13313
+ stream.buf.shift();
13314
+ this.#release(stream, head, void 0);
13315
+ }
13316
+ }
13317
+ }
13318
+ discardStream(streamKey) {
13319
+ const stream = this.#streams.get(streamKey);
13320
+ if (!stream) return;
13321
+ this.#recordStat("droppedOnLiveDispose", stream.buf.length);
13322
+ this.#streams.delete(streamKey);
13323
+ }
13324
+ /** Release one packet's buffered frames in order and forget its streams. */
13325
+ flushPacket(packetId) {
13326
+ for (const [key, stream] of this.#streams) {
13327
+ if (stream.packetId !== packetId) continue;
13328
+ this.#drain(stream);
13329
+ while (stream.buf.length > 0) {
13330
+ const head = stream.buf[0];
13331
+ stream.buf.shift();
13332
+ this.#release(stream, head, void 0);
13333
+ }
13334
+ this.#streams.delete(key);
13335
+ }
13336
+ }
13337
+ discardPacket(packetId) {
13338
+ for (const [key, stream] of this.#streams) {
13339
+ if (stream.packetId !== packetId) continue;
13340
+ this.#recordStat("droppedOnLiveDispose", stream.buf.length);
13341
+ this.#streams.delete(key);
13342
+ }
13343
+ }
13344
+ discard() {
13345
+ for (const stream of this.#streams.values()) {
13346
+ this.#recordStat("droppedOnLiveDispose", stream.buf.length);
13347
+ }
13348
+ this.#streams.clear();
13349
+ }
13350
+ #streamFor(streamKey, meta) {
13351
+ let stream = this.#streams.get(streamKey);
13352
+ if (!stream) {
13353
+ stream = {
13354
+ packetId: meta.packetId,
13355
+ ...meta.catalogTrackName === void 0 ? {} : { catalogTrackName: meta.catalogTrackName },
13356
+ buf: [],
13357
+ last: null,
13358
+ lastSbn: void 0,
13359
+ discontinuity: false
13360
+ };
13361
+ this.#streams.set(streamKey, stream);
13362
+ }
13363
+ return stream;
13364
+ }
13365
+ #drain(stream) {
13366
+ while (stream.buf.length > 0 && stream.last !== null) {
13367
+ const head = stream.buf[0];
13368
+ const last = stream.last;
13369
+ if (stream.discontinuity) {
13370
+ stream.discontinuity = false;
13371
+ stream.buf.shift();
13372
+ this.#release(stream, head, this.#gate.decide(last, head, [], true));
13373
+ continue;
13374
+ }
13375
+ if (authoredAdjacent(last.meta, head.meta)) {
13376
+ stream.buf.shift();
13377
+ this.#release(stream, head, void 0);
13378
+ continue;
13379
+ }
13380
+ const headSbn = head.meta.fecSbn;
13381
+ const from = stream.lastSbn ?? headSbn;
13382
+ const to = headSbn ?? stream.lastSbn;
13383
+ let lost = [];
13384
+ const unanchored = from === void 0 && to === void 0;
13385
+ if (from !== void 0 && to !== void 0) {
13386
+ const resolved = this.#gate.resolvedLoss(
13387
+ stream.packetId,
13388
+ stream.catalogTrackName,
13389
+ Math.min(from, to),
13390
+ Math.max(from, to),
13391
+ from
13392
+ );
13393
+ if (resolved === null) {
13394
+ const heldMs = performance.now() - head.arrivedAtMs;
13395
+ if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
13396
+ this.#recordStat("forcedWindowFlushes");
13397
+ stream.buf.shift();
13398
+ this.#release(stream, head, this.#gate.decide(last, head, [], true));
13399
+ continue;
13400
+ }
13401
+ lost = resolved;
13402
+ }
13403
+ stream.buf.shift();
13404
+ this.#release(
13405
+ stream,
13406
+ head,
13407
+ lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
13408
+ );
13409
+ }
13410
+ }
13411
+ #release(stream, frame, decision) {
13412
+ if (decision) frame.meta.gapBefore = decision;
13413
+ stream.last = frame;
13414
+ if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
13415
+ this.#gate.onReleased?.(frame.data, frame.meta);
13416
+ this.#emit(frame.data, frame.meta);
13417
+ }
13418
+ };
12380
13419
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
12381
13420
  function isFmp4Box(data) {
12382
13421
  if (data.length < 8) return false;
@@ -12415,6 +13454,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
12415
13454
  this.#evictedTimingSamples = 0;
12416
13455
  this.#rejectedMovieFragments = 0;
12417
13456
  this.#sequencers = /* @__PURE__ */ new Map();
13457
+ this.#fecGate = null;
13458
+ this.#fecSequencer = null;
12418
13459
  this.#reorderWindow = 0;
12419
13460
  this.#reassemblyPolicy = null;
12420
13461
  this.#frameCb = null;
@@ -12498,6 +13539,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
12498
13539
  maxSegmentsPerSample: maxSubsampleSegments
12499
13540
  };
12500
13541
  this.#defaultTrack = config?.defaultTrack ?? null;
13542
+ if (config?.fecReleaseGate) this.setFecReleaseGate(config.fecReleaseGate);
12501
13543
  if (this.#defaultTrack) this.#validateReassemblyPolicy();
12502
13544
  if (config?.tracks) {
12503
13545
  for (const [id, info] of config.tracks) {
@@ -12519,6 +13561,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
12519
13561
  #evictedTimingSamples;
12520
13562
  #rejectedMovieFragments;
12521
13563
  #sequencers;
13564
+ #fecGate;
13565
+ #fecSequencer;
12522
13566
  #reorderWindow;
12523
13567
  #reassemblyPolicy;
12524
13568
  #frameCb;
@@ -12636,10 +13680,63 @@ var MmtpContainerParser = class _MmtpContainerParser {
12636
13680
  };
12637
13681
  }
12638
13682
  get reorderStats() {
12639
- let bufferedFrames = 0;
13683
+ let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
12640
13684
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
12641
13685
  return { ...this.#reorderStats, bufferedFrames };
12642
13686
  }
13687
+ /**
13688
+ * Install (or remove) the in-order release policy for FEC-protected
13689
+ * streams. Streams the gate claims are released by block resolution; all
13690
+ * others keep the frame-count reorder window.
13691
+ */
13692
+ setFecReleaseGate(gate) {
13693
+ this.#fecSequencer?.flush();
13694
+ this.#fecGate = gate;
13695
+ this.#fecSequencer = gate ? new FecReleaseSequencer(
13696
+ gate,
13697
+ (data, meta) => this.#emitFrame(data, meta),
13698
+ (stat, count = 1) => {
13699
+ this.#reorderStats[stat] += count;
13700
+ }
13701
+ ) : null;
13702
+ }
13703
+ /** Re-evaluate held gaps after FEC block state changed. */
13704
+ pokeFecRelease(packetId, catalogTrackName) {
13705
+ if (!this.#fecSequencer) return;
13706
+ this.#fecSequencer.poke(
13707
+ packetId === void 0 ? void 0 : this.#streamKey(packetId, catalogTrackName)
13708
+ );
13709
+ }
13710
+ /**
13711
+ * The FEC source of a stream restarted: stall the next release. Marks
13712
+ * only; follow with `pokeFecRelease` to release frames held behind it.
13713
+ */
13714
+ markFecDiscontinuity(packetId, catalogTrackName) {
13715
+ this.#fecSequencer?.markDiscontinuity(this.#streamKey(packetId, catalogTrackName));
13716
+ }
13717
+ /**
13718
+ * MPU and data-unit identity of one MMTP packet, parsed in place (no copy,
13719
+ * no reassembly). Null for non-MPU packets and packets that do not parse.
13720
+ * `header` is the packet's already-parsed MMTP header (parsePacket()), so
13721
+ * the header is not parsed a second time (BLO-36599).
13722
+ */
13723
+ static sourcePacketIdentity(packet, header) {
13724
+ try {
13725
+ const extraction = extractMFUPayloadWithHeader(packet, header);
13726
+ if (!extraction) return null;
13727
+ const identity = {
13728
+ mpuSequenceNumber: extraction.mpu.mpuSequenceNumber
13729
+ };
13730
+ if (extraction.mfuDuHeader) {
13731
+ identity.sampleNumber = extraction.mfuDuHeader.sampleNumber;
13732
+ identity.movieFragmentSequenceNumber = extraction.mfuDuHeader.movieFragmentSequenceNumber;
13733
+ identity.offset = extraction.mfuDuHeader.offset;
13734
+ }
13735
+ return identity;
13736
+ } catch {
13737
+ return null;
13738
+ }
13739
+ }
12643
13740
  /**
12644
13741
  * Feed tallies for this parser. A fresh snapshot per call, not a live view,
12645
13742
  * so a caller can hold one and compare it against a later read.
@@ -12898,7 +13995,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
12898
13995
  readyOnRegister,
12899
13996
  info,
12900
13997
  resolver,
12901
- options?.recovered === true
13998
+ options?.recovered === true,
13999
+ options?.fecSbn
12902
14000
  );
12903
14001
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
12904
14002
  }
@@ -12989,7 +14087,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
12989
14087
  combined,
12990
14088
  info,
12991
14089
  resolver,
12992
- options?.recovered === true
14090
+ options?.recovered === true,
14091
+ options?.fecSbn
12993
14092
  );
12994
14093
  if (outcome.record !== void 0) return outcome.record;
12995
14094
  return this.#drop(outcome.reason);
@@ -13009,7 +14108,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13009
14108
  * attribution exists to keep readable. Leaving the choice at the call site
13010
14109
  * is what keeps both true.
13011
14110
  */
13012
- #emitCombinedSample(combined, info, resolver, recovered) {
14111
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
13013
14112
  const timing = resolver.sampleTiming(
13014
14113
  combined.mpuSequenceNumber,
13015
14114
  combined.movieFragmentSequenceNumber,
@@ -13025,6 +14124,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13025
14124
  recovered
13026
14125
  );
13027
14126
  if (!meta) return { reason: "combined-meta-build-failed" };
14127
+ if (fecSbn !== void 0) meta.fecSbn = fecSbn;
13028
14128
  if (!resolver.consumeSample(
13029
14129
  combined.mpuSequenceNumber,
13030
14130
  combined.movieFragmentSequenceNumber,
@@ -13078,6 +14178,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13078
14178
  entry.sequencer.flush();
13079
14179
  this.#sequencers.delete(key);
13080
14180
  }
14181
+ this.#fecSequencer?.flushPacket(packetId);
13081
14182
  for (const [key, state] of this.#timingStreams) {
13082
14183
  if (state.packetId === packetId) this.#dropTimingStream(key);
13083
14184
  }
@@ -13102,6 +14203,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
13102
14203
  this.#sequencers.delete(key);
13103
14204
  }
13104
14205
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14206
+ this.#fecSequencer?.discardStream(streamKey);
13105
14207
  this.#dropTimingStream(streamKey);
13106
14208
  this.#reliableMoqStartupGate.delete(streamKey);
13107
14209
  this.#reassembler.resetStream(catalogTrackName);
@@ -13134,6 +14236,15 @@ var MmtpContainerParser = class _MmtpContainerParser {
13134
14236
  * with direct source frames before the decoder sees them. */
13135
14237
  routeFrame(data, meta) {
13136
14238
  const seq = meta.packetSequenceNumber;
14239
+ if (this.#fecSequencer && this.#fecGate?.gates(meta.packetId, meta.catalogTrackName)) {
14240
+ this.#fecSequencer.push(
14241
+ this.#streamKey(meta.packetId, meta.catalogTrackName),
14242
+ data,
14243
+ meta,
14244
+ seq !== void 0 && Number.isFinite(seq) ? seq : 0
14245
+ );
14246
+ return;
14247
+ }
13137
14248
  const sequencer = this.#sequencerFor(meta.packetId, meta.trackType, meta.catalogTrackName);
13138
14249
  if (sequencer && seq !== void 0 && Number.isFinite(seq)) {
13139
14250
  sequencer.push(data, meta, seq);
@@ -13198,11 +14309,13 @@ var MmtpContainerParser = class _MmtpContainerParser {
13198
14309
  flush() {
13199
14310
  if (this.#disposed) return;
13200
14311
  this.#flushSequencers();
14312
+ this.#fecSequencer?.flush();
13201
14313
  }
13202
14314
  dispose() {
13203
14315
  this.#disposed = true;
13204
14316
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
13205
14317
  this.#sequencers.clear();
14318
+ this.#fecSequencer?.discard();
13206
14319
  this.#timingStreams.clear();
13207
14320
  this.#pendingTimingSamples = 0;
13208
14321
  this.#reliableMoqStartupGate.clear();
@@ -13454,6 +14567,225 @@ function findAnnexBStart(data, offset) {
13454
14567
  return null;
13455
14568
  }
13456
14569
 
14570
+ // src/duplicate-ledger.ts
14571
+ var COUNT_BOUNDED_GENERATION = 2e3;
14572
+ function serial32Precedes(a, b) {
14573
+ const distance = b - a >>> 0;
14574
+ return distance !== 0 && distance < 2147483648;
14575
+ }
14576
+ function assertPositiveMs(name, value) {
14577
+ if (!Number.isFinite(value) || value <= 0) {
14578
+ throw new Error(
14579
+ `[DuplicateLedger] ${name}=${value}. Derive a positive ${name} from the stream catalog through FECManager.`
14580
+ );
14581
+ }
14582
+ }
14583
+ function duplicateRetentionMs(geometry) {
14584
+ assertPositiveMs("blockSpanMs", geometry.blockSpanMs);
14585
+ assertPositiveMs("blockLifetimeMs", geometry.blockLifetimeMs);
14586
+ const untilTerminalMs = geometry.blockLifetimeMs;
14587
+ const terminalRecordMs = geometry.blockLifetimeMs;
14588
+ return geometry.blockSpanMs + untilTerminalMs + terminalRecordMs;
14589
+ }
14590
+ var GenerationalNumberSet = class {
14591
+ #members = /* @__PURE__ */ new Set();
14592
+ #olderCount = 0;
14593
+ #newerCount = 0;
14594
+ #rotations = 0;
14595
+ #floor = void 0;
14596
+ #gate;
14597
+ constructor(gate) {
14598
+ this.#gate = gate;
14599
+ }
14600
+ has(value) {
14601
+ return this.#members.has(value);
14602
+ }
14603
+ add(value) {
14604
+ if (!this.#gate.retaining || this.#members.has(value)) return;
14605
+ this.#members.add(value);
14606
+ if (++this.#newerCount >= COUNT_BOUNDED_GENERATION && this.#gate.countBounded) this.rotate();
14607
+ }
14608
+ /** Retire the older generation; the current one becomes the older. */
14609
+ rotate() {
14610
+ let retiring = this.#olderCount;
14611
+ if (retiring > 0) {
14612
+ for (const value of this.#members) {
14613
+ this.#members.delete(value);
14614
+ if (--retiring === 0) break;
14615
+ }
14616
+ }
14617
+ this.#olderCount = this.#newerCount;
14618
+ this.#newerCount = 0;
14619
+ this.#rotations++;
14620
+ this.#floor = void 0;
14621
+ for (const value of this.#members) {
14622
+ this.#floor = value;
14623
+ break;
14624
+ }
14625
+ }
14626
+ clear() {
14627
+ this.#members.clear();
14628
+ this.#olderCount = 0;
14629
+ this.#newerCount = 0;
14630
+ this.restartAging();
14631
+ }
14632
+ /**
14633
+ * Keep every member but forget how many rotations have passed, so no floor
14634
+ * is reported until two more rotations. A stream that starts timing its
14635
+ * generations calls this: generations rotated by count say nothing about
14636
+ * how long ago their members arrived.
14637
+ */
14638
+ restartAging() {
14639
+ this.#rotations = 0;
14640
+ this.#floor = void 0;
14641
+ }
14642
+ /**
14643
+ * The earliest-arrived member, once it is known to have arrived at least one
14644
+ * full generation ago; `undefined` before that.
14645
+ *
14646
+ * A rotation is triggered by an arriving packet, which is normally the
14647
+ * first member of the new generation (a live stream adds its next packet
14648
+ * within one packet interval otherwise). From the second rotation on, the
14649
+ * older generation therefore began at a rotation, and its first member
14650
+ * arrived about one generation length before now. Before the second
14651
+ * rotation the first member may be a number that simply arrived early out of
14652
+ * order, so no floor is reported.
14653
+ */
14654
+ get horizonFloor() {
14655
+ if (this.#rotations < 2 || this.#olderCount === 0) return void 0;
14656
+ return this.#floor;
14657
+ }
14658
+ get size() {
14659
+ return this.#members.size;
14660
+ }
14661
+ };
14662
+ var StreamDuplicateLedgers = class {
14663
+ #horizon;
14664
+ #now;
14665
+ #retentionMs = null;
14666
+ #countBounded = false;
14667
+ /** Whether the horizon was read since construction or the last clear(). */
14668
+ #horizonRead = false;
14669
+ #generationStartMs = 0;
14670
+ #lastSbn = void 0;
14671
+ /**
14672
+ * @param horizon resolves the stream's current horizon from its FEC
14673
+ * geometry. It is read when the stream moves to a new block, so a catalog
14674
+ * change applies from the next block.
14675
+ * @param now the clock FECManager's deadlines use.
14676
+ */
14677
+ constructor(horizon, now = () => performance.now()) {
14678
+ this.#horizon = horizon;
14679
+ this.#now = now;
14680
+ this.sourceSeqs = new GenerationalNumberSet(this);
14681
+ this.routedSeqs = new GenerationalNumberSet(this);
14682
+ this.parsedSymbols = new GenerationalNumberSet(this);
14683
+ }
14684
+ /**
14685
+ * Note the FEC block (SBN) of the packet about to be looked up, or
14686
+ * `undefined` for a packet without a Source FEC Payload ID. Returns whether
14687
+ * the stream keeps ledgers; while it does not, lookups find nothing and
14688
+ * additions are dropped. The horizon is read on the first packet after
14689
+ * construction or clear(), and again whenever the block changes; a packet
14690
+ * without a coordinate never re-reads it, so a stream without FEC
14691
+ * coordinates resolves its horizon once, not per packet.
14692
+ */
14693
+ advance(sbn) {
14694
+ if (sbn !== void 0) {
14695
+ if (sbn === this.#lastSbn) return this.retaining;
14696
+ this.#lastSbn = sbn;
14697
+ } else if (this.#horizonRead) {
14698
+ if (this.#retentionMs !== null) this.#rotateIfDue(this.#now());
14699
+ return this.retaining;
14700
+ }
14701
+ this.#horizonRead = true;
14702
+ const horizon = this.#horizon();
14703
+ if (horizon.kind === "none") {
14704
+ if (horizon.reason === "no-fec-manager") {
14705
+ this.#forget();
14706
+ } else {
14707
+ this.#retentionMs = null;
14708
+ this.#countBounded = true;
14709
+ }
14710
+ return this.retaining;
14711
+ }
14712
+ const nowMs = this.#now();
14713
+ this.#countBounded = false;
14714
+ if (this.#retentionMs === null) {
14715
+ this.#retentionMs = horizon.retentionMs;
14716
+ this.#generationStartMs = nowMs;
14717
+ this.sourceSeqs.restartAging();
14718
+ this.routedSeqs.restartAging();
14719
+ this.parsedSymbols.restartAging();
14720
+ return true;
14721
+ }
14722
+ this.#retentionMs = horizon.retentionMs;
14723
+ this.#rotateIfDue(nowMs);
14724
+ return true;
14725
+ }
14726
+ /**
14727
+ * Whether a packet with these wire numbers predates every number the stream
14728
+ * has kept for at least one full FEC horizon (BLO-36599).
14729
+ *
14730
+ * Within one publisher epoch this cannot happen to a usable packet: it
14731
+ * would have been sent before a packet that arrived a whole horizon ago, so
14732
+ * no FEC block could still recover it and no reorder window could still place
14733
+ * it. A publisher that restarts resets packet_sequence_number and SS_ID,
14734
+ * and its first packets land exactly here. The evidence is in-band: two
14735
+ * wire counters compared against numbers the stream actually received, with
14736
+ * the horizon derived from the catalog. No timer is armed and no count
14737
+ * threshold is guessed.
14738
+ *
14739
+ * Limits, by construction: a stream without an FEC horizon (count-bounded
14740
+ * ledgers, or none) reports nothing, and so does a stream younger than two
14741
+ * timed generations; a restart whose new counters land inside the retained
14742
+ * range is not evidence, and its old numbers age out of the ledgers within
14743
+ * one horizon.
14744
+ */
14745
+ predatesHorizon(packetSequenceNumber, ssId) {
14746
+ if (this.#retentionMs === null) return false;
14747
+ const seqFloor = this.sourceSeqs.horizonFloor;
14748
+ if (seqFloor !== void 0 && serial32Precedes(packetSequenceNumber, seqFloor) && !this.sourceSeqs.has(packetSequenceNumber)) {
14749
+ return true;
14750
+ }
14751
+ if (ssId === void 0) return false;
14752
+ const ssIdFloor = this.parsedSymbols.horizonFloor;
14753
+ return ssIdFloor !== void 0 && serial32Precedes(ssId, ssIdFloor) && !this.parsedSymbols.has(ssId);
14754
+ }
14755
+ /** Whether the stream keeps ledgers, for its FEC horizon or by count. */
14756
+ get retaining() {
14757
+ return this.#retentionMs !== null || this.#countBounded;
14758
+ }
14759
+ /** Whether the ledgers are bounded by count because no FEC horizon is derivable. */
14760
+ get countBounded() {
14761
+ return this.#countBounded;
14762
+ }
14763
+ /** Current retention in ms, or null while the stream has no FEC horizon. */
14764
+ get retentionMs() {
14765
+ return this.#retentionMs;
14766
+ }
14767
+ /** Forget every number (a track reset); the next packet re-derives the horizon. */
14768
+ clear() {
14769
+ this.#forget();
14770
+ this.#lastSbn = void 0;
14771
+ this.#horizonRead = false;
14772
+ }
14773
+ #forget() {
14774
+ this.sourceSeqs.clear();
14775
+ this.routedSeqs.clear();
14776
+ this.parsedSymbols.clear();
14777
+ this.#retentionMs = null;
14778
+ this.#countBounded = false;
14779
+ }
14780
+ #rotateIfDue(nowMs) {
14781
+ if (this.#retentionMs === null || nowMs - this.#generationStartMs < this.#retentionMs) return;
14782
+ this.sourceSeqs.rotate();
14783
+ this.routedSeqs.rotate();
14784
+ this.parsedSymbols.rotate();
14785
+ this.#generationStartMs = nowMs;
14786
+ }
14787
+ };
14788
+
13457
14789
  // src/mmtp-router.ts
13458
14790
  var KEYFRAME_LOST_TIMEOUT_SLACK = 1.5;
13459
14791
  function isRouterDebugEnabled() {
@@ -13507,19 +14839,31 @@ function ingressHasPacketId(ingress, packetId) {
13507
14839
  if (packetId === MMTP_SIGNALING_PACKET_ID) return false;
13508
14840
  return ingress === void 0 || ingressEntry(ingress, packetId) !== void 0;
13509
14841
  }
13510
- var PACKET_LEDGER_HIGH_WATER = 4e3;
13511
- var PACKET_LEDGER_RETAINED = 2e3;
13512
- function rememberInLedger(ledger, value) {
13513
- ledger.add(value);
13514
- if (ledger.size <= PACKET_LEDGER_HIGH_WATER) return;
13515
- let excess = ledger.size - PACKET_LEDGER_RETAINED;
13516
- for (const oldest of ledger) {
13517
- if (excess-- <= 0) break;
13518
- ledger.delete(oldest);
13519
- }
13520
- }
14842
+ var NO_FEC_MANAGER_HORIZON = Object.freeze({
14843
+ kind: "none",
14844
+ reason: "no-fec-manager"
14845
+ });
14846
+ var NO_FEC_GEOMETRY_HORIZON = Object.freeze({
14847
+ kind: "none",
14848
+ reason: "no-fec-geometry"
14849
+ });
14850
+ var NO_BLOCK_SPAN_HORIZON = Object.freeze({
14851
+ kind: "none",
14852
+ reason: "no-block-span"
14853
+ });
13521
14854
  var DIRECT_RECOVERED_VIDEO_QUEUE_LIMIT = 512;
13522
14855
  var DIRECT_RECOVERED_AUDIO_QUEUE_LIMIT = 512;
14856
+ function sourceSymbolEvidence(packet, header, rapFlag, packetSequenceNumber) {
14857
+ const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
14858
+ return {
14859
+ rap: rapFlag,
14860
+ packetSequenceNumber,
14861
+ ...identity === null ? {} : { mpu: identity.mpuSequenceNumber },
14862
+ ...identity?.sampleNumber !== void 0 && identity.sampleNumber >= 1 ? { idx: identity.sampleNumber - 1 } : {},
14863
+ ...identity?.movieFragmentSequenceNumber !== void 0 ? { movieFragment: identity.movieFragmentSequenceNumber } : {},
14864
+ ...identity?.offset !== void 0 ? { offset: identity.offset } : {}
14865
+ };
14866
+ }
13523
14867
  var MmtpRouter = class {
13524
14868
  #parser;
13525
14869
  // Source AND FEC-recovered MFU fragments share ONE reassembler — the parser's
@@ -13587,12 +14931,18 @@ var MmtpRouter = class {
13587
14931
  #trackInitCallbacks = /* @__PURE__ */ new Map();
13588
14932
  // Track whether init has been delivered per physical stream — prevent duplicates
13589
14933
  #trackInitDelivered = /* @__PURE__ */ new Set();
13590
- // FEC block lifecycle — backend decides failed handling: WebCodecs=freeze, MSE=green fill
14934
+ // FEC block lifecycle. A failed block is NOT a decoder instruction: the
14935
+ // stall/conceal decision rides on the first frame released after the gap.
13591
14936
  #onBlockStarted = null;
13592
- /** Subscriber for unrecoverable FEC blocks. Mirrors #onBlockStarted so
13593
- * players can drive decoder recovery when a block times out; the internal
13594
- * MSE/delta-role handling below stays independent of this subscriber. */
14937
+ /** Diagnostic subscriber for unrecoverable FEC blocks, with their class. */
13595
14938
  #onBlockFailed = null;
14939
+ /** Typed observer of every gap decision the release gate makes. */
14940
+ #onFrameGap;
14941
+ // Pokes requested while a packet is being processed are deferred to its
14942
+ // end: a synchronous recovery completes its block BEFORE routing the
14943
+ // recovered frames, and releasing a held gap in between would strand them.
14944
+ #fecPokeDepth = 0;
14945
+ #pendingFecPokes = /* @__PURE__ */ new Map();
13596
14946
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
13597
14947
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
13598
14948
  #packetIdRoles = /* @__PURE__ */ new Map();
@@ -13615,10 +14965,19 @@ var MmtpRouter = class {
13615
14965
  #lastKeyframeGroupId = 0;
13616
14966
  /** Callback fired when no complete keyframe is emitted within keyframeLostTimeoutMs. Argument: next expected groupId. */
13617
14967
  #onKeyframeLost = null;
14968
+ /**
14969
+ * Owner-held state to reset when a multicast stream's publisher restarts
14970
+ * (BLO-36599); see #processMMTP. The router has already reset its own state
14971
+ * for the stream when this runs.
14972
+ */
14973
+ #onPublisherRestart;
14974
+ #publisherRestarts = 0;
13618
14975
  #disposed = false;
13619
14976
  constructor(config) {
14977
+ this.#onPublisherRestart = config?.onPublisherRestart ?? null;
13620
14978
  this.#keyframeLostTimeoutMs = config?.keyframeLostTimeoutMs ?? null;
13621
14979
  this.#fecManager = config?.fecManager ?? null;
14980
+ this.#onFrameGap = config?.onFrameGap ?? null;
13622
14981
  this.#defaultFecMapper = config?.fecMapper ?? null;
13623
14982
  this.#manifestVerifier = config?.manifestVerifier ?? null;
13624
14983
  this.#ownsManifestVerifier = config?.manifestVerifierOwnership !== "caller";
@@ -13628,7 +14987,8 @@ var MmtpRouter = class {
13628
14987
  mfuTimeoutMs: config?.mfuTimeoutMs,
13629
14988
  reassemblyPolicy: config?.reassemblyPolicy,
13630
14989
  reassembler: config?.reassembler,
13631
- maxBufferedMfus: config?.maxBufferedMfus
14990
+ maxBufferedMfus: config?.maxBufferedMfus,
14991
+ ...this.#fecManager ? { fecReleaseGate: this.#createFecReleaseGate() } : {}
13632
14992
  });
13633
14993
  this.#parser.onInit((data, packetId, catalogTrackName) => {
13634
14994
  this.#diagFor(packetId, catalogTrackName).initSegments++;
@@ -13658,13 +15018,31 @@ var MmtpRouter = class {
13658
15018
  if (meta.deliveryProvenance !== void 0)
13659
15019
  frameMeta.deliveryProvenance = meta.deliveryProvenance;
13660
15020
  if (meta.recovered) frameMeta.recovered = true;
15021
+ if (meta.gapBefore) frameMeta.gapBefore = meta.gapBefore;
13661
15022
  const sourceDiscontinuity = this.#opensFecSync(
13662
15023
  packetId,
13663
15024
  frameMeta.keyframe,
13664
15025
  frameMeta.catalogTrackName
13665
15026
  );
13666
15027
  const assembler = this.#mseAssemblerFor(packetId, frameMeta.catalogTrackName);
13667
- if (assembler) {
15028
+ if (assembler && frameMeta.recovered) {
15029
+ assembler.addRecoveredBlock(meta.fecSbn ?? -1, [{
15030
+ data,
15031
+ timestamp: frameMeta.timestamp,
15032
+ keyframe: frameMeta.keyframe,
15033
+ ...frameMeta.mmtpTimestamp === void 0 ? {} : { mmtpTimestamp: frameMeta.mmtpTimestamp },
15034
+ ...frameMeta.authoredTiming === void 0 ? {} : { authoredTiming: frameMeta.authoredTiming },
15035
+ ...frameMeta.packetSequenceNumber === void 0 ? {} : { packetSequenceNumber: frameMeta.packetSequenceNumber },
15036
+ ...frameMeta.packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers: frameMeta.packetSequenceNumbers },
15037
+ ...frameMeta.repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers: frameMeta.repairedPacketSequenceNumbers },
15038
+ ...frameMeta.mpuSequenceNumber === void 0 ? {} : { mpuSequenceNumber: frameMeta.mpuSequenceNumber },
15039
+ ...frameMeta.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: frameMeta.movieFragmentSequenceNumber },
15040
+ ...frameMeta.sampleNumber === void 0 ? {} : { sampleNumber: frameMeta.sampleNumber },
15041
+ ...frameMeta.catalogTrackName === void 0 ? {} : { catalogTrackName: frameMeta.catalogTrackName },
15042
+ ...frameMeta.deliveryProvenance === void 0 ? {} : { deliveryProvenance: frameMeta.deliveryProvenance },
15043
+ ...frameMeta.gapBefore === void 0 ? {} : { gapBefore: frameMeta.gapBefore }
15044
+ }]);
15045
+ } else if (assembler) {
13668
15046
  const fecInfo = this.#currentFecInfo;
13669
15047
  if (fecInfo && !fecInfo.oversized) {
13670
15048
  assembler.addFrame(
@@ -13682,7 +15060,8 @@ var MmtpRouter = class {
13682
15060
  frameMeta.deliveryProvenance,
13683
15061
  frameMeta.mmtpTimestamp,
13684
15062
  frameMeta.movieFragmentSequenceNumber,
13685
- frameMeta.sampleNumber
15063
+ frameMeta.sampleNumber,
15064
+ frameMeta.gapBefore
13686
15065
  );
13687
15066
  } else {
13688
15067
  assembler.addBypassFrame(
@@ -13698,7 +15077,8 @@ var MmtpRouter = class {
13698
15077
  frameMeta.deliveryProvenance,
13699
15078
  frameMeta.mmtpTimestamp,
13700
15079
  frameMeta.movieFragmentSequenceNumber,
13701
- frameMeta.sampleNumber
15080
+ frameMeta.sampleNumber,
15081
+ frameMeta.gapBefore
13702
15082
  );
13703
15083
  }
13704
15084
  }
@@ -13730,19 +15110,26 @@ var MmtpRouter = class {
13730
15110
  this.#fecManager.onBlockStarted = (sbn, packetId, _catalogTrackName) => {
13731
15111
  this.#onBlockStarted?.(sbn, packetId);
13732
15112
  };
15113
+ this.#fecManager.onBlockResolved = (_sbn, packetId, catalogTrackName) => {
15114
+ this.#requestFecPoke(packetId, catalogTrackName);
15115
+ };
15116
+ this.#fecManager.onSourceDiscontinuity = (packetId, catalogTrackName) => {
15117
+ this.#parser.markFecDiscontinuity(packetId, catalogTrackName);
15118
+ this.#requestFecPoke(packetId, catalogTrackName);
15119
+ };
13733
15120
  this.#fecManager.onBlockComplete = (sbn, packetId, catalogTrackName) => {
13734
15121
  this.#mseAssemblerFor(packetId, catalogTrackName)?.completeBlock(sbn);
13735
15122
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
13736
15123
  this.#onDeltaBlockCompleteCb?.(packetId, false);
13737
15124
  }
13738
15125
  };
13739
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName) => {
15126
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
13740
15127
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
13741
15128
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
13742
15129
  this.#onDeltaBlockCompleteCb?.(packetId, true);
13743
15130
  }
13744
- config?.onBlockFailed?.(sbn, packetId, catalogTrackName);
13745
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName);
15131
+ config?.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
15132
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
13746
15133
  };
13747
15134
  }
13748
15135
  }
@@ -13750,6 +15137,33 @@ var MmtpRouter = class {
13750
15137
  get fecManager() {
13751
15138
  return this.#fecManager;
13752
15139
  }
15140
+ /**
15141
+ * How long this router keeps a packet ID's duplicate ledgers, derived from
15142
+ * the FEC manager's geometry for it (see duplicate-ledger.ts), or why no
15143
+ * horizon is derivable (the stream then keeps count-bounded ledgers, or none
15144
+ * without an FEC manager). A stream reads this when it moves to a new FEC
15145
+ * block, so a catalog change applies from the next block.
15146
+ */
15147
+ duplicateHorizonFor(packetId) {
15148
+ const fec = this.#fecManager;
15149
+ if (!fec) return NO_FEC_MANAGER_HORIZON;
15150
+ if (!fec.interleaveDepthMsForPacket || !fec.blockLifetimeMsForPacket) {
15151
+ return NO_FEC_GEOMETRY_HORIZON;
15152
+ }
15153
+ const blockSpanMs = fec.interleaveDepthMsForPacket(packetId);
15154
+ if (blockSpanMs === 0) return NO_BLOCK_SPAN_HORIZON;
15155
+ return {
15156
+ kind: "fec-horizon",
15157
+ retentionMs: duplicateRetentionMs({
15158
+ blockSpanMs,
15159
+ blockLifetimeMs: fec.blockLifetimeMsForPacket(packetId)
15160
+ })
15161
+ };
15162
+ }
15163
+ /** Publisher restarts detected on the multicast leg since construction. */
15164
+ get publisherRestartCount() {
15165
+ return this.#publisherRestarts;
15166
+ }
13753
15167
  get reassembler() {
13754
15168
  return this.#parser.reassembler;
13755
15169
  }
@@ -13839,6 +15253,11 @@ var MmtpRouter = class {
13839
15253
  const codec = this.#trackCodecs.get(packetId) ?? "";
13840
15254
  this.#parser.setTrack(packetId, { type: trackType, codec });
13841
15255
  }
15256
+ /** Media kind registered for a packetId, if any. */
15257
+ trackKindFor(packetId) {
15258
+ const classification = this.#classifyPacketId(packetId);
15259
+ return classification === null ? void 0 : classification ? "video" : "audio";
15260
+ }
13842
15261
  /** Register codec string for a packetId — enables codec-aware keyframe detection.
13843
15262
  * Without this, only H.264 IDR (NAL type 5) is detected as keyframe fallback.
13844
15263
  * AV1 (OBU_SEQUENCE_HEADER) and VP9 (frame_type bit) require the codec string. */
@@ -13946,8 +15365,8 @@ var MmtpRouter = class {
13946
15365
  onFecBlockStarted(cb) {
13947
15366
  this.#onBlockStarted = cb;
13948
15367
  }
13949
- /** Register callback for FEC blocks that time out unrecoverably. Players use
13950
- * this to recover a decoder that was starved by the lost block. */
15368
+ /** Register a diagnostic callback for FEC blocks that fail. A failure is
15369
+ * not a decoder instruction: act on `RoutedFrameMeta.gapBefore`. */
13951
15370
  onFecBlockFailed(cb) {
13952
15371
  this.#onBlockFailed = cb;
13953
15372
  }
@@ -14051,7 +15470,9 @@ var MmtpRouter = class {
14051
15470
  */
14052
15471
  feedPacket(packet, source, manifestIdentity, ingress) {
14053
15472
  if (this.#disposed) return;
14054
- this.#processMMTP(packet, source, manifestIdentity, false, ingress);
15473
+ this.#withDeferredFecPokes(() => {
15474
+ this.#processMMTP(packet, source, manifestIdentity, false, ingress);
15475
+ });
14055
15476
  }
14056
15477
  /**
14057
15478
  * Feed a reliable MoQ duplicate of a source packet that the multicast leg
@@ -14084,7 +15505,9 @@ var MmtpRouter = class {
14084
15505
  */
14085
15506
  feedOverlapCopy(packet, ingress) {
14086
15507
  if (this.#disposed) return;
14087
- this.#processMMTP(packet, "moq", void 0, false, ingress, true);
15508
+ this.#withDeferredFecPokes(() => {
15509
+ this.#processMMTP(packet, "moq", void 0, false, ingress, true);
15510
+ });
14088
15511
  }
14089
15512
  /**
14090
15513
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
@@ -14092,6 +15515,11 @@ var MmtpRouter = class {
14092
15515
  */
14093
15516
  feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
14094
15517
  if (this.#disposed) return;
15518
+ this.#withDeferredFecPokes(() => {
15519
+ this.#feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName);
15520
+ });
15521
+ }
15522
+ #feedRepairPacket(packet, ownerPacketIdHint, catalogTrackName) {
14095
15523
  let header;
14096
15524
  try {
14097
15525
  header = parseMMTPHeader(packet);
@@ -14151,7 +15579,7 @@ var MmtpRouter = class {
14151
15579
  this.#fecManager.cancelBlockTimeout(repairSbn, ownerPacketId, catalogTrackName);
14152
15580
  }
14153
15581
  if (!alreadyCompleted) {
14154
- this.#fecManager.countRecovery(ownerPacketId);
15582
+ this.#fecManager.countRecovery(ownerPacketId, repairSbn, catalogTrackName);
14155
15583
  if (catalogTrackName === void 0) {
14156
15584
  this.#fecManager.markBlockCompleted(repairSbn, ownerPacketId);
14157
15585
  } else {
@@ -14247,10 +15675,7 @@ var MmtpRouter = class {
14247
15675
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
14248
15676
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
14249
15677
  this.#manifestRecoveryQueues.delete(streamKey);
14250
- const ledgers = this.#stream(packetId, catalogTrackName);
14251
- ledgers.sourceSeqs.clear();
14252
- ledgers.routedSeqs.clear();
14253
- ledgers.parsedSymbols.clear();
15678
+ this.#stream(packetId, catalogTrackName).duplicates.clear();
14254
15679
  const assemblersToReset = /* @__PURE__ */ new Set();
14255
15680
  const exactAssembler = this.#mseAssemblers.get(streamKey);
14256
15681
  if (exactAssembler) assemblersToReset.add(exactAssembler);
@@ -14303,12 +15728,158 @@ var MmtpRouter = class {
14303
15728
  this.#onKeyframeLost?.(expectedNext);
14304
15729
  }, this.#keyframeLostTimeoutMs);
14305
15730
  }
14306
- #noteEmittedKeyframe(packetId, keyframe) {
14307
- if (!keyframe) return;
14308
- if (!this.#videoPacketIds.has(packetId)) return;
14309
- if (this.#keyframeLostTimeoutMs === null) return;
14310
- this.#lastKeyframeGroupId++;
14311
- this.#armKeyframeLostTimer();
15731
+ #noteEmittedKeyframe(packetId, keyframe) {
15732
+ if (!keyframe) return;
15733
+ if (!this.#videoPacketIds.has(packetId)) return;
15734
+ if (this.#keyframeLostTimeoutMs === null) return;
15735
+ if (this.#isFecTrack(packetId)) return;
15736
+ this.#lastKeyframeGroupId++;
15737
+ this.#armKeyframeLostTimer();
15738
+ }
15739
+ // ── Private: FEC release gate ───────────────────────────────────
15740
+ /** A packetId is an FEC track once the FEC manager configured it. */
15741
+ #isFecTrack(packetId) {
15742
+ return this.#fecManager?.isTrackConfigured?.(packetId) === true;
15743
+ }
15744
+ #withDeferredFecPokes(work) {
15745
+ this.#fecPokeDepth++;
15746
+ try {
15747
+ work();
15748
+ } finally {
15749
+ this.#fecPokeDepth--;
15750
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
15751
+ const pokes = [...this.#pendingFecPokes.values()];
15752
+ this.#pendingFecPokes.clear();
15753
+ for (const poke of pokes) {
15754
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
15755
+ }
15756
+ }
15757
+ }
15758
+ }
15759
+ #requestFecPoke(packetId, catalogTrackName) {
15760
+ if (this.#disposed) return;
15761
+ if (this.#fecPokeDepth > 0) {
15762
+ this.#pendingFecPokes.set(this.#mediaStreamKey(packetId, catalogTrackName), {
15763
+ packetId,
15764
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
15765
+ });
15766
+ return;
15767
+ }
15768
+ this.#parser.pokeFecRelease(packetId, catalogTrackName);
15769
+ }
15770
+ /**
15771
+ * The release policy the parser applies to FEC tracks: a frame after a gap
15772
+ * is held until every block that could hold the missing frames resolved,
15773
+ * then released with the stall/conceal decision when media was lost.
15774
+ */
15775
+ #createFecReleaseGate() {
15776
+ if (this.#fecManager?.blockResolution && !this.#fecManager.terminalRetentionMsForPacket) {
15777
+ throw new Error(
15778
+ "[MmtpRouter] an FEC manager with blockResolution must provide terminalRetentionMsForPacket: it bounds how long the release gate holds a frame"
15779
+ );
15780
+ }
15781
+ return {
15782
+ gates: (packetId) => this.#isFecTrack(packetId),
15783
+ resolvedLoss: (packetId, catalogTrackName, fromSbn, toSbn, releasedSbn) => {
15784
+ const fec = this.#fecManager;
15785
+ if (!fec?.blockResolution) return [];
15786
+ const highest = fec.highestSbn?.(packetId, catalogTrackName);
15787
+ const lost = [];
15788
+ for (let sbn = fromSbn; sbn <= toSbn; sbn++) {
15789
+ const resolution = fec.blockResolution(sbn, packetId, catalogTrackName);
15790
+ if (resolution === "pending") return null;
15791
+ if (resolution === "failed") {
15792
+ lost.push(sbn);
15793
+ } else if (resolution === "untracked") {
15794
+ if (sbn === releasedSbn) continue;
15795
+ if (highest === void 0 || sbn > highest) return null;
15796
+ lost.push(sbn);
15797
+ }
15798
+ }
15799
+ return lost;
15800
+ },
15801
+ // The retention window itself: a frame is never still held when a block
15802
+ // it waits on retires. Only consulted while resolvedLoss holds a gap,
15803
+ // which needs blockResolution, so the check above guarantees the method.
15804
+ holdLimitMs: (packetId) => this.#fecManager?.terminalRetentionMsForPacket?.(packetId) ?? Infinity,
15805
+ decide: (before, after, lostBlocks, discontinuity) => {
15806
+ const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
15807
+ this.#onFrameGap?.(decision);
15808
+ return decision;
15809
+ },
15810
+ onReleased: (data, meta) => {
15811
+ if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
15812
+ const timing = meta.authoredTiming;
15813
+ if (!timing || !this.#isRapForGap(data, meta)) return;
15814
+ this.#fecManager?.noteReleasedRap?.(
15815
+ meta.packetId,
15816
+ meta.catalogTrackName,
15817
+ meta.mpuSequenceNumber,
15818
+ timing.presentationTime,
15819
+ timing.mediaTimescale
15820
+ );
15821
+ }
15822
+ };
15823
+ }
15824
+ /**
15825
+ * Codec-aware RAP check for gap decisions: the bitstream, with the MMTP R
15826
+ * bit only as the fallback for source frames. Recovered frames are
15827
+ * bitstream-only, and the MFU priority hint never counts.
15828
+ */
15829
+ #isRapForGap(data, meta) {
15830
+ const codec = this.#trackCodecs.get(meta.packetId) ?? this.#fecManager?.codecFor?.(meta.packetId) ?? "";
15831
+ const rapFlag = meta.recovered ? false : meta.rapFlag === true;
15832
+ return MmtpContainerParser.isKeyframe(data, rapFlag, codec);
15833
+ }
15834
+ #decideGap(before, after, lostBlocks, discontinuity) {
15835
+ const { packetId, catalogTrackName } = after.meta;
15836
+ const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
15837
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
15838
+ const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
15839
+ const evidence = (frame) => {
15840
+ const timing = frame.meta.authoredTiming;
15841
+ const sampleNumber = frame.meta.sampleNumber;
15842
+ return {
15843
+ rap: trackKind === "video" && this.#isRapForGap(frame.data, frame.meta),
15844
+ ...!mpuTrusted || frame.meta.mpuSequenceNumber === void 0 ? {} : { mpu: frame.meta.mpuSequenceNumber },
15845
+ ...positionsTrusted && sampleNumber !== void 0 && sampleNumber >= 1 ? { idx: sampleNumber - 1 } : {},
15846
+ ...timing === void 0 ? {} : {
15847
+ pts: timing.presentationTime,
15848
+ durationTicks: timing.durationTicks,
15849
+ timescale: timing.mediaTimescale
15850
+ }
15851
+ };
15852
+ };
15853
+ return decideGap({
15854
+ stream: { packetId, catalogTrackName: catalogTrackName ?? null },
15855
+ trackKind,
15856
+ before: evidence(before),
15857
+ after: evidence(after),
15858
+ discontinuity,
15859
+ blocks: lostBlocks,
15860
+ maxMissingUnits: this.#maxMissingUnits(before.meta, after.meta),
15861
+ epoch: this.#fecManager?.epochFor?.(packetId) ?? 0
15862
+ });
15863
+ }
15864
+ /**
15865
+ * The most media units a gap between two released frames can hold: the
15866
+ * FEC blocks from `before`'s SBN to `after`'s, times D, the media units one
15867
+ * block touches (ceil(interleaveDepthMs / unit duration), §5.1). Null when
15868
+ * either SBN, the unit duration or the catalog interleave is unknown.
15869
+ */
15870
+ #maxMissingUnits(before, after) {
15871
+ const from = before.fecSbn;
15872
+ const to = after.fecSbn;
15873
+ const timing = before.authoredTiming;
15874
+ const interleaveMs = this.#fecManager?.interleaveDepthMsForPacket?.(after.packetId);
15875
+ if (from === void 0 || to === void 0 || !timing || interleaveMs === void 0) return null;
15876
+ if (!(timing.durationTicks > 0) || !(timing.mediaTimescale > 0) || !(interleaveMs > 0)) return null;
15877
+ const numerator = BigInt(Math.ceil(interleaveMs)) * BigInt(timing.mediaTimescale);
15878
+ const denominator = BigInt(timing.durationTicks) * 1000n;
15879
+ const unitsPerBlock = (numerator + denominator - 1n) / denominator;
15880
+ const blocks = BigInt(Math.abs(to - from) + 1);
15881
+ const bound = unitsPerBlock * blocks;
15882
+ return bound > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(bound);
14312
15883
  }
14313
15884
  // ── Private: MMTP processing ────────────────────────────────────
14314
15885
  /** Classify a packetId from the catalog. Returns true=video, false=audio, null=unknown (drop). */
@@ -14365,7 +15936,7 @@ var MmtpRouter = class {
14365
15936
  * 1. parseHeader() → extract packetId + fecPayloadId for FEC feeding
14366
15937
  * 2. feed() → MFU extraction, reassembly, keyframe detection, emit via callbacks
14367
15938
  */
14368
- #processMMTP(packet, source, manifestIdentity, manifestAdmitted = false, ingress, overlapCopy = false) {
15939
+ #processMMTP(packet, source, manifestIdentity, manifestAdmitted = false, ingress, overlapCopy = false, releasedFromQuarantine = false) {
14369
15940
  const parsed = this.#parser.parsePacket(packet);
14370
15941
  if (!parsed) return;
14371
15942
  const info = parsed.info;
@@ -14411,9 +15982,13 @@ var MmtpRouter = class {
14411
15982
  ...info.fecPayloadId ? { ssId: info.fecPayloadId.ssId } : {}
14412
15983
  };
14413
15984
  const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
14414
- this.#manifestVerifier.admitObject(identity, authenticated, () => {
14415
- if (!this.#disposed) this.#processMMTP(packet, source, identity, true, ingress, overlapCopy);
15985
+ let quarantined = false;
15986
+ const admission = this.#manifestVerifier.admitObject(identity, authenticated, () => {
15987
+ if (!this.#disposed) {
15988
+ this.#processMMTP(packet, source, identity, true, ingress, overlapCopy, quarantined);
15989
+ }
14416
15990
  });
15991
+ quarantined = admission.action === "stall";
14417
15992
  return;
14418
15993
  }
14419
15994
  if (this.#manifestVerifier.config.mode === "enforce" && this.#manifestVerifier.config.onMissingManifest === "stall") {
@@ -14485,7 +16060,7 @@ var MmtpRouter = class {
14485
16060
  );
14486
16061
  }
14487
16062
  if (!alreadyCompleted) {
14488
- this.#fecManager.countRecovery(ownerPacketId);
16063
+ this.#fecManager.countRecovery(ownerPacketId, repairSbn, repairCatalogTrackName);
14489
16064
  if (repairCatalogTrackName === void 0) {
14490
16065
  this.#fecManager.markBlockCompleted(repairSbn, ownerPacketId);
14491
16066
  } else {
@@ -14524,12 +16099,25 @@ var MmtpRouter = class {
14524
16099
  names.add(catalogTrackName);
14525
16100
  this.#catalogTrackNamesByPacketId.set(info.packetId, names);
14526
16101
  }
14527
- if (this.#fecManager && info.fecPayloadId) {
16102
+ const duplicates = this.#stream(info.packetId, catalogTrackName).duplicates;
16103
+ const coords = this.#fecManager && info.fecPayloadId ? this.#deriveSbnEsi(info.fecPayloadId.ssId, info.packetId) : void 0;
16104
+ duplicates.advance(coords?.sbn);
16105
+ if (source === "multicast" && !overlapCopy && !releasedFromQuarantine && catalogTrackName !== void 0 && duplicates.predatesHorizon(info.sequenceNumber, info.fecPayloadId?.ssId)) {
16106
+ this.#publisherRestarts++;
16107
+ console.warn(
16108
+ `[MmtpRouter] publisher restart on pid=${info.packetId} track=${catalogTrackName}: packet_sequence_number=${info.sequenceNumber} predates the stream's FEC horizon; starting a new epoch`
16109
+ );
16110
+ this.#parser.markFecDiscontinuity(info.packetId, catalogTrackName);
16111
+ this.#parser.pokeFecRelease(info.packetId, catalogTrackName);
16112
+ this.resetTrack(info.packetId, catalogTrackName);
16113
+ this.#onPublisherRestart?.(info.packetId, catalogTrackName);
16114
+ duplicates.advance(coords?.sbn);
16115
+ }
16116
+ if (this.#fecManager && info.fecPayloadId && coords) {
14528
16117
  const fecId = info.fecPayloadId;
14529
16118
  const symbolSize = this.#symbolSizeForPacket(info.packetId);
14530
16119
  const rawSymbol = packet.subarray(0, packet.length - 4);
14531
16120
  const oversized = symbolSize > 0 && rawSymbol.length > symbolSize;
14532
- const coords = this.#deriveSbnEsi(fecId.ssId, info.packetId);
14533
16121
  let overlapBlockCompleted = false;
14534
16122
  if (overlapCopy) {
14535
16123
  overlapBlockCompleted = catalogTrackName === void 0 ? this.#fecManager.isBlockCompleted(coords.sbn, info.packetId) : this.#fecManager.isBlockCompleted(
@@ -14562,15 +16150,12 @@ var MmtpRouter = class {
14562
16150
  sourceFec = { ssId: fecId.ssId, sbn: coords.sbn, symbolData };
14563
16151
  }
14564
16152
  }
14565
- parseSourceSymbol = (overlapCopy ? !overlapBlockCompleted : sourceSymbolAccepted) && !this.#stream(info.packetId, catalogTrackName).parsedSymbols.has(fecId.ssId);
16153
+ parseSourceSymbol = (overlapCopy ? !overlapBlockCompleted : sourceSymbolAccepted) && !duplicates.parsedSymbols.has(fecId.ssId);
14566
16154
  fecInfo = { sbn: coords.sbn, esi: coords.esi, oversized };
14567
16155
  }
14568
16156
  if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
14569
16157
  if (this.#fecManager && info.fecPayloadId) {
14570
- rememberInLedger(
14571
- this.#stream(info.packetId, catalogTrackName).parsedSymbols,
14572
- info.fecPayloadId.ssId
14573
- );
16158
+ duplicates.parsedSymbols.add(info.fecPayloadId.ssId);
14574
16159
  }
14575
16160
  this.#noteSourcePacketSeq(
14576
16161
  info.packetId,
@@ -14584,7 +16169,8 @@ var MmtpRouter = class {
14584
16169
  });
14585
16170
  this.#feedViaParser(packet, info, fecInfo, {
14586
16171
  source,
14587
- catalogTrackName
16172
+ catalogTrackName,
16173
+ ...fecInfo === void 0 ? {} : { fecSbn: fecInfo.sbn }
14588
16174
  }, parsed);
14589
16175
  }
14590
16176
  if (this.#fecManager && info.fecPayloadId && sourceSymbolAccepted && sourceSymbolTrackable) {
@@ -14592,17 +16178,15 @@ var MmtpRouter = class {
14592
16178
  info.fecPayloadId.ssId,
14593
16179
  info.packetId
14594
16180
  );
14595
- if (this.#classifyPacketId(info.packetId) !== null) {
14596
- if (catalogTrackName === void 0) {
14597
- this.#fecManager.trackBlock(sbn, info.packetId, void 0, esi);
14598
- } else {
14599
- this.#fecManager.trackBlock(
14600
- sbn,
14601
- info.packetId,
14602
- catalogTrackName,
14603
- esi
14604
- );
14605
- }
16181
+ if (this.#classifyPacketId(info.packetId) !== null && this.#fecManager.isTrackConfigured?.(info.packetId) !== false) {
16182
+ this.#fecManager.trackBlock(
16183
+ sbn,
16184
+ info.packetId,
16185
+ catalogTrackName,
16186
+ esi,
16187
+ sourceSymbolEvidence(packet, parsed.header, info.rapFlag, info.sequenceNumber)
16188
+ );
16189
+ this.#requestFecPoke(info.packetId, catalogTrackName);
14606
16190
  }
14607
16191
  }
14608
16192
  if (this.#fecManager && sourceFec) {
@@ -14636,7 +16220,7 @@ var MmtpRouter = class {
14636
16220
  }
14637
16221
  }
14638
16222
  if (!alreadyCompleted) {
14639
- this.#fecManager.countRecovery(info.packetId);
16223
+ this.#fecManager.countRecovery(info.packetId, sourceFec.sbn, catalogTrackName);
14640
16224
  if (catalogTrackName === void 0) {
14641
16225
  this.#fecManager.markBlockCompleted(sourceFec.sbn, info.packetId);
14642
16226
  } else {
@@ -14677,7 +16261,8 @@ var MmtpRouter = class {
14677
16261
  recovered: parserOptions?.recovered,
14678
16262
  source: parserOptions?.source,
14679
16263
  deliveryProvenance: parserOptions?.deliveryProvenance,
14680
- catalogTrackName: parserOptions?.catalogTrackName
16264
+ catalogTrackName: parserOptions?.catalogTrackName,
16265
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
14681
16266
  };
14682
16267
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
14683
16268
  else this.#parser.feed(packet, feedOptions);
@@ -14753,21 +16338,18 @@ var MmtpRouter = class {
14753
16338
  }
14754
16339
  #noteSourcePacketSeq(packetId, packetSequenceNumber, catalogTrackName) {
14755
16340
  if (packetSequenceNumber === void 0 || !Number.isFinite(packetSequenceNumber)) return;
14756
- rememberInLedger(
14757
- this.#stream(packetId, catalogTrackName).sourceSeqs,
14758
- packetSequenceNumber
14759
- );
16341
+ this.#stream(packetId, catalogTrackName).duplicates.sourceSeqs.add(packetSequenceNumber);
14760
16342
  }
14761
16343
  #sourceSeqReceived(packetId, packetSequenceNumber, catalogTrackName) {
14762
- return this.#stream(packetId, catalogTrackName).sourceSeqs.has(packetSequenceNumber);
16344
+ return this.#stream(packetId, catalogTrackName).duplicates.sourceSeqs.has(packetSequenceNumber);
14763
16345
  }
14764
16346
  #routeTrackPacket(packet, packetId, packetSequenceNumber, meta) {
14765
16347
  if (!Number.isFinite(packetSequenceNumber)) return;
14766
16348
  const callback = this.#trackPacketCallbacks.get(packetId);
14767
16349
  if (!callback) return;
14768
- const routedSeqs = this.#stream(packetId, meta.catalogTrackName).routedSeqs;
16350
+ const routedSeqs = this.#stream(packetId, meta.catalogTrackName).duplicates.routedSeqs;
14769
16351
  if (routedSeqs.has(packetSequenceNumber)) return;
14770
- rememberInLedger(routedSeqs, packetSequenceNumber);
16352
+ routedSeqs.add(packetSequenceNumber);
14771
16353
  callback(packet, {
14772
16354
  packetId,
14773
16355
  packetSequenceNumber,
@@ -14802,9 +16384,7 @@ var MmtpRouter = class {
14802
16384
  if (stream === void 0) {
14803
16385
  stream = {
14804
16386
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
14805
- sourceSeqs: /* @__PURE__ */ new Set(),
14806
- routedSeqs: /* @__PURE__ */ new Set(),
14807
- parsedSymbols: /* @__PURE__ */ new Set()
16387
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
14808
16388
  };
14809
16389
  byName.set(catalogTrackName, stream);
14810
16390
  }
@@ -15134,6 +16714,7 @@ var MmtpRouter = class {
15134
16714
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName) {
15135
16715
  if (ownerPacketId == null) return;
15136
16716
  if (this.#classifyPacketId(ownerPacketId) === null) return;
16717
+ this.#stream(ownerPacketId, catalogTrackName).duplicates.advance(blockId);
15137
16718
  const deliveryProvenance = this.#fecManager?.blockDeliveryProvenance?.(
15138
16719
  blockId,
15139
16720
  ownerPacketId,
@@ -15160,6 +16741,7 @@ var MmtpRouter = class {
15160
16741
  }
15161
16742
  );
15162
16743
  }
16744
+ const gated = this.#isFecTrack(ownerPacketId);
15163
16745
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
15164
16746
  if (assembler) {
15165
16747
  const isVideoTrack = this.#classifyPacketId(ownerPacketId) === true;
@@ -15179,6 +16761,37 @@ var MmtpRouter = class {
15179
16761
  sym.fragment.data,
15180
16762
  isMfuKeyframeMetadata2(sym.fragment.rapFlag, sym.fragment.priority)
15181
16763
  ) : sym.fragment.rapFlag;
16764
+ if (gated) {
16765
+ const gatedTiming = this.#resolveRecoveredTiming(
16766
+ ownerPacketId,
16767
+ sym.fragment.mpuSequenceNumber,
16768
+ sym.fragment.movieFragmentSequenceNumber,
16769
+ sym.fragment.sampleNumber,
16770
+ sym.fragment.timestamp,
16771
+ catalogTrackName
16772
+ );
16773
+ if (!gatedTiming) continue;
16774
+ this.#parser.routeFrame(sym.fragment.data, {
16775
+ timestamp: gatedTiming.timestamp,
16776
+ mmtpTimestamp: gatedTiming.mmtpTimestamp,
16777
+ ...gatedTiming.authoredTiming === void 0 ? {} : { authoredTiming: gatedTiming.authoredTiming },
16778
+ keyframe: isVideoTrack ? keyframe : true,
16779
+ packetId: ownerPacketId,
16780
+ trackType: isVideoTrack ? "video" : "audio",
16781
+ packetSequenceNumber: sym.packetSequenceNumber,
16782
+ packetSequenceNumbers: [sym.packetSequenceNumber],
16783
+ repairedPacketSequenceNumbers: [sym.packetSequenceNumber],
16784
+ mpuSequenceNumber: sym.fragment.mpuSequenceNumber,
16785
+ ...sym.fragment.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber },
16786
+ ...sym.fragment.sampleNumber === void 0 ? {} : { sampleNumber: sym.fragment.sampleNumber },
16787
+ rapFlag: sym.fragment.rapFlag,
16788
+ recovered: true,
16789
+ deliveryProvenance,
16790
+ fecSbn: blockId,
16791
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
16792
+ });
16793
+ continue;
16794
+ }
15182
16795
  const sourceDiscontinuity = this.#opensFecSync(
15183
16796
  ownerPacketId,
15184
16797
  keyframe,
@@ -15260,6 +16873,37 @@ var MmtpRouter = class {
15260
16873
  isMfuKeyframeMetadata2(assembled.rapFlag, assembled.priority)
15261
16874
  ) : assembled.rapFlag;
15262
16875
  const recoveredCatalogTrackName = assembled.catalogTrackName ?? catalogTrackName;
16876
+ if (gated) {
16877
+ const gatedTiming = this.#resolveRecoveredTiming(
16878
+ ownerPacketId,
16879
+ assembled.mpuSequenceNumber,
16880
+ assembled.movieFragmentSequenceNumber,
16881
+ assembled.sampleNumber,
16882
+ assembled.timestamp,
16883
+ recoveredCatalogTrackName
16884
+ );
16885
+ if (!gatedTiming) continue;
16886
+ this.#parser.routeFrame(assembled.data, {
16887
+ timestamp: gatedTiming.timestamp,
16888
+ mmtpTimestamp: gatedTiming.mmtpTimestamp,
16889
+ ...gatedTiming.authoredTiming === void 0 ? {} : { authoredTiming: gatedTiming.authoredTiming },
16890
+ keyframe: isVideoTrack ? keyframe : true,
16891
+ packetId: ownerPacketId,
16892
+ trackType: isVideoTrack ? "video" : "audio",
16893
+ packetSequenceNumber: sym.packetSequenceNumber,
16894
+ ...assembled.packetSequenceNumbers === void 0 ? {} : { packetSequenceNumbers: assembled.packetSequenceNumbers },
16895
+ ...assembled.repairedPacketSequenceNumbers === void 0 ? {} : { repairedPacketSequenceNumbers: assembled.repairedPacketSequenceNumbers },
16896
+ mpuSequenceNumber: assembled.mpuSequenceNumber,
16897
+ ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
16898
+ ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
16899
+ rapFlag: assembled.rapFlag,
16900
+ recovered: true,
16901
+ ...assembled.deliveryProvenance === void 0 ? {} : { deliveryProvenance: assembled.deliveryProvenance },
16902
+ fecSbn: blockId,
16903
+ ...recoveredCatalogTrackName === void 0 ? {} : { catalogTrackName: recoveredCatalogTrackName }
16904
+ });
16905
+ continue;
16906
+ }
15263
16907
  const sourceDiscontinuity = this.#opensFecSync(
15264
16908
  ownerPacketId,
15265
16909
  keyframe,
@@ -15388,8 +17032,10 @@ var MmtpRouter = class {
15388
17032
  mpuSequenceNumber: sym.fragment.mpuSequenceNumber,
15389
17033
  ...sym.fragment.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber },
15390
17034
  ...sym.fragment.sampleNumber === void 0 ? {} : { sampleNumber: sym.fragment.sampleNumber },
17035
+ rapFlag: sym.fragment.rapFlag,
15391
17036
  recovered: true,
15392
17037
  deliveryProvenance,
17038
+ fecSbn: blockId,
15393
17039
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
15394
17040
  });
15395
17041
  } else {
@@ -15465,8 +17111,10 @@ var MmtpRouter = class {
15465
17111
  mpuSequenceNumber: assembled.mpuSequenceNumber,
15466
17112
  ...assembled.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: assembled.movieFragmentSequenceNumber },
15467
17113
  ...assembled.sampleNumber === void 0 ? {} : { sampleNumber: assembled.sampleNumber },
17114
+ rapFlag: assembled.rapFlag,
15468
17115
  recovered: true,
15469
17116
  deliveryProvenance,
17117
+ fecSbn: blockId,
15470
17118
  ...assembled.catalogTrackName === void 0 ? {} : { catalogTrackName: assembled.catalogTrackName }
15471
17119
  });
15472
17120
  }
@@ -15485,6 +17133,27 @@ var MmtpRouter = class {
15485
17133
  catalogTrackName
15486
17134
  );
15487
17135
  if (recoveredTiming === null) continue;
17136
+ if (gated) {
17137
+ this.#parser.routeFrame(sym.fragment.data, {
17138
+ timestamp: recoveredTiming.timestamp,
17139
+ mmtpTimestamp: recoveredTiming.mmtpTimestamp,
17140
+ ...recoveredTiming.authoredTiming === void 0 ? {} : { authoredTiming: recoveredTiming.authoredTiming },
17141
+ keyframe: true,
17142
+ packetId: ownerPacketId,
17143
+ trackType: "audio",
17144
+ packetSequenceNumber: sym.packetSequenceNumber,
17145
+ packetSequenceNumbers: [sym.packetSequenceNumber],
17146
+ repairedPacketSequenceNumbers: [sym.packetSequenceNumber],
17147
+ mpuSequenceNumber: sym.fragment.mpuSequenceNumber,
17148
+ ...sym.fragment.movieFragmentSequenceNumber === void 0 ? {} : { movieFragmentSequenceNumber: sym.fragment.movieFragmentSequenceNumber },
17149
+ ...sym.fragment.sampleNumber === void 0 ? {} : { sampleNumber: sym.fragment.sampleNumber },
17150
+ recovered: true,
17151
+ deliveryProvenance,
17152
+ fecSbn: blockId,
17153
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
17154
+ });
17155
+ continue;
17156
+ }
15488
17157
  const meta = {
15489
17158
  timestamp: recoveredTiming.timestamp,
15490
17159
  mmtpTimestamp: recoveredTiming.mmtpTimestamp,
@@ -16418,6 +18087,11 @@ function isPositivePort(port) {
16418
18087
  return Number.isInteger(port) && port > 0 && port <= 65535;
16419
18088
  }
16420
18089
 
18090
+ // node_modules/@blockcast/mmt-transport/dist/packet-batch.js
18091
+ function subscriptionDeliversPacketBatches(subscription) {
18092
+ return subscription.eventTypes?.includes("packets") === true;
18093
+ }
18094
+
16421
18095
  // node_modules/@blockcast/mmt-transport/dist/multicast-subscription-pool.js
16422
18096
  var MulticastSubscriptionPool = class {
16423
18097
  #entries = /* @__PURE__ */ new Map();
@@ -16500,8 +18174,18 @@ var MulticastSubscriptionPool = class {
16500
18174
  }));
16501
18175
  const consumers = /* @__PURE__ */ new Map();
16502
18176
  let entry;
16503
- const bytesListener = (event) => {
16504
- this.#dispatch(consumers, (consumer) => consumer.onBytes(event.detail));
18177
+ const packetListener = subscriptionDeliversPacketBatches(subscription) ? {
18178
+ type: "packets",
18179
+ listener: (event) => {
18180
+ for (const data of event.detail) {
18181
+ this.#dispatch(consumers, (consumer) => consumer.onBytes(data));
18182
+ }
18183
+ }
18184
+ } : {
18185
+ type: "bytes",
18186
+ listener: (event) => {
18187
+ this.#dispatch(consumers, (consumer) => consumer.onBytes(event.detail));
18188
+ }
16505
18189
  };
16506
18190
  const stateListener = (event) => {
16507
18191
  this.#dispatch(consumers, (consumer) => consumer.onState?.(event.detail));
@@ -16514,8 +18198,12 @@ var MulticastSubscriptionPool = class {
16514
18198
  const error = event.detail instanceof Error ? event.detail : new Error(String(event.detail));
16515
18199
  this.#dispatch(consumers, (consumer) => consumer.onError?.(error));
16516
18200
  };
16517
- entry = { subscription, consumers, bytesListener, stateListener, errorListener, closed: false };
16518
- subscription.addEventListener("bytes", bytesListener);
18201
+ entry = { subscription, consumers, packetListener, stateListener, errorListener, closed: false };
18202
+ if (packetListener.type === "packets") {
18203
+ subscription.addEventListener("packets", packetListener.listener);
18204
+ } else {
18205
+ subscription.addEventListener("bytes", packetListener.listener);
18206
+ }
16519
18207
  subscription.addEventListener("state", stateListener);
16520
18208
  subscription.addEventListener("error", errorListener);
16521
18209
  return entry;
@@ -16530,7 +18218,12 @@ var MulticastSubscriptionPool = class {
16530
18218
  return id;
16531
18219
  }
16532
18220
  #detach(entry) {
16533
- entry.subscription.removeEventListener("bytes", entry.bytesListener);
18221
+ const { packetListener } = entry;
18222
+ if (packetListener.type === "packets") {
18223
+ entry.subscription.removeEventListener("packets", packetListener.listener);
18224
+ } else {
18225
+ entry.subscription.removeEventListener("bytes", packetListener.listener);
18226
+ }
16534
18227
  entry.subscription.removeEventListener("state", entry.stateListener);
16535
18228
  entry.subscription.removeEventListener("error", entry.errorListener);
16536
18229
  }
@@ -16959,9 +18652,20 @@ function moqtPublisherPriority(value) {
16959
18652
  }
16960
18653
  var MOQT_SUBSCRIBER_PRIORITY = Object.freeze({
16961
18654
  catalog: moqtSubscriberPriority(0),
18655
+ /**
18656
+ * @deprecated A repair FETCH's SUBSCRIBER_PRIORITY is derived per request
18657
+ * from the catalog source and repair priorities (draft-ramadan-moq-fec
18658
+ * §11.4.5), not a player constant. Use the `subscriberPriority` that
18659
+ * `@blockcast/mmt-container`'s `wireRepairFetch` puts on each
18660
+ * `RepairFetchRequest` (`repairFetchSubscriberPriority`).
18661
+ */
16962
18662
  deadlineRepair: moqtSubscriberPriority(0),
16963
18663
  audio: moqtSubscriberPriority(1),
16964
18664
  video: moqtSubscriberPriority(2),
18665
+ /**
18666
+ * @deprecated See `deadlineRepair`: use the request's catalog-derived
18667
+ * `RepairFetchRequest.subscriberPriority` (draft-ramadan-moq-fec §11.4.5).
18668
+ */
16965
18669
  backgroundRepair: moqtSubscriberPriority(3)
16966
18670
  });
16967
18671
  var MOQT_PUBLISHER_PRIORITY = Object.freeze({
@@ -17160,6 +18864,7 @@ function hasMulticastGateway() {
17160
18864
  }
17161
18865
  function normalizeBytesEventDetail(detail) {
17162
18866
  const value = detail && typeof detail === "object" && "data" in detail ? detail.data : detail;
18867
+ if (value instanceof Uint8Array) return value;
17163
18868
  if (value instanceof ArrayBuffer) return new Uint8Array(value);
17164
18869
  if (ArrayBuffer.isView(value)) {
17165
18870
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
@@ -17169,7 +18874,7 @@ function normalizeBytesEventDetail(detail) {
17169
18874
  var MulticastTransport = class _MulticastTransport {
17170
18875
  #onPacket;
17171
18876
  #subscription = null;
17172
- #bytesListener = null;
18877
+ #packetListener = null;
17173
18878
  #resolvedTransport;
17174
18879
  #videoConfirmed = false;
17175
18880
  #audioConfirmed = false;
@@ -17233,24 +18938,29 @@ var MulticastTransport = class _MulticastTransport {
17233
18938
  }
17234
18939
  throw new Error("window.multicast subscription does not support bytes events");
17235
18940
  }
17236
- const onBytes = (event) => {
17237
- if (this.#disposed || generation !== this.#joinGeneration) return;
17238
- const packet = normalizeBytesEventDetail(event.detail);
17239
- if (!packet) {
17240
- this.#stats.packetsDroppedUnparseable++;
17241
- return;
18941
+ const live = () => !this.#disposed && generation === this.#joinGeneration;
18942
+ const packetListener = subscriptionDeliversPacketBatches(subscription) ? {
18943
+ type: "packets",
18944
+ listener: (event) => {
18945
+ if (!live()) return;
18946
+ this.#deliverBatch(event.detail, context, live);
18947
+ }
18948
+ } : {
18949
+ type: "bytes",
18950
+ listener: (event) => {
18951
+ if (!live()) return;
18952
+ if (this.#deliver(event.detail, context)) this.#resetWatchdog();
17242
18953
  }
17243
- if (!this.#acceptPacket(packet)) return;
17244
- this.#stats.packetsReceived++;
17245
- this.#stats.bytesReceived += packet.byteLength;
17246
- this.#onPacket(packet, context);
17247
- this.#resetWatchdog();
17248
18954
  };
17249
18955
  this.#subscription = subscription;
17250
- this.#bytesListener = onBytes;
18956
+ this.#packetListener = packetListener;
17251
18957
  this.#packetIds = packetIds;
17252
18958
  this.#resolvedTransport = subscribeConfig.origin === "amt" ? "amt" : "native";
17253
- subscription.addEventListener("bytes", onBytes);
18959
+ if (packetListener.type === "packets") {
18960
+ subscription.addEventListener("packets", packetListener.listener);
18961
+ } else {
18962
+ subscription.addEventListener("bytes", packetListener.listener);
18963
+ }
17254
18964
  this.#resetWatchdog();
17255
18965
  console.log(
17256
18966
  `[MulticastTransport] Joined ${config.groupAddress}:${config.port}`
@@ -17263,6 +18973,59 @@ var MulticastTransport = class _MulticastTransport {
17263
18973
  return false;
17264
18974
  }
17265
18975
  }
18976
+ /**
18977
+ * One packet from the subscription: filter, count, and hand it to the
18978
+ * callback. Returns whether it was delivered; the caller notes liveness.
18979
+ */
18980
+ #deliver(detail, context) {
18981
+ const packet = normalizeBytesEventDetail(detail);
18982
+ if (!packet) {
18983
+ this.#stats.packetsDroppedUnparseable++;
18984
+ return false;
18985
+ }
18986
+ if (!this.#acceptPacket(packet)) return false;
18987
+ this.#stats.packetsReceived++;
18988
+ this.#stats.bytesReceived += packet.byteLength;
18989
+ this.#onPacket(packet, context);
18990
+ return true;
18991
+ }
18992
+ /**
18993
+ * One `packets` event. Each packet is delivered as a `bytes` event would
18994
+ * have delivered it, including isolation: a packet whose callback throws
18995
+ * does not cost the rest of its batch, as it would not have cost the next
18996
+ * `bytes` event. The first failure is rethrown once the batch is done, so
18997
+ * it reaches the event-listener error reporting a `bytes` listener's throw
18998
+ * reached; any further one is rethrown from its own microtask, which the
18999
+ * host reports the same way, so no failure is swallowed. A callback that
19000
+ * disposes the transport or starts another join ends the batch there, as
19001
+ * the per-packet guard would have ignored the remaining events.
19002
+ */
19003
+ #deliverBatch(batch, context, live) {
19004
+ if (!Array.isArray(batch)) {
19005
+ throw new TypeError("[MulticastTransport] packets event detail must be an array of packets");
19006
+ }
19007
+ let delivered = false;
19008
+ let failures = null;
19009
+ for (let i = 0; i < batch.length; i++) {
19010
+ try {
19011
+ if (this.#deliver(batch[i], context)) delivered = true;
19012
+ } catch (error) {
19013
+ if (failures === null) failures = [];
19014
+ failures.push(error);
19015
+ }
19016
+ if (!live()) break;
19017
+ }
19018
+ if (delivered && live()) this.#resetWatchdog();
19019
+ if (failures !== null) {
19020
+ for (let i = 1; i < failures.length; i++) {
19021
+ const failure = failures[i];
19022
+ queueMicrotask(() => {
19023
+ throw failure;
19024
+ });
19025
+ }
19026
+ throw failures[0];
19027
+ }
19028
+ }
17266
19029
  /** Feed a raw packet from an external source (e.g., AMT tunnel or ASM subscription). */
17267
19030
  feedPacket(data, context) {
17268
19031
  if (this.#disposed) return;
@@ -17323,13 +19086,16 @@ var MulticastTransport = class _MulticastTransport {
17323
19086
  if (this.#watchdog) clearTimeout(this.#watchdog);
17324
19087
  this.#watchdog = null;
17325
19088
  if (this.#subscription) {
17326
- if (this.#bytesListener) {
17327
- this.#subscription.removeEventListener("bytes", this.#bytesListener);
19089
+ const packetListener = this.#packetListener;
19090
+ if (packetListener?.type === "packets") {
19091
+ this.#subscription.removeEventListener("packets", packetListener.listener);
19092
+ } else if (packetListener) {
19093
+ this.#subscription.removeEventListener("bytes", packetListener.listener);
17328
19094
  }
17329
19095
  void this.#subscription.unsubscribe();
17330
19096
  }
17331
19097
  this.#subscription = null;
17332
- this.#bytesListener = null;
19098
+ this.#packetListener = null;
17333
19099
  this.#resolvedTransport = void 0;
17334
19100
  this.#packetIds = null;
17335
19101
  }
@@ -17398,6 +19164,35 @@ var MulticastTransport = class _MulticastTransport {
17398
19164
  };
17399
19165
 
17400
19166
  // src/multicast-manager.ts
19167
+ function newBlockPolicyStats(packetId, catalogTrackName, epoch) {
19168
+ return {
19169
+ packetId,
19170
+ catalogTrackName,
19171
+ epoch,
19172
+ classifierMode: null,
19173
+ classifierReason: null,
19174
+ keyframeBlocksProtected: 0,
19175
+ unknownBlocksProtected: 0,
19176
+ keyframeBlocksRecoveredInband: 0,
19177
+ keyframeBlocksRecoveredQuic: 0,
19178
+ keyframeBlocksFailed: 0,
19179
+ deltaBlocksShort: 0,
19180
+ deltaBlocksRecoveredInband: 0,
19181
+ deltaBlocksRecoveredQuic: 0,
19182
+ deltaRepairsPreempted: 0,
19183
+ deltaRepairsDeferred: 0,
19184
+ deltaBlocksFailed: 0,
19185
+ audioBlocksRecoveredInband: 0,
19186
+ audioBlocksRecoveredQuic: 0,
19187
+ audioBlocksFailed: 0,
19188
+ stalls: 0,
19189
+ concealedBlocks: 0,
19190
+ concealedGaps: 0,
19191
+ concealedFrames: 0,
19192
+ concealedAudioMs: 0,
19193
+ vanishedBlocks: 0
19194
+ };
19195
+ }
17401
19196
  var REPAIR_LIFECYCLE_EVENT_TYPE = "repairlifecycle";
17402
19197
  var REPAIR_LIFECYCLE_LOG_PREFIX = "[MulticastManager] repair-lifecycle ";
17403
19198
  function createDefaultRepairLifecycleEvent(detail, options) {
@@ -17434,24 +19229,105 @@ function isDecoderUnavailableReason(value) {
17434
19229
  function isFecFallbackDecoder(value) {
17435
19230
  return value === "sync" || value === "none";
17436
19231
  }
19232
+ var BLOCK_CLASSES = /* @__PURE__ */ new Set(["keyframe", "delta", "unknown", "audio"]);
19233
+ var RECLASSIFICATION_EVIDENCE = /* @__PURE__ */ new Set([
19234
+ "rap",
19235
+ "mpu-span",
19236
+ "window",
19237
+ "classifier-disabled"
19238
+ ]);
19239
+ var CLASSIFIER_MODES = /* @__PURE__ */ new Set(["classifying", "all-protected"]);
19240
+ var CLASSIFIER_REASONS = /* @__PURE__ */ new Set([
19241
+ "framerate-absent",
19242
+ "keyframe-cadence-absent",
19243
+ "keyframe-interval-not-integral",
19244
+ "block-spans-gop",
19245
+ "keyframe-interval-not-media-integral",
19246
+ "rap-not-mpu-start",
19247
+ "stream-geometry-absent",
19248
+ "mpu-longer-than-gop",
19249
+ "block-not-contiguous",
19250
+ "rap-spacing-mismatch",
19251
+ "mpu-multiple-fragments",
19252
+ "block-wider-than-interleave"
19253
+ ]);
19254
+ var REPAIR_PRIORITY_REASONS = /* @__PURE__ */ new Set([
19255
+ "source-priority-absent",
19256
+ "source-priority-invalid",
19257
+ "repair-priority-absent",
19258
+ "repair-priority-invalid"
19259
+ ]);
19260
+ var GAP_REASONS = {
19261
+ "rap-lost": "stall",
19262
+ "rap-unknown": "stall",
19263
+ discontinuity: "stall",
19264
+ "delta-lost": "conceal",
19265
+ "rap-next": "conceal",
19266
+ "audio-gap": "conceal",
19267
+ "audio-discontinuity": "conceal"
19268
+ };
19269
+ function hasExactKeys(value, keys) {
19270
+ const present = Object.keys(value);
19271
+ return present.length === keys.length && keys.every((key) => key in value);
19272
+ }
19273
+ function isNonNegativeSafeInteger(value) {
19274
+ return Number.isSafeInteger(value) && value >= 0;
19275
+ }
19276
+ function isSymbolCounts(value) {
19277
+ return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
19278
+ }
19279
+ function isNullableNonNegative(value) {
19280
+ return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
19281
+ }
17437
19282
  function isRepairLifecycleEvent(value) {
17438
- if (!isRecord(value)) return false;
17439
- const version = value["version"];
17440
- const type = value["type"];
19283
+ if (!isRecord(value) || value["version"] !== 2) return false;
17441
19284
  const block = value["block"];
17442
- const symbols = value["symbols"];
17443
- if (version !== 1) return false;
17444
- if (type === "decoder-unavailable") {
17445
- return isRepairStreamIdentity(value["stream"]) && isDecoderUnavailableReason(value["reason"]) && isFecFallbackDecoder(value["fallbackDecoder"]) && block === void 0 && symbols === void 0;
17446
- }
17447
- if (type !== "requested" && type !== "recovered" && type !== "failed" || !isRepairBlockIdentity(block) || value["stream"] !== void 0 || value["reason"] !== void 0 || value["fallbackDecoder"] !== void 0) {
17448
- return false;
19285
+ switch (value["type"]) {
19286
+ case "requested": {
19287
+ const blockClass = value["blockClass"];
19288
+ return hasExactKeys(value, ["version", "type", "block", "blockClass", "priority"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(blockClass) && value["priority"] === repairPriorityForClass(blockClass);
19289
+ }
19290
+ case "reclassified":
19291
+ return hasExactKeys(value, ["version", "type", "block", "from", "to", "evidence"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["from"]) && BLOCK_CLASSES.has(value["to"]) && RECLASSIFICATION_EVIDENCE.has(value["evidence"]);
19292
+ case "recovered":
19293
+ return hasExactKeys(value, ["version", "type", "block", "blockClass", "via", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && (value["via"] === "inband" || value["via"] === "quic") && isSymbolCounts(value["symbols"]);
19294
+ case "failed":
19295
+ return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
19296
+ case "repair-preempted":
19297
+ case "repair-deferred":
19298
+ return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
19299
+ case "repair-priority": {
19300
+ const blockClass = value["blockClass"];
19301
+ const action = value["action"];
19302
+ const reason = value["reason"];
19303
+ const expected = BLOCK_CLASSES.has(blockClass) && repairPriorityForClass(blockClass) === 0 ? "omitted" : "declined";
19304
+ return hasExactKeys(value, ["version", "type", "block", "blockClass", "action", "reason"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(blockClass) && action === expected && REPAIR_PRIORITY_REASONS.has(reason) && action === "omitted" === (reason === "source-priority-absent" || reason === "source-priority-invalid");
19305
+ }
19306
+ case "classifier": {
19307
+ const reason = value["reason"];
19308
+ return hasExactKeys(value, ["version", "type", "stream", "mode", "reason"]) && isRepairStreamIdentity(value["stream"]) && CLASSIFIER_MODES.has(value["mode"]) && (reason === null || CLASSIFIER_REASONS.has(reason));
19309
+ }
19310
+ case "gap": {
19311
+ const reason = value["reason"];
19312
+ const blocks = value["blocks"];
19313
+ return hasExactKeys(value, [
19314
+ "version",
19315
+ "type",
19316
+ "stream",
19317
+ "trackKind",
19318
+ "action",
19319
+ "reason",
19320
+ "blocks",
19321
+ "missingFrames",
19322
+ "missingMs",
19323
+ "epoch"
19324
+ ]) && isRepairStreamIdentity(value["stream"]) && (value["trackKind"] === "video" || value["trackKind"] === "audio") && typeof reason === "string" && GAP_REASONS[reason] !== void 0 && GAP_REASONS[reason] === value["action"] && Array.isArray(blocks) && blocks.every(isNonNegativeSafeInteger) && (value["missingFrames"] === null || isNonNegativeSafeInteger(value["missingFrames"])) && isNullableNonNegative(value["missingMs"]) && isNonNegativeSafeInteger(value["epoch"]);
19325
+ }
19326
+ case "decoder-unavailable":
19327
+ return hasExactKeys(value, ["version", "type", "stream", "reason", "fallbackDecoder"]) && isRepairStreamIdentity(value["stream"]) && isDecoderUnavailableReason(value["reason"]) && isFecFallbackDecoder(value["fallbackDecoder"]);
19328
+ default:
19329
+ return false;
17449
19330
  }
17450
- if (type === "requested") return symbols === void 0;
17451
- if (!isRecord(symbols)) return false;
17452
- const multicast = symbols["multicast"];
17453
- const moq = symbols["moq"];
17454
- return Number.isSafeInteger(multicast) && multicast >= 0 && Number.isSafeInteger(moq) && moq >= 0;
17455
19331
  }
17456
19332
  function forwardRepairLifecycleEvents(source, target, options = {}) {
17457
19333
  return source.addRepairLifecycleObserver((event) => {
@@ -17555,7 +19431,12 @@ function publishFecDiagnostics(packetId, stats) {
17555
19431
  blocksComplete: stats.blocksComplete,
17556
19432
  blocksRecovered: stats.blocksRecovered,
17557
19433
  blocksFailed: stats.blocksFailed,
17558
- greenFillFrames: stats.greenFillFrames,
19434
+ // Required by the IWA subscription_diagnostics contract (pim
19435
+ // normalizeSubscriptionDiagnostics rejects a report without it). No
19436
+ // fill frame is ever synthesised any more — concealment is the sink's
19437
+ // hold-last-good-frame — so the value is 0 until that contract drops
19438
+ // the field.
19439
+ greenFillFrames: 0,
17559
19440
  recoveryRate: stats.recoveryRate,
17560
19441
  liveSbn: stats.liveSbn,
17561
19442
  blocks: stats.blocks.slice(-FEC_DIAGNOSTIC_BLOCK_TAIL).map(projectFecDiagnosticBlock),
@@ -17616,6 +19497,8 @@ var MulticastManager = class {
17616
19497
  #trackResetObservers = /* @__PURE__ */ new Set();
17617
19498
  /** Callback fired when a repair fetch should be issued for a block. */
17618
19499
  #onRepairSubscribeCb = null;
19500
+ /** Keyframe-protected repair policy counters per catalog track. */
19501
+ #blockPolicyStats = /* @__PURE__ */ new Map();
17619
19502
  constructor(options) {
17620
19503
  this.#logRepairLifecycle = options?.logRepairLifecycle === true;
17621
19504
  this.#fec = new FECManager();
@@ -17641,21 +19524,48 @@ var MulticastManager = class {
17641
19524
  manifestVerifierOwnership: options?.manifestVerifierOwnership,
17642
19525
  resolveManifestIdentity: options?.resolveManifestIdentity,
17643
19526
  resolveManifestIdentityForRoute: options?.resolveManifestIdentityForRoute,
17644
- onBlockFailed: (sbn, packetId, catalogTrackName) => {
19527
+ // The router has reset its own state for the stream; reset the rest.
19528
+ onPublisherRestart: (packetId, catalogTrackName) => {
19529
+ this.#resetStreamOutsideRouter(packetId, catalogTrackName);
19530
+ },
19531
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
17645
19532
  const pathCount = this.#fec.blockPathCount(
17646
19533
  sbn,
17647
19534
  packetId,
17648
19535
  catalogTrackName
17649
19536
  );
19537
+ const stats = this.#statsFor(packetId, catalogTrackName);
19538
+ if (blockClass === "delta") stats.deltaBlocksFailed++;
19539
+ else if (blockClass === "audio") stats.audioBlocksFailed++;
19540
+ else stats.keyframeBlocksFailed++;
17650
19541
  this.#emitRepairLifecycle({
17651
- version: 1,
19542
+ version: 2,
17652
19543
  type: "failed",
17653
19544
  block: repairBlockIdentity(packetId, sbn, catalogTrackName),
19545
+ blockClass,
17654
19546
  symbols: {
17655
19547
  multicast: pathCount?.multicastSymbols ?? 0,
17656
19548
  moq: pathCount?.moqSymbols ?? 0
17657
19549
  }
17658
19550
  });
19551
+ },
19552
+ onFrameGap: (decision) => {
19553
+ const stats = this.#statsFor(
19554
+ decision.stream.packetId,
19555
+ decision.stream.catalogTrackName ?? void 0
19556
+ );
19557
+ if (decision.action === "stall") {
19558
+ stats.stalls++;
19559
+ } else {
19560
+ stats.concealedGaps++;
19561
+ stats.concealedBlocks += decision.blocks.length;
19562
+ if (decision.trackKind === "audio") {
19563
+ stats.concealedAudioMs += decision.missingMs ?? 0;
19564
+ } else {
19565
+ stats.concealedFrames += decision.missingFrames ?? 0;
19566
+ }
19567
+ }
19568
+ this.#emitRepairLifecycle(decision);
17659
19569
  }
17660
19570
  });
17661
19571
  this.#transport = new MulticastTransport((packet, ingress) => {
@@ -17676,29 +19586,63 @@ var MulticastManager = class {
17676
19586
  );
17677
19587
  }
17678
19588
  };
17679
- this.#fec.onRepairResolved = (sbn, packetId, outcome, catalogTrackName) => {
19589
+ this.#fec.onRepairResolved = (sbn, packetId, _outcome, catalogTrackName) => {
17680
19590
  this.clearRepairForBlock(sbn, packetId, catalogTrackName);
17681
- if (outcome === "failed") return;
17682
- const pathCount = this.#fec.blockPathCount(
17683
- sbn,
17684
- packetId,
17685
- catalogTrackName
17686
- );
17687
- const multicastSymbols = pathCount?.multicastSymbols ?? 0;
17688
- const moqSymbols = pathCount?.moqSymbols ?? 0;
19591
+ };
19592
+ this.#fec.onBlockRepaired = (sbn, packetId, catalogTrackName, blockClass, via) => {
19593
+ const pathCount = this.#fec.blockPathCount(sbn, packetId, catalogTrackName);
19594
+ const stats = this.#statsFor(packetId, catalogTrackName);
19595
+ if (blockClass === "delta") {
19596
+ if (via === "quic") stats.deltaBlocksRecoveredQuic++;
19597
+ else stats.deltaBlocksRecoveredInband++;
19598
+ } else if (blockClass === "audio") {
19599
+ if (via === "quic") stats.audioBlocksRecoveredQuic++;
19600
+ else stats.audioBlocksRecoveredInband++;
19601
+ } else if (via === "quic") {
19602
+ stats.keyframeBlocksRecoveredQuic++;
19603
+ } else {
19604
+ stats.keyframeBlocksRecoveredInband++;
19605
+ }
17689
19606
  this.#emitRepairLifecycle({
17690
- version: 1,
19607
+ version: 2,
17691
19608
  type: "recovered",
17692
19609
  block: repairBlockIdentity(packetId, sbn, catalogTrackName),
19610
+ blockClass,
19611
+ via,
17693
19612
  symbols: {
17694
- multicast: multicastSymbols,
17695
- moq: moqSymbols
19613
+ multicast: pathCount?.multicastSymbols ?? 0,
19614
+ moq: pathCount?.moqSymbols ?? 0
17696
19615
  }
17697
19616
  });
17698
19617
  };
19618
+ this.#fec.onBlockReclassified = (sbn, packetId, catalogTrackName, from, to, evidence) => {
19619
+ this.#emitRepairLifecycle({
19620
+ version: 2,
19621
+ type: "reclassified",
19622
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
19623
+ from,
19624
+ to,
19625
+ evidence
19626
+ });
19627
+ };
19628
+ this.#fec.onClassifierMode = (packetId, catalogTrackName, mode, reason) => {
19629
+ const stats = this.#statsFor(packetId, catalogTrackName);
19630
+ stats.classifierMode = mode;
19631
+ stats.classifierReason = reason;
19632
+ this.#emitRepairLifecycle({
19633
+ version: 2,
19634
+ type: "classifier",
19635
+ stream: repairStreamIdentity(packetId, catalogTrackName),
19636
+ mode,
19637
+ reason
19638
+ });
19639
+ };
19640
+ this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
19641
+ this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
19642
+ };
17699
19643
  this.#fec.onDecoderUnavailable = (event) => {
17700
19644
  this.#emitRepairLifecycle({
17701
- version: 1,
19645
+ version: 2,
17702
19646
  type: "decoder-unavailable",
17703
19647
  stream: repairStreamIdentity(event.packetId, event.catalogTrackName),
17704
19648
  reason: event.reason,
@@ -17744,7 +19688,7 @@ var MulticastManager = class {
17744
19688
  // FEC configuration (delegates to FECManager)
17745
19689
  // ---------------------------------------------------------------------------
17746
19690
  setFecDecoder(packetId, client, k, trackType = "video", config, catalogTrackName) {
17747
- const fecConfig = { ...config, k };
19691
+ const fecConfig = { ...config, k, trackKind: config?.trackKind ?? trackType };
17748
19692
  this.#fec.setFecDecoder(packetId, client, k, fecConfig, catalogTrackName);
17749
19693
  this.#configureTrackMapper(packetId, fecConfig);
17750
19694
  this.#router.setPacketIdType(packetId, trackType);
@@ -17755,7 +19699,12 @@ var MulticastManager = class {
17755
19699
  * FECManager.onBlockRecovered callback instead of feedSourceSymbol return value.
17756
19700
  */
17757
19701
  setFecWorker(packetId, client, trackType, config, catalogTrackName) {
17758
- this.#fec.setFecWorker(packetId, client, config, catalogTrackName);
19702
+ this.#fec.setFecWorker(
19703
+ packetId,
19704
+ client,
19705
+ { ...config, trackKind: config.trackKind ?? trackType },
19706
+ catalogTrackName
19707
+ );
17759
19708
  this.#configureTrackMapper(packetId, config);
17760
19709
  this.#router.setPacketIdType(packetId, trackType);
17761
19710
  }
@@ -17859,8 +19808,20 @@ var MulticastManager = class {
17859
19808
  * window) become an explicit max reduction instead of a last-caller-wins race
17860
19809
  * in which whichever track configured last silently set the whole stream's
17861
19810
  * timing.
19811
+ *
19812
+ * `catalogTrackName` scopes the block-classifier geometry (kind, fps,
19813
+ * interleave, cadence) to that one stream. Pass it whenever ABR rungs can
19814
+ * share this packetId: each rung then classifies with its own framerate
19815
+ * and GOP, and a rung on the packetId that was never configured this way
19816
+ * runs all-protected (`stream-geometry-absent`) instead of borrowing a
19817
+ * sibling's geometry. K, T and the delivery timing stay per packetId.
17862
19818
  */
17863
- configureTrackFec(packetId, config) {
19819
+ configureTrackFec(packetId, config, catalogTrackName) {
19820
+ if (catalogTrackName !== void 0 && catalogTrackName.length === 0) {
19821
+ throw new Error(
19822
+ `[MulticastManager] configureTrackFec(${packetId}) catalogTrackName must be non-empty when given`
19823
+ );
19824
+ }
17864
19825
  if (config.fecK === void 0 || config.fecInterleaveDepthMs === void 0) {
17865
19826
  throw new Error(
17866
19827
  `[MulticastManager] configureTrackFec(${packetId}) requires fecK and fecInterleaveDepthMs. Derive the per-track FEC geometry from the stream catalog.`
@@ -17875,6 +19836,9 @@ var MulticastManager = class {
17875
19836
  "minimumFailbackWindowMs",
17876
19837
  config.minimumFailbackWindowMs
17877
19838
  );
19839
+ assertPositiveGeometry("timescale", config.timescale);
19840
+ assertPositiveGeometry("keyframeIntervalTicks", config.keyframeIntervalTicks);
19841
+ assertPositiveGeometry("keyframeIntervalMs", config.keyframeIntervalMs);
17878
19842
  assertNonNegativeGeometry("fecRepairSymbols", config.fecRepairSymbols);
17879
19843
  assertNonNegativeGeometry(
17880
19844
  "fecReorderToleranceMs",
@@ -17889,14 +19853,26 @@ var MulticastManager = class {
17889
19853
  bandwidthBps: config.bandwidth,
17890
19854
  jitterBufferMs: config.fecReorderToleranceMs
17891
19855
  }) : void 0;
19856
+ const trackKind = config.trackKind ?? this.#router.trackKindFor(packetId);
19857
+ const geometry = trackKind === void 0 ? void 0 : deriveBlockClassifierGeometry({
19858
+ trackKind,
19859
+ framerate: config.fps,
19860
+ interleaveDepthMs: config.fecInterleaveDepthMs,
19861
+ timescale: config.timescale,
19862
+ keyframeIntervalTicks: config.keyframeIntervalTicks,
19863
+ keyframeIntervalMs: config.keyframeIntervalMs
19864
+ });
17892
19865
  const fecConfig = {
17893
19866
  k: config.fecK,
17894
19867
  symbolSize: config.fecSymbolSize,
17895
19868
  interleaveDepthMs: config.fecInterleaveDepthMs,
17896
19869
  fps: config.fps,
17897
- timeoutMs: deliveryWindowMs
19870
+ timeoutMs: deliveryWindowMs,
19871
+ ...trackKind === void 0 ? {} : { trackKind },
19872
+ ...config.codec === void 0 ? {} : { codec: config.codec },
19873
+ ...geometry === void 0 ? {} : { geometry }
17898
19874
  };
17899
- this.#fec.configureTrack(packetId, fecConfig);
19875
+ this.#fec.configureTrack(packetId, fecConfig, catalogTrackName);
17900
19876
  this.#configureTrackMapper(packetId, fecConfig);
17901
19877
  this.#trackFecTiming.set(packetId, {
17902
19878
  deliveryWindowMs,
@@ -17972,10 +19948,11 @@ var MulticastManager = class {
17972
19948
  this.#onTrackTypeDiscovered?.(packetId, trackType);
17973
19949
  }
17974
19950
  /**
17975
- * Set the keyframe loss timeout on the inner MmtpRouter.
19951
+ * Set the keyframe loss timeout on the inner MmtpRouter (Phase 13).
19952
+ * Applies only to tracks WITHOUT FEC: an FEC track never arms the timer,
19953
+ * because its vanished blocks resolve through catalog-derived block
19954
+ * deadlines and the release gate's stall decision.
17976
19955
  * Must be called BEFORE setPacketIdType('video').
17977
- * Derive from explicit keyframe/group duration:
17978
- * Math.ceil(groupDurationMs * KEYFRAME_LOST_TIMEOUT_SLACK).
17979
19956
  */
17980
19957
  setKeyframeLostTimeoutMs(ms) {
17981
19958
  this.#router.setKeyframeLostTimeoutMs(ms);
@@ -17985,6 +19962,9 @@ var MulticastManager = class {
17985
19962
  }
17986
19963
  setTrackCodec(packetId, codec) {
17987
19964
  this.#router.setTrackCodec(packetId, codec);
19965
+ if (this.#fec.isTrackConfigured(packetId)) {
19966
+ this.#fec.configureTrack(packetId, { codec });
19967
+ }
17988
19968
  }
17989
19969
  // ---------------------------------------------------------------------------
17990
19970
  // Callbacks (delegates to MmtpRouter)
@@ -18245,7 +20225,8 @@ var MulticastManager = class {
18245
20225
  k: fecCfg.sourceSymbols,
18246
20226
  symbolSize: fecCfg.symbolSize,
18247
20227
  interleaveDepthMs: fecCfg.interleaveDepthMs,
18248
- fps: track.framerate
20228
+ fps: track.framerate,
20229
+ trackKind: "video"
18249
20230
  },
18250
20231
  track.name
18251
20232
  );
@@ -18286,10 +20267,66 @@ var MulticastManager = class {
18286
20267
  */
18287
20268
  onRepairSubscribe(cb) {
18288
20269
  this.#onRepairSubscribeCb = cb;
18289
- this.#fec.onRepairNeeded = (sbn, packetId, catalogTrackName) => {
18290
- this.requestRepairForBlock(sbn, packetId, catalogTrackName);
20270
+ this.#fec.onRepairNeeded = (sbn, packetId, catalogTrackName, blockClass) => {
20271
+ this.requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass);
18291
20272
  };
18292
20273
  }
20274
+ /**
20275
+ * Record a repair request whose SUBSCRIBER_PRIORITY the catalog could not
20276
+ * supply (draft-ramadan-moq-fec §11.4.5): sent without the parameter, or
20277
+ * not sent. Emits one `repair-priority` lifecycle event.
20278
+ */
20279
+ noteRepairPriority(action, reason, blockClass, sbn, packetId, catalogTrackName) {
20280
+ this.#emitRepairLifecycle({
20281
+ version: 2,
20282
+ type: "repair-priority",
20283
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName),
20284
+ blockClass,
20285
+ action,
20286
+ reason
20287
+ });
20288
+ }
20289
+ /**
20290
+ * Record a repair-scheduler decision about a delta block: preempted for
20291
+ * keyframe/audio work, or never dispatched before its block resolved.
20292
+ */
20293
+ noteRepairScheduling(type, sbn, packetId, catalogTrackName) {
20294
+ const stats = this.#statsFor(packetId, catalogTrackName);
20295
+ if (type === "repair-preempted") stats.deltaRepairsPreempted++;
20296
+ else stats.deltaRepairsDeferred++;
20297
+ this.#emitRepairLifecycle({
20298
+ version: 2,
20299
+ type,
20300
+ block: repairBlockIdentity(packetId, sbn, catalogTrackName)
20301
+ });
20302
+ }
20303
+ /** Catalog/reset epoch of a packet's streams; gap decisions carry it. */
20304
+ epochFor(packetId) {
20305
+ return this.#fec.epochFor(packetId);
20306
+ }
20307
+ /**
20308
+ * Keyframe-protected repair policy counters, keyed by catalog track name
20309
+ * (`packetId:<n>` for a stream with no catalog name). Each track's
20310
+ * counters reset with its epoch.
20311
+ */
20312
+ getBlockPolicyStats() {
20313
+ const out = {};
20314
+ for (const [key, stats] of this.#blockPolicyStats) {
20315
+ if (stats.epoch !== this.#fec.epochFor(stats.packetId)) continue;
20316
+ out[key] = { ...stats };
20317
+ }
20318
+ return out;
20319
+ }
20320
+ #statsFor(packetId, catalogTrackName) {
20321
+ const key = catalogTrackName ?? `packetId:${packetId}`;
20322
+ const epoch = this.#fec.epochFor(packetId);
20323
+ let stats = this.#blockPolicyStats.get(key);
20324
+ if (!stats || stats.epoch !== epoch || stats.packetId !== packetId) {
20325
+ stats = newBlockPolicyStats(packetId, catalogTrackName ?? null, epoch);
20326
+ this.#blockPolicyStats.set(key, stats);
20327
+ }
20328
+ return stats;
20329
+ }
18293
20330
  /**
18294
20331
  * Observe causal repair lifecycle events without retaining snapshots in the
18295
20332
  * transport. Returns an unsubscribe function.
@@ -18308,6 +20345,11 @@ var MulticastManager = class {
18308
20345
  if (!catalogTrackName) {
18309
20346
  throw new Error("[MulticastManager] catalogTrackName is required for track reset");
18310
20347
  }
20348
+ this.#resetStreamOutsideRouter(packetId, catalogTrackName);
20349
+ this.#router.resetTrack(packetId, catalogTrackName);
20350
+ }
20351
+ /** resetTrack() for everything but the router's own state. */
20352
+ #resetStreamOutsideRouter(packetId, catalogTrackName) {
18311
20353
  for (const observer of this.#trackResetObservers) {
18312
20354
  try {
18313
20355
  observer(packetId, catalogTrackName);
@@ -18325,7 +20367,6 @@ var MulticastManager = class {
18325
20367
  }
18326
20368
  }
18327
20369
  this.#fec.resetTrack(packetId, catalogTrackName);
18328
- this.#router.resetTrack(packetId, catalogTrackName);
18329
20370
  }
18330
20371
  /**
18331
20372
  * Request a repair-track fetch for the given FEC block.
@@ -18337,21 +20378,23 @@ var MulticastManager = class {
18337
20378
  * @param packetId - MMTP packet_id owning the block (video/audio tracks have
18338
20379
  * independent SBN spaces, so the in-flight key must be composite).
18339
20380
  */
18340
- requestRepairForBlock(sbn, packetId, catalogTrackName) {
20381
+ requestRepairForBlock(sbn, packetId, catalogTrackName, blockClass) {
18341
20382
  const block = repairBlockIdentity(packetId, sbn, catalogTrackName);
18342
20383
  const key = JSON.stringify([packetId, block.catalogTrackName, sbn]);
18343
20384
  if (this.#repairInFlight.has(key)) return;
18344
20385
  this.#repairInFlight.add(key);
20386
+ const stats = this.#statsFor(packetId, catalogTrackName);
20387
+ if (blockClass === "keyframe") stats.keyframeBlocksProtected++;
20388
+ else if (blockClass === "unknown") stats.unknownBlocksProtected++;
20389
+ else if (blockClass === "delta") stats.deltaBlocksShort++;
18345
20390
  this.#emitRepairLifecycle({
18346
- version: 1,
20391
+ version: 2,
18347
20392
  type: "requested",
18348
- block
20393
+ block,
20394
+ blockClass,
20395
+ priority: repairPriorityForClass(blockClass)
18349
20396
  });
18350
- if (catalogTrackName === void 0) {
18351
- this.#onRepairSubscribeCb?.(sbn, packetId);
18352
- } else {
18353
- this.#onRepairSubscribeCb?.(sbn, packetId, catalogTrackName);
18354
- }
20397
+ this.#onRepairSubscribeCb?.(sbn, packetId, catalogTrackName, blockClass);
18355
20398
  }
18356
20399
  /**
18357
20400
  * Clear in-flight repair state for the given block.
@@ -18363,11 +20406,11 @@ var MulticastManager = class {
18363
20406
  );
18364
20407
  }
18365
20408
  #emitRepairLifecycle(event) {
18366
- const immutableEvent = Object.freeze(
18367
- event.type === "decoder-unavailable" ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
20409
+ const immutableEvent = event.type === "gap" ? event : Object.freeze(
20410
+ "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
18368
20411
  ...event,
18369
20412
  block: Object.freeze({ ...event.block }),
18370
- ...event.type === "requested" ? {} : { symbols: Object.freeze({ ...event.symbols }) }
20413
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
18371
20414
  }
18372
20415
  );
18373
20416
  if (this.#logRepairLifecycle) {
@@ -18561,7 +20604,13 @@ var MediaRouter = class {
18561
20604
  this.#audioFallbackMs = options?.audioFallbackMs ?? 0;
18562
20605
  this.#crossfadeFrames = options?.crossfadeFrames ?? DEFAULT_CROSSFADE_FRAMES;
18563
20606
  this.#maxOverlayBuffer = options?.maxOverlayBuffer ?? DEFAULT_MAX_OVERLAY_BUFFER;
18564
- this.#maxRepairInFlight = options?.maxRepairInFlight ?? 2;
20607
+ const maxRepairInFlight = options?.maxRepairInFlight;
20608
+ if (maxRepairInFlight !== void 0 && (!Number.isSafeInteger(maxRepairInFlight) || maxRepairInFlight < 1)) {
20609
+ throw new Error(
20610
+ `[MediaRouter] maxRepairInFlight=${maxRepairInFlight} must be a positive integer`
20611
+ );
20612
+ }
20613
+ this.#maxRepairInFlight = maxRepairInFlight ?? null;
18565
20614
  this.#allowDeltaMulticastTakeoverAfterMoqKeyframe = options?.allowDeltaMulticastTakeoverAfterMoqKeyframe ?? false;
18566
20615
  }
18567
20616
  onVideoFrame(cb) {
@@ -18582,6 +20631,11 @@ var MediaRouter = class {
18582
20631
  // ── Keyframe repair API ──────────────────────────────────────────
18583
20632
  /** Register callback for keyframe repair requests. Player wires this to issue MoQ SUBSCRIBE. */
18584
20633
  onRepairRequest(cb) {
20634
+ if (this.#maxRepairInFlight === null) {
20635
+ throw new Error(
20636
+ "[MediaRouter] onRepairRequest requires an explicit maxRepairInFlight option"
20637
+ );
20638
+ }
18585
20639
  this.#onRepairRequest = cb;
18586
20640
  }
18587
20641
  /**
@@ -18592,6 +20646,7 @@ var MediaRouter = class {
18592
20646
  */
18593
20647
  repairLostGroup(expectedGroupId, trackName = "video") {
18594
20648
  if (this.#active !== "multicast") return;
20649
+ if (this.#maxRepairInFlight === null) return;
18595
20650
  if (this.#repairInFlight.has(expectedGroupId)) return;
18596
20651
  if (this.#repairInFlight.size >= this.#maxRepairInFlight) {
18597
20652
  console.warn(
@@ -19291,13 +21346,17 @@ var MmtpDecodePipeline = class {
19291
21346
  }
19292
21347
  let outcomeKind = "threw";
19293
21348
  try {
21349
+ let record;
19294
21350
  if (this.#fecClient?.addSourceSymbol) {
19295
- const info = this.#parser.parseHeader(packet);
19296
- if (info?.fecPayloadId) {
19297
- this.#fecClient.addSourceSymbol(info.fecPayloadId.ssId, packet);
21351
+ const parsed = this.#parser.parsePacket(packet);
21352
+ const fecPayloadId = parsed?.info.fecPayloadId;
21353
+ if (fecPayloadId) {
21354
+ this.#fecClient.addSourceSymbol(fecPayloadId.ssId, packet);
19298
21355
  }
21356
+ record = parsed ? this.#parser.feedParsed(packet, parsed) : this.#parser.feed(packet);
21357
+ } else {
21358
+ record = this.#parser.feed(packet);
19299
21359
  }
19300
- const record = this.#parser.feed(packet);
19301
21360
  outcomeKind = record?.kind ?? "null(parse-or-extract-failed)";
19302
21361
  } finally {
19303
21362
  const seen = (this.#feedOutcomes.get(outcomeKind) ?? 0) + 1;
@@ -19861,9 +21920,6 @@ function buildFecParams(stats) {
19861
21920
  params["x-bc-fec-k"] = cfg.k;
19862
21921
  params["x-bc-fec-p"] = cfg.repairCount;
19863
21922
  params["x-bc-fec-recovery"] = parseFloat((stats.recoveryRate / 100).toFixed(4));
19864
- if (stats.greenFillFrames > 0) {
19865
- params["x-bc-scu"] = stats.greenFillFrames;
19866
- }
19867
21923
  if (cfg.altaEnabled) {
19868
21924
  params["x-bc-alta-verified"] = stats.altaVerified > 0;
19869
21925
  params["x-bc-alta-failures"] = stats.altaFailed;
@@ -20167,6 +22223,19 @@ function resolveRepairLayers(catalog, source) {
20167
22223
  layerZeroMustBeDeclared: true
20168
22224
  });
20169
22225
  }
22226
+ function moqtPriority2(value) {
22227
+ return Number.isSafeInteger(value) && value >= 0 && value <= 255 ? value : null;
22228
+ }
22229
+ function catalogRepairTarget(catalog, source) {
22230
+ const repair = resolveRepairLayers(catalog, source);
22231
+ const layerZero = repair?.baseLayers[0];
22232
+ if (!catalog || !layerZero) return null;
22233
+ const sourceName = typeof source === "string" ? source : source.name;
22234
+ const msf = msfTracks(catalog);
22235
+ const entry = msf?.tracks.find((t) => t["name"] === sourceName);
22236
+ const sourcePriority = entry === void 0 ? null : moqtPriority2(entry["priority"] ?? msf.common["priority"]);
22237
+ return { repairTrack: layerZero.repairTrackName, sourcePriority, repairPriority: layerZero.priority };
22238
+ }
20170
22239
  function geometryOf(name, path, fec) {
20171
22240
  return {
20172
22241
  name,
@@ -20229,6 +22298,19 @@ function resolveCatalogTrackFec(catalog, tracks) {
20229
22298
  audioFps,
20230
22299
  sampleRate
20231
22300
  );
22301
+ const forTrack = (track) => {
22302
+ if (track.type === "audio") {
22303
+ if (track.name === audioTrackName) return audioParams;
22304
+ const rendition2 = audioRenditions?.[track.name];
22305
+ if (!rendition2) return { ...NO_FEC };
22306
+ const rate = numericField(rendition2.sampleRate ?? rendition2.samplerate);
22307
+ return fecParams(catalog, { name: track.name, type: "audio" }, rendition2, rate ? rate / 1024 : void 0, rate);
22308
+ }
22309
+ if (track.name === videoTrackName) return videoParams;
22310
+ const rendition = videoRenditions?.[track.name];
22311
+ if (!rendition) return { ...NO_FEC };
22312
+ return fecParams(catalog, { name: track.name, type: "video" }, rendition, numericField(rendition.framerate));
22313
+ };
20232
22314
  return {
20233
22315
  videoTrackName,
20234
22316
  audioTrackName,
@@ -20238,7 +22320,7 @@ function resolveCatalogTrackFec(catalog, tracks) {
20238
22320
  catalogFps,
20239
22321
  video: videoParams,
20240
22322
  audio: audioParams,
20241
- forTrack: (track) => track.type === "audio" ? audioParams : videoParams
22323
+ forTrack
20242
22324
  };
20243
22325
  }
20244
22326
 
@@ -20262,53 +22344,199 @@ function catalogAmtNetworkSource(networkSource) {
20262
22344
  }
20263
22345
 
20264
22346
  // src/repair-fetch.ts
22347
+ var MOQT_PRIORITY_MAX = 255;
22348
+ var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
22349
+ function isMoqtPriority(value) {
22350
+ return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
22351
+ }
22352
+ function repairFetchSubscriberPriority(blockClass, target) {
22353
+ if (repairPriorityForClass(blockClass) === 0) {
22354
+ const source = target.sourcePriority;
22355
+ if (source === null) return { kind: "omit", reason: "source-priority-absent" };
22356
+ if (!isMoqtPriority(source)) return { kind: "omit", reason: "source-priority-invalid" };
22357
+ return { kind: "carry", subscriberPriority: Math.min(source, SOURCE_MEDIA_PRIORITY_MAX) };
22358
+ }
22359
+ const repair = target.repairPriority;
22360
+ if (repair === null) return { kind: "decline", reason: "repair-priority-absent" };
22361
+ if (!isMoqtPriority(repair)) return { kind: "decline", reason: "repair-priority-invalid" };
22362
+ return { kind: "carry", subscriberPriority: Math.max(repair, REPAIR_PRIORITY_MIN) };
22363
+ }
20265
22364
  function wireRepairFetch(mc, opts) {
20266
- const inFlight = /* @__PURE__ */ new Map();
22365
+ if (!Number.isSafeInteger(opts.attemptLimit) || opts.attemptLimit < 1) {
22366
+ throw new Error(
22367
+ `[RepairFetch] attemptLimit=${String(opts.attemptLimit)} must be a positive integer`
22368
+ );
22369
+ }
22370
+ const entries = /* @__PURE__ */ new Map();
20267
22371
  const warnedNoTarget = /* @__PURE__ */ new Set();
20268
22372
  let disposed = false;
22373
+ let enqueueOrder = 0;
20269
22374
  const requestKey = (sbn, packetId, catalogTrackName) => JSON.stringify([packetId, catalogTrackName ?? null, sbn]);
20270
22375
  const noTargetKey = (packetId, catalogTrackName) => JSON.stringify([packetId, catalogTrackName ?? null]);
20271
- const removeResetObserver = mc.addTrackResetObserver(
20272
- (packetId, catalogTrackName) => {
20273
- for (const [key, request] of inFlight) {
20274
- if (request.packetId === packetId && request.catalogTrackName === catalogTrackName) {
20275
- request.controller.abort();
20276
- inFlight.delete(key);
20277
- }
20278
- }
20279
- warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
20280
- }
20281
- );
20282
- const timeoutFor = (sbn, packetId, catalogTrackName) => opts.timeoutMsForPacket?.(packetId) ?? mc.fecManager.repairFetchTimeoutMsForBlock(
20283
- sbn,
20284
- packetId,
20285
- catalogTrackName
20286
- );
20287
22376
  const clearRepair = (sbn, packetId, catalogTrackName) => {
20288
22377
  if (catalogTrackName === void 0) mc.clearRepairForBlock(sbn, packetId);
20289
22378
  else mc.clearRepairForBlock(sbn, packetId, catalogTrackName);
20290
22379
  };
20291
- const clearRepairIfOwner = (key, request) => {
20292
- if (inFlight.get(key) !== request) return;
20293
- clearRepair(request.sbn, request.packetId, request.catalogTrackName);
22380
+ const note = (type, entry) => {
22381
+ mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
22382
+ };
22383
+ const stop = (entry, reason) => {
22384
+ const run = entry.running;
22385
+ if (!run) return;
22386
+ entry.running = null;
22387
+ run.stopped = reason;
22388
+ run.controller.abort();
22389
+ };
22390
+ const retire = (entry) => {
22391
+ if (entries.get(entry.key) === entry) entries.delete(entry.key);
22392
+ };
22393
+ const urgentOutstanding = () => {
22394
+ for (const entry of entries.values()) {
22395
+ if (entry.priority < 2) return true;
22396
+ }
22397
+ return false;
22398
+ };
22399
+ const preemptDeltas = () => {
22400
+ for (const entry of entries.values()) {
22401
+ if (entry.priority !== 2 || !entry.running) continue;
22402
+ stop(entry, "preempted");
22403
+ note("repair-preempted", entry);
22404
+ }
22405
+ };
22406
+ const wirePriority = (entry, blockClass) => {
22407
+ const derived = repairFetchSubscriberPriority(blockClass, entry.target);
22408
+ if (derived.kind === "carry") return { subscriberPriority: derived.subscriberPriority };
22409
+ mc.noteRepairPriority(
22410
+ derived.kind === "omit" ? "omitted" : "declined",
22411
+ derived.reason,
22412
+ blockClass,
22413
+ entry.sbn,
22414
+ entry.packetId,
22415
+ entry.catalogTrackName
22416
+ );
22417
+ return derived.kind === "omit" ? { subscriberPriority: void 0 } : null;
22418
+ };
22419
+ const start = (entry, counted = true) => {
22420
+ if (counted) entry.attempts++;
22421
+ const run = { controller: new AbortController(), stopped: null };
22422
+ entry.running = run;
22423
+ void execute(entry, run);
22424
+ };
22425
+ const dispatch = () => {
22426
+ if (disposed) return;
22427
+ const now = performance.now();
22428
+ const queued = [];
22429
+ for (const entry of [...entries.values()]) {
22430
+ if (entry.running) {
22431
+ if (entry.deadlineAt <= now) {
22432
+ stop(entry, "expired");
22433
+ retire(entry);
22434
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
22435
+ }
22436
+ continue;
22437
+ }
22438
+ if (entry.deadlineAt <= now) {
22439
+ retire(entry);
22440
+ if (entry.priority === 2 && entry.attempts === 0) note("repair-deferred", entry);
22441
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
22442
+ continue;
22443
+ }
22444
+ queued.push(entry);
22445
+ }
22446
+ for (const entry of queued) {
22447
+ if (entry.priority < 2) start(entry);
22448
+ }
22449
+ if (urgentOutstanding()) return;
22450
+ queued.filter((entry) => entry.priority === 2).sort((a, b) => a.deadlineAt - b.deadlineAt || a.order - b.order).forEach((entry) => start(entry));
20294
22451
  };
20295
- const waitForRetry = (signal) => new Promise((resolve) => {
20296
- if (signal.aborted) {
20297
- resolve();
22452
+ const finish = (entry, run, fed, error) => {
22453
+ if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
20298
22454
  return;
20299
22455
  }
20300
- let timer;
20301
- const onAbort = () => {
20302
- clearTimeout(timer);
20303
- resolve();
20304
- };
20305
- timer = setTimeout(() => {
20306
- signal.removeEventListener("abort", onAbort);
20307
- resolve();
20308
- }, Math.max(1, opts.retryDelayMs ?? 10));
20309
- signal.addEventListener("abort", onAbort, { once: true });
22456
+ entry.running = null;
22457
+ if (error === void 0) {
22458
+ retire(entry);
22459
+ if (fed === 0) clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
22460
+ dispatch();
22461
+ return;
22462
+ }
22463
+ const retryable = fed === 0 && entry.attempts < opts.attemptLimit && entry.deadlineAt > performance.now() && opts.shouldRetry?.(error) === true;
22464
+ if (retryable) {
22465
+ dispatch();
22466
+ return;
22467
+ }
22468
+ retire(entry);
22469
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
22470
+ console.warn(
22471
+ `[RepairFetch] fetch failed pid=${entry.packetId} sbn=${entry.sbn} track=${entry.repairTrack}:`,
22472
+ error
22473
+ );
22474
+ dispatch();
22475
+ };
22476
+ const execute = async (entry, run) => {
22477
+ let fed = 0;
22478
+ try {
22479
+ for await (const packet of opts.transport({
22480
+ repairTrack: entry.repairTrack,
22481
+ sbn: entry.sbn,
22482
+ packetId: entry.packetId,
22483
+ signal: run.controller.signal,
22484
+ subscriberPriority: entry.subscriberPriority
22485
+ })) {
22486
+ if (run.stopped !== null || entry.running !== run) break;
22487
+ fed++;
22488
+ if (entry.catalogTrackName === void 0) {
22489
+ mc.processRepairFromMoQ(packet, entry.packetId);
22490
+ } else {
22491
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
22492
+ }
22493
+ }
22494
+ finish(entry, run, fed, void 0);
22495
+ } catch (error) {
22496
+ finish(entry, run, fed, error ?? new Error("repair transport rejected"));
22497
+ }
22498
+ };
22499
+ const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
22500
+ for (const entry of [...entries.values()]) {
22501
+ if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
22502
+ retire(entry);
22503
+ stop(entry, "reset");
22504
+ }
22505
+ warnedNoTarget.delete(noTargetKey(packetId, catalogTrackName));
22506
+ dispatch();
22507
+ });
22508
+ const removeLifecycleObserver = mc.addRepairLifecycleObserver((event) => {
22509
+ if (disposed) return;
22510
+ if (event.type === "reclassified") {
22511
+ const entry2 = entries.get(
22512
+ requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? void 0)
22513
+ );
22514
+ if (!entry2 || entry2.priority !== 2) return;
22515
+ const promoted = repairPriorityForClass(event.to);
22516
+ if (promoted >= entry2.priority) return;
22517
+ const wire = wirePriority(entry2, event.to);
22518
+ if (wire === null) return;
22519
+ entry2.priority = promoted;
22520
+ entry2.subscriberPriority = wire.subscriberPriority;
22521
+ if (entry2.running) {
22522
+ stop(entry2, "reprioritized");
22523
+ start(entry2, false);
22524
+ }
22525
+ preemptDeltas();
22526
+ dispatch();
22527
+ return;
22528
+ }
22529
+ if (event.type !== "recovered" && event.type !== "failed") return;
22530
+ const entry = entries.get(
22531
+ requestKey(event.block.sbn, event.block.packetId, event.block.catalogTrackName ?? void 0)
22532
+ );
22533
+ if (!entry) return;
22534
+ retire(entry);
22535
+ if (entry.running) stop(entry, "resolved");
22536
+ else if (entry.priority === 2 && entry.attempts === 0) note("repair-deferred", entry);
22537
+ dispatch();
20310
22538
  });
20311
- mc.onRepairSubscribe((sbn, packetId, catalogTrackName) => {
22539
+ mc.onRepairSubscribe((sbn, packetId, catalogTrackName, blockClass) => {
20312
22540
  if (disposed) {
20313
22541
  clearRepair(sbn, packetId, catalogTrackName);
20314
22542
  return;
@@ -20325,68 +22553,55 @@ function wireRepairFetch(mc, opts) {
20325
22553
  clearRepair(sbn, packetId, catalogTrackName);
20326
22554
  return;
20327
22555
  }
20328
- const ctrl = new AbortController();
20329
22556
  const key = requestKey(sbn, packetId, catalogTrackName);
20330
- const previous = inFlight.get(key);
20331
- previous?.controller.abort();
20332
- const request = { controller: ctrl, sbn, packetId, catalogTrackName };
20333
- inFlight.set(key, request);
20334
- const timeoutMs = timeoutFor(sbn, packetId, catalogTrackName);
20335
- const timer = setTimeout(() => ctrl.abort(), Math.max(1, timeoutMs));
20336
- void (async () => {
20337
- let fed = 0;
20338
- try {
20339
- while (!ctrl.signal.aborted) {
20340
- try {
20341
- for await (const packet of opts.transport(
20342
- target.repairTrack,
20343
- sbn,
20344
- packetId,
20345
- ctrl.signal
20346
- )) {
20347
- if (ctrl.signal.aborted) break;
20348
- if (inFlight.get(key) !== request) break;
20349
- fed++;
20350
- if (catalogTrackName === void 0) {
20351
- mc.processRepairFromMoQ(packet, packetId);
20352
- } else {
20353
- mc.processRepairFromMoQ(packet, packetId, catalogTrackName);
20354
- }
20355
- }
20356
- break;
20357
- } catch (err) {
20358
- if (fed > 0 || ctrl.signal.aborted || !opts.shouldRetry?.(err)) throw err;
20359
- await waitForRetry(ctrl.signal);
20360
- }
20361
- }
20362
- if (fed === 0) clearRepairIfOwner(key, request);
20363
- } catch (err) {
20364
- clearRepairIfOwner(key, request);
20365
- if (!ctrl.signal.aborted) {
20366
- console.warn(
20367
- `[RepairFetch] fetch failed pid=${packetId} sbn=${sbn} track=${target.repairTrack}:`,
20368
- err
20369
- );
20370
- }
20371
- } finally {
20372
- clearTimeout(timer);
20373
- if (inFlight.get(key) === request) inFlight.delete(key);
20374
- }
20375
- })();
22557
+ const previous = entries.get(key);
22558
+ if (previous) {
22559
+ retire(previous);
22560
+ stop(previous, "reset");
22561
+ }
22562
+ const identity = {
22563
+ target,
22564
+ sbn,
22565
+ packetId,
22566
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
22567
+ };
22568
+ const wire = wirePriority(identity, blockClass);
22569
+ if (wire === null) {
22570
+ clearRepair(sbn, packetId, catalogTrackName);
22571
+ return;
22572
+ }
22573
+ const budgetMs = mc.fecManager.repairFetchTimeoutMsForBlock(sbn, packetId, catalogTrackName);
22574
+ const entry = {
22575
+ key,
22576
+ ...identity,
22577
+ repairTrack: target.repairTrack,
22578
+ priority: repairPriorityForClass(blockClass),
22579
+ subscriberPriority: wire.subscriberPriority,
22580
+ deadlineAt: performance.now() + budgetMs,
22581
+ order: enqueueOrder++,
22582
+ attempts: 0,
22583
+ running: null
22584
+ };
22585
+ entries.set(key, entry);
22586
+ if (entry.priority < 2) preemptDeltas();
22587
+ dispatch();
20376
22588
  });
20377
22589
  return () => {
20378
22590
  disposed = true;
20379
22591
  removeResetObserver();
20380
- for (const request of inFlight.values()) {
20381
- clearRepair(request.sbn, request.packetId, request.catalogTrackName);
20382
- request.controller.abort();
22592
+ removeLifecycleObserver();
22593
+ for (const entry of [...entries.values()]) {
22594
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
22595
+ stop(entry, "disposed");
20383
22596
  }
20384
- inFlight.clear();
22597
+ entries.clear();
20385
22598
  };
20386
22599
  }
20387
22600
  export {
22601
+ AudioGapConcealer,
20388
22602
  AudioRingBuffer,
20389
22603
  AuthTag,
22604
+ BlockClassifier,
20390
22605
  CmafBlockAssembler,
20391
22606
  CmafGroupBatcher,
20392
22607
  CmcdProducer,
@@ -20397,6 +22612,7 @@ export {
20397
22612
  FEC_SBN_MAX,
20398
22613
  FecSourceInfo,
20399
22614
  FecStarvationDetector,
22615
+ HoldLastTimeline,
20400
22616
  JOIN_DEFER_WARN_MS,
20401
22617
  KEYFRAME_LOST_TIMEOUT_SLACK,
20402
22618
  LOCHeaderExtensionId,
@@ -20424,6 +22640,7 @@ export {
20424
22640
  REPAIR_TRACK_ONLY_KEYS,
20425
22641
  ReedSolomonCodec,
20426
22642
  RepairContractError,
22643
+ SOURCE_MEDIA_PRIORITY_MAX,
20427
22644
  SampleCombineError,
20428
22645
  SampleCombiner,
20429
22646
  SessionManager,
@@ -20442,6 +22659,7 @@ export {
20442
22659
  catalogAmtNetworkSource,
20443
22660
  catalogFecInterleaveMs,
20444
22661
  catalogGroupDurationMs,
22662
+ catalogRepairTarget,
20445
22663
  classifyH264Keyframe,
20446
22664
  classifyPacket,
20447
22665
  codecStringFromAvcC,
@@ -20452,11 +22670,13 @@ export {
20452
22670
  createFragment,
20453
22671
  createWasmMmtpContainerParser,
20454
22672
  datagramMfuReassembly,
22673
+ decideGap,
20455
22674
  decodeFecSourceInfo,
20456
22675
  decodeLocHeader,
20457
22676
  decodeLocTimestamp,
20458
22677
  decodeTimestamp,
20459
22678
  dependsTarget,
22679
+ deriveBlockClassifierGeometry,
20460
22680
  describeRepairTrack,
20461
22681
  detectH264Keyframe,
20462
22682
  driftCheck,
@@ -20475,7 +22695,6 @@ export {
20475
22695
  forwardRepairLifecycleEvents,
20476
22696
  frameSamplesFromInit,
20477
22697
  generateFallbackAvcC,
20478
- generateGreenFillNAL,
20479
22698
  generateHvcCFromParameterSets,
20480
22699
  generateSilenceFrame,
20481
22700
  getPacketType,
@@ -20499,6 +22718,7 @@ export {
20499
22718
  isSourcePacket,
20500
22719
  isTrackTimingConfig,
20501
22720
  joinedRepairSymbolCount,
22721
+ keyframeIntervalMediaTicks,
20502
22722
  mergeOverrideIntoCmsfTracks,
20503
22723
  mergeOverrideIntoHangRenditions,
20504
22724
  mfuReassemblyTimeoutMs,
@@ -20516,6 +22736,8 @@ export {
20516
22736
  rejectRepairTrackGeometry,
20517
22737
  reliableMoqMfuReassembly,
20518
22738
  removeEmulationPrevention,
22739
+ repairFetchSubscriberPriority,
22740
+ repairPriorityForClass,
20519
22741
  repairReachability,
20520
22742
  resolveCatalogTrackFec,
20521
22743
  resolveCatalogTrackGroupDurationMs,
@@ -20534,6 +22756,7 @@ export {
20534
22756
  validateMulticastContainerContract,
20535
22757
  validateRepairTrackFields,
20536
22758
  validateSwitchingSetTiming,
22759
+ videoConcealModeForCodec,
20537
22760
  wireRepairFetch,
20538
22761
  wrapAdtsFrame
20539
22762
  };