@blockcast/mmt-container 2.2.0-main.a88c3a0aa4f3 → 2.2.0-main.aee8d33d2cc8

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 (118) hide show
  1. package/README.md +34 -19
  2. package/dist/block-policy.d.ts +55 -13
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +104 -32
  5. package/dist/block-policy.js.map +2 -2
  6. package/dist/browser-runtime.js +2094 -385
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.js.map +2 -2
  9. package/dist/catalog-fec-params.d.ts +18 -2
  10. package/dist/catalog-fec-params.d.ts.map +1 -1
  11. package/dist/catalog-fec-params.js +29 -1
  12. package/dist/catalog-fec-params.js.map +2 -2
  13. package/dist/catalog-network-source.js.map +2 -2
  14. package/dist/cmaf-block-assembler.js +92 -1
  15. package/dist/cmaf-block-assembler.js.map +2 -2
  16. package/dist/cmcd-producer.d.ts +60 -47
  17. package/dist/cmcd-producer.d.ts.map +1 -1
  18. package/dist/cmcd-producer.js +138 -109
  19. package/dist/cmcd-producer.js.map +2 -2
  20. package/dist/codec-utils.d.ts.map +1 -1
  21. package/dist/codec-utils.js +92 -1
  22. package/dist/codec-utils.js.map +2 -2
  23. package/dist/delivery-catalog.js +26 -16
  24. package/dist/delivery-catalog.js.map +2 -2
  25. package/dist/delta-fallback-config.js +5 -1
  26. package/dist/delta-fallback-config.js.map +3 -3
  27. package/dist/fec-manager.d.ts +114 -15
  28. package/dist/fec-manager.d.ts.map +1 -1
  29. package/dist/fec-manager.js +639 -95
  30. package/dist/fec-manager.js.map +2 -2
  31. package/dist/fec-state.js +5 -1
  32. package/dist/fec-state.js.map +2 -2
  33. package/dist/fec-worker-setup.d.ts +1 -1
  34. package/dist/fec-worker-setup.js +1 -1
  35. package/dist/fec-worker-setup.js.map +2 -2
  36. package/dist/held-layer-admission.js.map +2 -2
  37. package/dist/index.d.ts +6 -5
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +12 -2
  40. package/dist/index.js.map +2 -2
  41. package/dist/iso-block-locator.d.ts +48 -13
  42. package/dist/iso-block-locator.d.ts.map +1 -1
  43. package/dist/iso-block-locator.js +97 -25
  44. package/dist/iso-block-locator.js.map +2 -2
  45. package/dist/iso-bmff-timing.d.ts +10 -1
  46. package/dist/iso-bmff-timing.d.ts.map +1 -1
  47. package/dist/iso-bmff-timing.js +36 -2
  48. package/dist/iso-bmff-timing.js.map +2 -2
  49. package/dist/media-router.js.map +1 -1
  50. package/dist/mfu-reassembler.js +12 -19
  51. package/dist/mfu-reassembler.js.map +2 -2
  52. package/dist/mmtp-container-parser.d.ts +106 -12
  53. package/dist/mmtp-container-parser.d.ts.map +1 -1
  54. package/dist/mmtp-container-parser.js +324 -46
  55. package/dist/mmtp-container-parser.js.map +2 -2
  56. package/dist/mmtp-container-parser.no-modules.js +466 -66
  57. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  58. package/dist/mmtp-decode-pipeline.js +323 -46
  59. package/dist/mmtp-decode-pipeline.js.map +2 -2
  60. package/dist/mmtp-fec-session.d.ts +41 -3
  61. package/dist/mmtp-fec-session.d.ts.map +1 -1
  62. package/dist/mmtp-fec-session.js +118 -13
  63. package/dist/mmtp-fec-session.js.map +3 -3
  64. package/dist/mmtp-router.d.ts +36 -8
  65. package/dist/mmtp-router.d.ts.map +1 -1
  66. package/dist/mmtp-router.js +716 -100
  67. package/dist/mmtp-router.js.map +3 -3
  68. package/dist/multicast-auth-catalog.js.map +2 -2
  69. package/dist/multicast-input.js.map +2 -2
  70. package/dist/multicast-manager.d.ts +28 -3
  71. package/dist/multicast-manager.d.ts.map +1 -1
  72. package/dist/multicast-manager.js +1451 -215
  73. package/dist/multicast-manager.js.map +3 -3
  74. package/dist/multicast-transport.js +28 -18
  75. package/dist/multicast-transport.js.map +2 -2
  76. package/dist/multicast-unwrap.js +12 -19
  77. package/dist/multicast-unwrap.js.map +2 -2
  78. package/dist/no-modules.d.ts +1 -0
  79. package/dist/no-modules.d.ts.map +1 -1
  80. package/dist/no-modules.js +463 -64
  81. package/dist/no-modules.js.map +4 -4
  82. package/dist/repair-fetch.d.ts +38 -8
  83. package/dist/repair-fetch.d.ts.map +1 -1
  84. package/dist/repair-fetch.js +286 -27
  85. package/dist/repair-fetch.js.map +3 -3
  86. package/dist/repair-layer-subscriptions.d.ts +82 -0
  87. package/dist/repair-layer-subscriptions.d.ts.map +1 -0
  88. package/dist/repair-layer-subscriptions.js +192 -0
  89. package/dist/repair-layer-subscriptions.js.map +7 -0
  90. package/dist/signaling.js.map +2 -2
  91. package/dist/timestamp-codec.js +12 -19
  92. package/dist/timestamp-codec.js.map +2 -2
  93. package/dist/track-session.d.ts +1 -1
  94. package/dist/track-session.d.ts.map +1 -1
  95. package/dist/track-session.js +1 -0
  96. package/dist/track-session.js.map +2 -2
  97. package/dist/wasm-mfu-reassembler.js.map +2 -2
  98. package/dist/wasm-mmtp-container-parser.js +323 -46
  99. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  100. package/package.json +8 -5
  101. package/schemas/catalog.schema.json +4 -0
  102. package/src/block-policy.ts +216 -52
  103. package/src/catalog-fec-params.ts +37 -1
  104. package/src/cmcd-producer.ts +189 -179
  105. package/src/codec-utils.ts +121 -1
  106. package/src/fec-manager.ts +619 -37
  107. package/src/fec-worker-setup.ts +2 -2
  108. package/src/index.ts +22 -2
  109. package/src/iso-block-locator.ts +133 -31
  110. package/src/iso-bmff-timing.ts +40 -1
  111. package/src/mmtp-container-parser.ts +353 -32
  112. package/src/mmtp-fec-session.ts +115 -15
  113. package/src/mmtp-router.ts +618 -44
  114. package/src/multicast-manager.ts +139 -16
  115. package/src/no-modules.ts +3 -0
  116. package/src/repair-fetch.ts +366 -50
  117. package/src/repair-layer-subscriptions.ts +261 -0
  118. package/src/track-session.ts +4 -1
@@ -489,6 +489,8 @@ var PACKET_TYPE_SIGNALING = 2;
489
489
  var PACKET_TYPE_REPAIR = 3;
490
490
  var MMTP_SIGNALING_PACKET_ID = 0;
491
491
  var MMTP_PACKET_ID_MAX = 65535;
492
+ var FEC_CODE_REED_SOLOMON = 1;
493
+ var FEC_CODE_RAPTORQ = 3;
492
494
  function parseMMTPHeader(buffer) {
493
495
  if (buffer.length < MMTP_HEADER_SIZE) {
494
496
  throw new Error(`MMTP packet too small: ${buffer.length} bytes`);
@@ -655,30 +657,26 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
655
657
  const authLength = view2.getUint16(2, false);
656
658
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
657
659
  }
658
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
660
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
659
661
  if (declaredEnd > payload.length)
660
662
  return null;
661
663
  if (options?.skipFecId) {
662
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
664
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
663
665
  }
664
- const overlay = options?.overlayDeclared === true && rapFlag;
665
666
  if (fecType === 1) {
666
- const fecStart = payload.length - sourceFecTrailerSize(overlay);
667
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
667
668
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
668
669
  return null;
669
670
  }
670
- return { hasFecId: true, hasOverlayFecId: overlay };
671
+ return { hasFecId: true };
671
672
  }
672
- if (fecType !== 0 || overlay)
673
+ if (fecType !== 0)
673
674
  return null;
674
675
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
675
- return { hasFecId: false, hasOverlayFecId: false };
676
+ return { hasFecId: false };
676
677
  }
677
678
  return null;
678
679
  }
679
- function sourceFecTrailerSize(overlay) {
680
- return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
681
- }
682
680
  function extractNALUnit(mmtpPacket) {
683
681
  const extraction = extractMFUPayload(mmtpPacket);
684
682
  if (!extraction)
@@ -737,11 +735,11 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
737
735
  if ("rejection" in layoutResult)
738
736
  return layoutResult;
739
737
  const { layout } = layoutResult;
740
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
738
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
741
739
  if (!trailerLayout) {
742
740
  if (!options?.skipFecId && header.fecType === 1) {
743
741
  const observed = payload.length - layout.dataEnd;
744
- const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
742
+ const expected = SOURCE_FEC_PAYLOAD_ID_SIZE;
745
743
  if (observed !== expected) {
746
744
  return {
747
745
  rejection: {
@@ -776,13 +774,10 @@ function extractPlannedMfu(mmtpPacket, result) {
776
774
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
777
775
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
778
776
  const data = payload.subarray(mfuOffset, dataEnd);
779
- const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
780
- const ssIdAt = (offset) => ({
781
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
782
- });
783
- const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
784
- const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
785
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
777
+ const fecPayloadId = trailerLayout.hasFecId ? {
778
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, 4).getUint32(0, false)
779
+ } : null;
780
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
786
781
  }
787
782
  function extractTimestamp(mmtpPacket) {
788
783
  const { header } = unwrapMMTP(mmtpPacket);
@@ -856,6 +851,17 @@ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
856
851
  dataOffset: off + REPAIR_FEC_PID_SIZE
857
852
  };
858
853
  }
854
+ function extractRepairFecPayloadId(mmtpPacket) {
855
+ const fields = readRepairFecPayloadIdFields(mmtpPacket);
856
+ if (!fields)
857
+ return null;
858
+ return {
859
+ ssStart: fields.ssStart,
860
+ rsbLength: fields.rsbLength,
861
+ rsId: fields.rsId,
862
+ ssbLength: fields.ssbLength
863
+ };
864
+ }
859
865
  function parseMoqRepairFrame(frame) {
860
866
  return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame));
861
867
  }
@@ -903,6 +909,50 @@ var NTP_SHORT_BITS = 32;
903
909
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
904
910
  var NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1);
905
911
 
912
+ // ../mmt-base/dist/signalling.js
913
+ var FEC_CODING_STRUCTURE_ONE_STAGE = 1;
914
+ var SSBG_MODE_1 = 1;
915
+ var RAPTORQ_MAX_SOURCE_SYMBOLS = 56403;
916
+ var REPAIR_SYMBOL_ID_MAX = 16777215;
917
+ var MIN_REPAIR_SYMBOL_SIZE = 14;
918
+ var REED_SOLOMON_MAX_BLOCK = 255;
919
+ function alFecRaptorQFlowConfig(flow) {
920
+ if (flow.fecCodingStructure !== FEC_CODING_STRUCTURE_ONE_STAGE || flow.repairFlows.length !== 1)
921
+ return null;
922
+ if (flow.ssbgMode !== SSBG_MODE_1 || flow.ffsrptsFlag !== 0 || flow.fecPayloadIdMode !== 0)
923
+ return null;
924
+ if (flow.packetIds.length !== 1)
925
+ return null;
926
+ const repair = flow.repairFlows[0];
927
+ const { fecCodeId, maximumK: k, maximumP: p } = repair;
928
+ const t = flow.repairSymbolSize;
929
+ if (t < MIN_REPAIR_SYMBOL_SIZE || k < 1 || p < 1 || k + p - 1 > REPAIR_SYMBOL_ID_MAX)
930
+ return null;
931
+ if (fecCodeId === FEC_CODE_RAPTORQ) {
932
+ if (t % 8 !== 0 || k > RAPTORQ_MAX_SOURCE_SYMBOLS)
933
+ return null;
934
+ } else if (fecCodeId === FEC_CODE_REED_SOLOMON) {
935
+ if (k + p > REED_SOLOMON_MAX_BLOCK)
936
+ return null;
937
+ } else {
938
+ return null;
939
+ }
940
+ if (repair.repairFlowId === MMTP_SIGNALING_PACKET_ID || repair.repairFlowId === flow.packetIds[0])
941
+ return null;
942
+ return {
943
+ sourcePacketIds: [...flow.packetIds],
944
+ repairFlowId: repair.repairFlowId,
945
+ fecCodeId,
946
+ ssbgMode: flow.ssbgMode,
947
+ fecPayloadIdMode: flow.fecPayloadIdMode,
948
+ repairSymbolSize: t,
949
+ maximumK: k,
950
+ maximumP: p,
951
+ protectionWindowTime: repair.protectionWindowTime,
952
+ protectionWindowSize: repair.protectionWindowSize
953
+ };
954
+ }
955
+
906
956
  // ../mmt-base/dist/serial-number.js
907
957
  var SERIAL32_SPAN = 4294967296;
908
958
  var SERIAL32_HALF = 2147483648;
@@ -1747,13 +1797,25 @@ function fecCatalogTracks(catalog) {
1747
1797
  });
1748
1798
  return { tracks, pointers };
1749
1799
  }
1750
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1800
+ function runtimeView(catalog, receiver) {
1751
1801
  const { tracks, pointers } = fecCatalogTracks(catalog);
1752
1802
  const report = validateFecCatalog({ tracks }, receiver);
1753
1803
  const at2 = (path) => {
1754
1804
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
1755
1805
  return m ? pointers[Number(m[1])] + m[2] : path;
1756
1806
  };
1807
+ return { tracks, pointers, report, at: at2 };
1808
+ }
1809
+ function runtimeFecCatalogReport(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1810
+ const { report, at: at2 } = runtimeView(catalog, receiver);
1811
+ const issue = (i) => Object.freeze({ code: i.code, path: at2(i.path) });
1812
+ return Object.freeze({
1813
+ instances: Object.freeze(report.instances.map((i) => Object.freeze({ ...i, path: at2(i.path), issues: Object.freeze(i.issues.map(issue)) }))),
1814
+ issues: Object.freeze(report.issues.map(issue))
1815
+ });
1816
+ }
1817
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
1818
+ const { tracks, pointers, report, at: at2 } = runtimeView(catalog, receiver);
1757
1819
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
1758
1820
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
1759
1821
  const why = (i) => Object.freeze({
@@ -6049,9 +6111,10 @@ function isH264IntraSlice(nal) {
6049
6111
  const sliceType = readH264SliceType(nal);
6050
6112
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
6051
6113
  }
6114
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
6052
6115
  function readH264SliceType(nal) {
6053
6116
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6054
- const rbsp = removeEmulationPrevention(nal.subarray(1));
6117
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
6055
6118
  const state = { bitOffset: 0 };
6056
6119
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6057
6120
  return readUnsignedExpGolomb(rbsp, state);
@@ -6420,6 +6483,96 @@ if (void 0) {
6420
6483
  ]))).toBe(false);
6421
6484
  });
6422
6485
  });
6486
+ describe("readH264SliceType", () => {
6487
+ const wholeNalSliceType = (nal) => {
6488
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
6489
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
6490
+ const state = { bitOffset: 0 };
6491
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
6492
+ return readUnsignedExpGolomb(rbsp, state);
6493
+ };
6494
+ const hex3 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
6495
+ const ue = (value) => {
6496
+ const code = (value + 1).toString(2);
6497
+ return "0".repeat(code.length - 1) + code;
6498
+ };
6499
+ const sliceNal = (bits) => {
6500
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
6501
+ const nal = [1];
6502
+ let zeros = 0;
6503
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
6504
+ if (zeros >= 2 && byte <= 3) {
6505
+ nal.push(3);
6506
+ zeros = 0;
6507
+ }
6508
+ nal.push(byte);
6509
+ zeros = byte === 0 ? zeros + 1 : 0;
6510
+ }
6511
+ return Uint8Array.from(nal);
6512
+ };
6513
+ const x264Slices = [
6514
+ ["64x48 P", hex3("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
6515
+ ["64x48 B", hex3("419e414212fffeeade283707cb70f7"), 6, false],
6516
+ ["64x48 non-IDR I", hex3(
6517
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
6518
+ ), 7, true],
6519
+ ["1280x720 B, escape at byte 10", hex3(
6520
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
6521
+ ), 6, false],
6522
+ ["1280x720 P, escape at byte 15", hex3(
6523
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
6524
+ ), 5, false],
6525
+ ["1280x720 B, escape at byte 22", hex3("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
6526
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex3(
6527
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
6528
+ ), null, true],
6529
+ ["7680x4320 P, first_mb_in_slice 32640", hex3(
6530
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
6531
+ ), 5, false],
6532
+ ["7680x4320 P, first_mb_in_slice 97440", hex3(
6533
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
6534
+ ), 5, false]
6535
+ ];
6536
+ const syntheticSlices = [
6537
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
6538
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
6539
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
6540
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
6541
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
6542
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
6543
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
6544
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
6545
+ ];
6546
+ test("reads the slice_type of real and synthetic slices", () => {
6547
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
6548
+ expect(readH264SliceType(nal), name).toBe(sliceType);
6549
+ }
6550
+ });
6551
+ test("matches the whole-NAL unescape at every truncation", () => {
6552
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
6553
+ for (let end = 0; end <= nal.length; end++) {
6554
+ const cut = nal.subarray(0, end);
6555
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
6556
+ }
6557
+ }
6558
+ });
6559
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
6560
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
6561
+ let seed = 1;
6562
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
6563
+ for (let i = 0; i < 5e3; i++) {
6564
+ const nal = new Uint8Array(2 + next() % 63);
6565
+ nal[0] = 65;
6566
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
6567
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
6568
+ }
6569
+ });
6570
+ test("classifies the x264 slices as keyframes or not", () => {
6571
+ for (const [name, nal, , keyframe] of x264Slices) {
6572
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
6573
+ }
6574
+ });
6575
+ });
6423
6576
  describe("avccToAnnexB", () => {
6424
6577
  test("converts with SPS/PPS on keyframe", () => {
6425
6578
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -7949,8 +8102,8 @@ var MulticastSubscriptionPool = class {
7949
8102
  record.claims--;
7950
8103
  return this.acquire(gateway, config, consumer);
7951
8104
  }
7952
- const token = Symbol(key);
7953
- entry.consumers.set(token, consumer);
8105
+ const token2 = Symbol(key);
8106
+ entry.consumers.set(token2, consumer);
7954
8107
  let released = false;
7955
8108
  return {
7956
8109
  key,
@@ -7958,7 +8111,7 @@ var MulticastSubscriptionPool = class {
7958
8111
  if (released)
7959
8112
  return;
7960
8113
  released = true;
7961
- entry.consumers.delete(token);
8114
+ entry.consumers.delete(token2);
7962
8115
  record.claims--;
7963
8116
  if (record.claims > 0)
7964
8117
  return;
@@ -8586,9 +8739,9 @@ async function openSubscription(rx, openedPromise, options, packetIds) {
8586
8739
  } catch (error) {
8587
8740
  throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
8588
8741
  }
8589
- if (rx.integrityScheme !== INTEGRITY_SCHEME) {
8742
+ if (opened.integrityScheme !== INTEGRITY_SCHEME) {
8590
8743
  await rx.close();
8591
- throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8744
+ throw unsupported(`integrity scheme ${String(opened.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
8592
8745
  }
8593
8746
  const events = new EventTarget();
8594
8747
  let state = "connected";
@@ -8707,14 +8860,15 @@ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
8707
8860
  });
8708
8861
 
8709
8862
  // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
8863
+ var MAX_PENDING_PACKETS = 256;
8710
8864
  var AMTGatewayManager = class {
8711
8865
  subscriptions = /* @__PURE__ */ new Map();
8712
8866
  messageHandler;
8867
+ messageListenerRegistered = false;
8713
8868
  pendingPackets = /* @__PURE__ */ new Map();
8714
8869
  constructor() {
8715
8870
  this.messageHandler = (event) => {
8716
8871
  const data = event.data;
8717
- console.log(`[AMT] SW message received:`, data.type);
8718
8872
  if (data.type === "UDP_PACKET") {
8719
8873
  this.handlePacket(data);
8720
8874
  } else if (data.type === "SOCKET_ERROR") {
@@ -8723,12 +8877,22 @@ var AMTGatewayManager = class {
8723
8877
  console.log(`[AMT SW Debug] ${data.message}`);
8724
8878
  }
8725
8879
  };
8726
- if (typeof navigator !== "undefined" && navigator.serviceWorker) {
8727
- navigator.serviceWorker.addEventListener("message", this.messageHandler);
8728
- console.log("[AMT] Registered service worker message handler");
8729
- } else {
8730
- console.warn("[AMT] Service worker not available");
8880
+ }
8881
+ ensureMessageListener() {
8882
+ if (this.messageListenerRegistered || typeof navigator === "undefined" || !navigator.serviceWorker || !this.messageHandler) {
8883
+ return;
8731
8884
  }
8885
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
8886
+ this.messageListenerRegistered = true;
8887
+ console.log("[AMT] Registered service worker message handler");
8888
+ }
8889
+ removeMessageListener() {
8890
+ if (!this.messageListenerRegistered)
8891
+ return;
8892
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
8893
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
8894
+ }
8895
+ this.messageListenerRegistered = false;
8732
8896
  }
8733
8897
  /**
8734
8898
  * Subscribe via AMT tunnel
@@ -8738,6 +8902,7 @@ var AMTGatewayManager = class {
8738
8902
  if (config.protected) {
8739
8903
  throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
8740
8904
  }
8905
+ this.ensureMessageListener();
8741
8906
  const keyStr = this.getKeyString(key);
8742
8907
  if (this.subscriptions.has(keyStr)) {
8743
8908
  console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
@@ -8773,6 +8938,8 @@ var AMTGatewayManager = class {
8773
8938
  this.subscriptions.delete(keyStr);
8774
8939
  this.pendingPackets.delete(subscription.subscriptionId);
8775
8940
  }
8941
+ if (this.subscriptions.size === 0)
8942
+ this.removeMessageListener();
8776
8943
  throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
8777
8944
  }
8778
8945
  }
@@ -8794,6 +8961,8 @@ var AMTGatewayManager = class {
8794
8961
  } finally {
8795
8962
  this.subscriptions.delete(handle);
8796
8963
  this.pendingPackets.delete(subscription.subscriptionId);
8964
+ if (this.subscriptions.size === 0)
8965
+ this.removeMessageListener();
8797
8966
  }
8798
8967
  }
8799
8968
  /**
@@ -8810,14 +8979,12 @@ var AMTGatewayManager = class {
8810
8979
  if (!subscriptionId)
8811
8980
  return;
8812
8981
  const subscription = this.subscriptions.get(subscriptionId);
8813
- if (!subscription) {
8814
- console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
8982
+ if (!subscription)
8815
8983
  return;
8816
- }
8817
8984
  if (!subscription.handshakeComplete) {
8818
8985
  const queue = this.pendingPackets.get(subscriptionId);
8819
8986
  const packetData2 = data;
8820
- if (queue) {
8987
+ if (queue && queue.length < MAX_PENDING_PACKETS) {
8821
8988
  queue.push({
8822
8989
  data: packetData2.data,
8823
8990
  remoteAddress: packetData2.remoteAddress,
@@ -8843,19 +9010,15 @@ var AMTGatewayManager = class {
8843
9010
  if (!subscriptionId)
8844
9011
  return;
8845
9012
  const subscription = this.subscriptions.get(subscriptionId);
8846
- if (!subscription) {
8847
- console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
9013
+ if (!subscription)
8848
9014
  return;
8849
- }
8850
9015
  subscription.config.onError(new Error(error || "Unknown error"));
8851
9016
  }
8852
9017
  /**
8853
9018
  * Cleanup on destroy
8854
9019
  */
8855
9020
  destroy() {
8856
- if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
8857
- navigator.serviceWorker.removeEventListener("message", this.messageHandler);
8858
- }
9021
+ this.removeMessageListener();
8859
9022
  const handles = Array.from(this.subscriptions.keys());
8860
9023
  for (const handle of handles) {
8861
9024
  this.unsubscribe(handle).catch((err) => {
@@ -12386,6 +12549,7 @@ var TrackSession = class {
12386
12549
  this.#state = "idle";
12387
12550
  this.#subscription = null;
12388
12551
  this.#disarmFec();
12552
+ this.#unsuppress();
12389
12553
  }
12390
12554
  // -----------------------------------------------------------------------
12391
12555
  // Internal
@@ -12879,6 +13043,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
12879
13043
  this.#heldEvicted = 0;
12880
13044
  /** Pending holes (see `deferIncompleteGaps`): unstated, sources still held. */
12881
13045
  this.#holes = [];
13046
+ /** Holes the horizon passed while pending: sources held until closed. */
13047
+ this.#expired = [];
13048
+ /** Of `#expired`, those `takeExpiredHoles` has not handed out yet. */
13049
+ this.#newlyExpired = [];
13050
+ /**
13051
+ * Spans closed from expired holes: behind the horizon, so kept only for
13052
+ * `locate` while their sources are fed, until the next retirement.
13053
+ */
13054
+ this.#closedBehind = [];
12882
13055
  /**
12883
13056
  * Keep a gap that is missing a source as a pending hole rather than a span,
12884
13057
  * so a repair FETCHed for it (draft-ramadan-moq-fec §7.5) can still state
@@ -12900,7 +13073,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
12900
13073
  #retentionBlocks;
12901
13074
  #heldEvicted;
12902
13075
  #newest;
13076
+ #newestSource;
12903
13077
  #holes;
13078
+ #expired;
13079
+ #newlyExpired;
13080
+ #closedBehind;
12904
13081
  static #checkedRetention(retentionBlocks) {
12905
13082
  if (!Number.isSafeInteger(retentionBlocks) || retentionBlocks <= 0) {
12906
13083
  throw new Error(
@@ -12937,6 +13114,21 @@ var IsoBlockLocator = class _IsoBlockLocator {
12937
13114
  observe(position) {
12938
13115
  if (this.#newest === void 0 || serial32Precedes(this.#newest, position)) this.#newest = position;
12939
13116
  }
13117
+ /**
13118
+ * The newest source SS_ID noted with `noteSource` (RFC 1982 order). Unlike
13119
+ * `newest`, a repair never moves it: a repair can run ahead of its sources,
13120
+ * a source cannot run ahead of the sources sent before it except by
13121
+ * reordering.
13122
+ */
13123
+ get newestSource() {
13124
+ return this.#newestSource;
13125
+ }
13126
+ /** Note a received source's SS_ID; true when it is the newest one yet. */
13127
+ noteSource(ssId) {
13128
+ if (this.#newestSource !== void 0 && !serial32Precedes(this.#newestSource, ssId)) return false;
13129
+ this.#newestSource = ssId;
13130
+ return true;
13131
+ }
12940
13132
  /** Held sources evicted by `heldCapacity` (never by the horizon itself). */
12941
13133
  get heldEvicted() {
12942
13134
  return this.#heldEvicted;
@@ -12955,17 +13147,29 @@ var IsoBlockLocator = class _IsoBlockLocator {
12955
13147
  }
12956
13148
  /** The known block or span containing `ssId`, with its ESI. */
12957
13149
  locate(ssId) {
12958
- for (let i = this.#blocks.length - 1; i >= 0; i--) {
12959
- const block = this.#blocks[i];
12960
- if (isoBlockContains(block.start, block.length, ssId)) {
12961
- return { block, esi: serial32Distance(block.start, ssId) };
13150
+ for (const blocks of [this.#blocks, this.#closedBehind]) {
13151
+ for (let i = blocks.length - 1; i >= 0; i--) {
13152
+ const block = blocks[i];
13153
+ if (isoBlockContains(block.start, block.length, ssId)) {
13154
+ return { block, esi: serial32Distance(block.start, ssId) };
13155
+ }
12962
13156
  }
12963
13157
  }
12964
13158
  return null;
12965
13159
  }
12966
- /** Number of pending holes. */
13160
+ /** Number of holes not closed yet, pending or past the horizon. */
12967
13161
  get holeCount() {
12968
- return this.#holes.length;
13162
+ return this.#holes.length + this.#expired.length;
13163
+ }
13164
+ /**
13165
+ * The pending holes the horizon has passed since the last call, in the
13166
+ * order it passed them. Each is no longer pending: no repair states a block
13167
+ * in it (that repair is `stale`, as for a span the horizon retired) and the
13168
+ * release gate does not wait for it. Its owner must close it
13169
+ * (`closeHolesWithin`), which turns it into a span that is not kept here.
13170
+ */
13171
+ takeExpiredHoles() {
13172
+ return this.#newlyExpired.splice(0);
12969
13173
  }
12970
13174
  /** The stated block (never a span) ending exactly at `end`. */
12971
13175
  blockEndingAt(end) {
@@ -13021,9 +13225,11 @@ var IsoBlockLocator = class _IsoBlockLocator {
13021
13225
  /**
13022
13226
  * Apply one repair symbol's `(SS_Start, SSB_length)`. The first repair of a
13023
13227
  * block states its range and places every held source in it; later repair
13024
- * symbols of the same block change nothing. A range that contradicts a
13025
- * known block (a different length, or an overlap with another block or a
13026
- * span) fails closed: the repair symbol is dropped and no block changes.
13228
+ * symbols of the same block change nothing. A repair whose range is exactly
13229
+ * a repair-less span states that span's one block. A range that contradicts
13230
+ * a known block (a different length, or an overlap with another block or
13231
+ * with part of a span) fails closed: the repair symbol is dropped and no
13232
+ * block changes.
13027
13233
  * A newly stated block retires behind its SS_Start (see the class note).
13028
13234
  * A block so far past `newest` that stating it would retire the position
13029
13235
  * `newest` is refused as `ahead`. When `newest` is a placed block's SS_Start
@@ -13042,7 +13248,16 @@ var IsoBlockLocator = class _IsoBlockLocator {
13042
13248
  const known = this.blockAt(start);
13043
13249
  if (known !== void 0) {
13044
13250
  if (known.span) {
13045
- return { status: "overlap", reason: `repair block ${start}+${length} falls inside a repair-less span` };
13251
+ if (known.length === length) {
13252
+ const block2 = { start, length, span: false };
13253
+ this.#blocks[this.#blocks.indexOf(known)] = block2;
13254
+ return { status: "placed", block: block2, placed: [] };
13255
+ }
13256
+ return length < known.length ? {
13257
+ status: "overlap",
13258
+ reason: `repair block ${start}+${length} is only the first block of repair-less span ${known.start}+${known.length}`,
13259
+ ofSpan: known
13260
+ } : { status: "overlap", reason: `repair block ${start}+${length} runs past repair-less span ${known.start}+${known.length}` };
13046
13261
  }
13047
13262
  if (known.length !== length) {
13048
13263
  return {
@@ -13110,18 +13325,28 @@ var IsoBlockLocator = class _IsoBlockLocator {
13110
13325
  return span === void 0 ? { status: "placed", block, placed } : { status: "placed", block, placed, span };
13111
13326
  }
13112
13327
  /**
13113
- * Turn every pending hole inside `[start, start + length)` into a
13114
- * repair-less span, claiming its held sources: its range FETCH ended, so
13115
- * nothing more will state its blocks. Returns the spans, in SS_ID order.
13328
+ * Turn every hole inside `[start, start + length)` into a repair-less span,
13329
+ * claiming its held sources: its range FETCH ended, so nothing more will
13330
+ * state its blocks. A hole the horizon passed (`takeExpiredHoles`) leaves a
13331
+ * span that is not kept among the blocks, as the horizon would retire it at
13332
+ * once; only `locate` finds it, until the next retirement, so its sources
13333
+ * can be fed. Returns the spans, in SS_ID order.
13116
13334
  */
13117
13335
  closeHolesWithin(start, length) {
13118
13336
  const closed = [];
13119
- for (const hole of [...this.#holes]) {
13120
- if (!isoBlockContains(start, length, hole.start)) continue;
13121
- this.#holes.splice(this.#holes.indexOf(hole), 1);
13122
- const spanBlock = { start: hole.start, length: hole.length, span: true };
13123
- closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13124
- this.#blocks.push(spanBlock);
13337
+ for (const holes of [this.#holes, this.#expired]) {
13338
+ for (const hole of [...holes]) {
13339
+ if (!isoBlockContains(start, length, hole.start)) continue;
13340
+ holes.splice(holes.indexOf(hole), 1);
13341
+ const spanBlock = { start: hole.start, length: hole.length, span: true };
13342
+ closed.push({ block: spanBlock, placed: this.#claim(spanBlock) });
13343
+ if (holes === this.#holes) {
13344
+ this.#blocks.push(spanBlock);
13345
+ } else {
13346
+ this.#closedBehind.push(spanBlock);
13347
+ if (this.#newlyExpired.includes(hole)) this.#newlyExpired.splice(this.#newlyExpired.indexOf(hole), 1);
13348
+ }
13349
+ }
13125
13350
  }
13126
13351
  return closed.sort((x, y) => serial32Distance(start, x.block.start) - serial32Distance(start, y.block.start));
13127
13352
  }
@@ -13135,15 +13360,17 @@ var IsoBlockLocator = class _IsoBlockLocator {
13135
13360
  return void 0;
13136
13361
  }
13137
13362
  /**
13138
- * Retire every block and span whose last SS_ID, and every held source,
13139
- * lies more than `retentionBlocks` blocks behind `position`, with the shared
13140
- * lower-bound metric (`isoBlocksBehindLowerBound`) every ISO interleave
13141
- * horizon uses. Returns the retired block starts.
13363
+ * Retire every block and span whose last SS_ID, and every held source
13364
+ * outside a hole, lies more than `retentionBlocks` blocks behind
13365
+ * `position`, with the shared lower-bound metric (`isoBlocksBehindLowerBound`)
13366
+ * every ISO interleave horizon uses; a pending hole so far behind expires
13367
+ * (`takeExpiredHoles`). Returns the retired block starts.
13142
13368
  */
13143
13369
  retireBehind(position) {
13144
13370
  this.observe(position);
13145
13371
  const horizon = this.#retentionBlocks;
13146
13372
  const retired = [];
13373
+ this.#closedBehind.length = 0;
13147
13374
  for (let i = this.#blocks.length - 1; i >= 0; i--) {
13148
13375
  const block = this.#blocks[i];
13149
13376
  const last = serial32Add(block.start, block.length - 1);
@@ -13155,10 +13382,15 @@ var IsoBlockLocator = class _IsoBlockLocator {
13155
13382
  for (let i = this.#holes.length - 1; i >= 0; i--) {
13156
13383
  const hole = this.#holes[i];
13157
13384
  const last = serial32Add(hole.start, hole.length - 1);
13158
- if (isoBlocksBehindLowerBound(last, position, this.#kMax) > horizon) this.#holes.splice(i, 1);
13385
+ if (isoBlocksBehindLowerBound(last, position, this.#kMax) <= horizon) continue;
13386
+ this.#holes.splice(i, 1);
13387
+ this.#expired.push(hole);
13388
+ this.#newlyExpired.push(hole);
13159
13389
  }
13160
13390
  for (const ssId of [...this.#held.keys()]) {
13161
- if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon) this.#held.delete(ssId);
13391
+ if (isoBlocksBehindLowerBound(ssId, position, this.#kMax) > horizon && !this.#holes.some((hole) => isoBlockContains(hole.start, hole.length, ssId)) && !this.#expired.some((hole) => isoBlockContains(hole.start, hole.length, ssId))) {
13392
+ this.#held.delete(ssId);
13393
+ }
13162
13394
  }
13163
13395
  return retired;
13164
13396
  }
@@ -13166,9 +13398,13 @@ var IsoBlockLocator = class _IsoBlockLocator {
13166
13398
  reset() {
13167
13399
  this.#blocks.length = 0;
13168
13400
  this.#holes.length = 0;
13401
+ this.#expired.length = 0;
13402
+ this.#newlyExpired.length = 0;
13403
+ this.#closedBehind.length = 0;
13169
13404
  this.#held.clear();
13170
13405
  this.#coverageEnd = void 0;
13171
13406
  this.#newest = void 0;
13407
+ this.#newestSource = void 0;
13172
13408
  }
13173
13409
  #claim(block) {
13174
13410
  const placed = [];
@@ -13307,8 +13543,9 @@ function keyframeIntervalMediaTicks(geometry2, mediaTimescale) {
13307
13543
  return scaled / divisor;
13308
13544
  }
13309
13545
  function compareDataUnitStarts(a, b) {
13310
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset;
13546
+ return a.movieFragment - b.movieFragment | 0 || a.idx - b.idx || a.offset - b.offset;
13311
13547
  }
13548
+ var UNPLACED = { rapNotMpuStart: false };
13312
13549
  var BlockClassifier = class {
13313
13550
  #geometry;
13314
13551
  #mode;
@@ -13331,8 +13568,23 @@ var BlockClassifier = class {
13331
13568
  #mpuSbnSpans = /* @__PURE__ */ new Map();
13332
13569
  #dataUnitStarts = /* @__PURE__ */ new Map();
13333
13570
  #highestMpu = null;
13334
- /** MPU → movie_fragment_sequence_number observed in it. */
13335
- #mpuFragments = /* @__PURE__ */ new Map();
13571
+ /**
13572
+ * P3 layout, kept for the MPUs within the classification horizon and valid
13573
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
13574
+ */
13575
+ #mpus = /* @__PURE__ */ new Map();
13576
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
13577
+ #fragmentPerFrame = false;
13578
+ /** A DU header of this sequence stated sample_number above 1. */
13579
+ #multiSampleFragment = false;
13580
+ /**
13581
+ * The anchor received last, whether or not its MPU is still in the
13582
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
13583
+ * checked against it.
13584
+ */
13585
+ #lastAnchor = null;
13586
+ /** Two anchors were exactly G fragments per MPU apart. */
13587
+ #fragmentsProven = false;
13336
13588
  #lastRap = null;
13337
13589
  constructor(geometry2) {
13338
13590
  this.#geometry = geometry2;
@@ -13362,7 +13614,7 @@ var BlockClassifier = class {
13362
13614
  this.#geometry = geometry2;
13363
13615
  this.#blocks.clear();
13364
13616
  this.#clearContiguityLedger();
13365
- this.#mpuFragments.clear();
13617
+ this.#clearMpuLayout();
13366
13618
  this.#lastRap = null;
13367
13619
  this.#mpuBoundsRaps = true;
13368
13620
  if (geometry2.trackKind === "video" && geometry2.mode === "all-protected") {
@@ -13396,11 +13648,13 @@ var BlockClassifier = class {
13396
13648
  /**
13397
13649
  * The stream's SBN sequence restarted (FECManager source discontinuity:
13398
13650
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
13399
- * order are comparable only within one continuous sequence, so the P1
13400
- * ledger starts again.
13651
+ * order are comparable only within one continuous sequence, and a
13652
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
13653
+ * ledger and the P3 layout start again.
13401
13654
  */
13402
13655
  noteSourceDiscontinuity() {
13403
13656
  this.#clearContiguityLedger();
13657
+ this.#clearMpuLayout();
13404
13658
  }
13405
13659
  /** Register a block that exists without evidence (a vanished block). */
13406
13660
  touch(sbn) {
@@ -13419,16 +13673,16 @@ var BlockClassifier = class {
13419
13673
  if (this.#geometry.trackKind === "audio") return [];
13420
13674
  const changes = [];
13421
13675
  const block = this.#blockFor(sbn);
13676
+ const placement = this.#place(evidence);
13422
13677
  if (evidence.rap) block.rapSeen = true;
13423
13678
  if (evidence.mpu !== void 0) block.mpus.add(evidence.mpu);
13424
- if (evidence.idx !== void 0) {
13425
- block.idxMin = block.idxMin === void 0 ? evidence.idx : Math.min(block.idxMin, evidence.idx);
13426
- block.idxMax = block.idxMax === void 0 ? evidence.idx : Math.max(block.idxMax, evidence.idx);
13679
+ const { position } = placement;
13680
+ if (position !== void 0) {
13681
+ block.positionMin = block.positionMin === void 0 ? position : Math.min(block.positionMin, position);
13682
+ block.positionMax = block.positionMax === void 0 ? position : Math.max(block.positionMax, position);
13427
13683
  }
13428
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13429
- this.#mpuBoundsRaps = false;
13430
- }
13431
- const violation = this.#checkInvariants(sbn, block, evidence);
13684
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false;
13685
+ const violation = this.#checkInvariants(sbn, block, evidence, placement);
13432
13686
  if (violation !== null) changes.push(...this.#disable(violation));
13433
13687
  const next = this.#classify(block);
13434
13688
  if (next !== block.cls && this.#allowed(block.cls, next)) {
@@ -13481,35 +13735,89 @@ var BlockClassifier = class {
13481
13735
  }
13482
13736
  return block;
13483
13737
  }
13484
- #checkInvariants(sbn, block, evidence) {
13738
+ #checkInvariants(sbn, block, evidence, placement) {
13485
13739
  if (this.#mode === "all-protected" || this.#geometry.trackKind !== "video") return null;
13486
13740
  const geometry2 = this.#geometry;
13487
13741
  if (geometry2.mode !== "classifying") return null;
13488
- if (evidence.rap && evidence.idx !== void 0 && evidence.idx !== 0) {
13489
- return "rap-not-mpu-start";
13490
- }
13491
- if (evidence.idx !== void 0 && evidence.idx >= geometry2.gopFrames) {
13742
+ if (placement.rapNotMpuStart) return "rap-not-mpu-start";
13743
+ if (placement.position !== void 0 && placement.position >= geometry2.gopFrames) {
13492
13744
  return "mpu-longer-than-gop";
13493
13745
  }
13494
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0 && block.idxMax - block.idxMin >= geometry2.interleaveUnits) {
13746
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0 && block.positionMax - block.positionMin >= geometry2.interleaveUnits) {
13495
13747
  return "block-wider-than-interleave";
13496
13748
  }
13497
- if (evidence.mpu !== void 0 && evidence.movieFragment !== void 0) {
13498
- const fragment = this.#mpuFragments.get(evidence.mpu);
13499
- if (fragment === void 0) {
13500
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment);
13501
- for (const mpu of this.#mpuFragments.keys()) {
13502
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu);
13503
- }
13504
- } else if (fragment !== evidence.movieFragment) {
13505
- return "mpu-multiple-fragments";
13506
- }
13507
- }
13749
+ if (placement.violation !== void 0) return placement.violation;
13508
13750
  if (evidence.mpu !== void 0 && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
13509
13751
  return "block-not-contiguous";
13510
13752
  }
13511
13753
  return null;
13512
13754
  }
13755
+ /**
13756
+ * The MPU position a source symbol's DU header proves (P3), and what it
13757
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
13758
+ */
13759
+ #place(evidence) {
13760
+ const { mpu, idx, movieFragment: fragment } = evidence;
13761
+ if (idx === void 0) return UNPLACED;
13762
+ const bySample = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 };
13763
+ if (mpu === void 0 || fragment === void 0) {
13764
+ return this.#fragmentPerFrame && !this.#multiSampleFragment ? { rapNotMpuStart: bySample.rapNotMpuStart } : bySample;
13765
+ }
13766
+ let layout = this.#mpus.get(mpu);
13767
+ if (layout === void 0) {
13768
+ layout = { low: fragment };
13769
+ this.#mpus.set(mpu, layout);
13770
+ for (const other of this.#mpus.keys()) {
13771
+ if (other + 1 < mpu) this.#mpus.delete(other);
13772
+ }
13773
+ } else if (fragment !== layout.low) {
13774
+ this.#fragmentPerFrame = true;
13775
+ if ((fragment - layout.low | 0) < 0) layout.low = fragment;
13776
+ }
13777
+ if (idx !== 0) this.#multiSampleFragment = true;
13778
+ let arrival;
13779
+ if (evidence.rap && layout.anchor === void 0) {
13780
+ layout.anchor = fragment;
13781
+ arrival = this.#anchorDrift(mpu, fragment);
13782
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true;
13783
+ this.#lastAnchor = { mpu, fragment };
13784
+ }
13785
+ if (!this.#fragmentPerFrame) return bySample;
13786
+ if (this.#multiSampleFragment) return { ...bySample, violation: "mpu-multiple-fragments" };
13787
+ const { anchor } = layout;
13788
+ if (anchor === void 0) return UNPLACED;
13789
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor);
13790
+ const offset = fragment - anchor | 0;
13791
+ return {
13792
+ ...offset === 0 || offset > 0 && this.#fragmentsProven ? { position: offset } : {},
13793
+ rapNotMpuStart: evidence.rap && offset !== 0 || (layout.low - anchor | 0) < 0 || // Fragments count frames: an anchor arriving past the spacing is a
13794
+ // RAP inside its MPU, or an earlier MPU outran G.
13795
+ arrival !== void 0 && arrival > 0 && this.#fragmentsProven,
13796
+ ...drift === void 0 || drift === 0 ? {} : { violation: "rap-spacing-mismatch" }
13797
+ };
13798
+ }
13799
+ /**
13800
+ * How many fragments MPU m's anchor `fragment` lies past the start that
13801
+ * the anchor received last predicts for MPU m: one frame per fragment and
13802
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
13803
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
13804
+ * cadence, or this layout.
13805
+ */
13806
+ #anchorDrift(mpu, fragment) {
13807
+ const geometry2 = this.#geometry;
13808
+ const last = this.#lastAnchor;
13809
+ if (last === null || !this.#fragmentPerFrame || this.#multiSampleFragment || geometry2.trackKind !== "video" || geometry2.mode !== "classifying") {
13810
+ return void 0;
13811
+ }
13812
+ return fragment - last.fragment - geometry2.gopFrames * (mpu - last.mpu) | 0;
13813
+ }
13814
+ #clearMpuLayout() {
13815
+ this.#mpus.clear();
13816
+ this.#fragmentPerFrame = false;
13817
+ this.#multiSampleFragment = false;
13818
+ this.#lastAnchor = null;
13819
+ this.#fragmentsProven = false;
13820
+ }
13513
13821
  #clearContiguityLedger() {
13514
13822
  this.#mpuSbnSpans.clear();
13515
13823
  this.#dataUnitStarts.clear();
@@ -13609,9 +13917,9 @@ var BlockClassifier = class {
13609
13917
  if (this.#mode === "all-protected") return "unknown";
13610
13918
  const geometry2 = this.#geometry;
13611
13919
  if (geometry2.trackKind !== "video" || geometry2.mode !== "classifying") return "unknown";
13612
- if (block.mpus.size === 1 && block.idxMin !== void 0 && block.idxMax !== void 0) {
13920
+ if (block.mpus.size === 1 && block.positionMin !== void 0 && block.positionMax !== void 0) {
13613
13921
  const span = geometry2.interleaveUnits - 1;
13614
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry2.gopFrames - 1) {
13922
+ if (block.positionMax - span >= 1 && block.positionMin + span <= geometry2.gopFrames - 1) {
13615
13923
  return "delta";
13616
13924
  }
13617
13925
  }
@@ -13788,6 +14096,7 @@ var WORKER_ERROR_LOG_CAP = 5;
13788
14096
  var WORKER_ERROR_KIND_CAP = 32;
13789
14097
  var WORKER_ERROR_OVERFLOW_KIND = "other";
13790
14098
  var STARTUP_REPAIR_WAIT_SOURCE_BOUNDARIES = 2;
14099
+ var NOT_TAKEN = Object.freeze({ taken: false, recovered: null });
13791
14100
  function isMulticastSymbolDelivery(value) {
13792
14101
  return value === "datagram" || value === "ordered-relay";
13793
14102
  }
@@ -13881,10 +14190,18 @@ var FECManager = class _FECManager {
13881
14190
  // 'pending' forever, which would park every later frame of its stream in
13882
14191
  // the in-order release gate. Each entry owns its handle; the callback
13883
14192
  // checks it still owns the key, so a settled or reset key is never touched.
14193
+ /**
14194
+ * Per owed Worker cleanup: the bound on its acknowledgement, when its block
14195
+ * was due, and when its cleanup was asked for (see `onCleanupComplete`).
14196
+ */
13884
14197
  this.#pendingWorkerCleanupBounds = /* @__PURE__ */ new Map();
13885
14198
  // Source symbol count per track-scoped block — marks complete when K symbols arrive.
13886
14199
  this.#blockSourceCounts = /* @__PURE__ */ new Map();
13887
14200
  this.#blockSourceEsis = /* @__PURE__ */ new Map();
14201
+ // Source ESIs per block that another FEC instance rebuilt and fed in
14202
+ // (feedRebuiltSourceSymbol). Kept apart from #blockSourceEsis: they are
14203
+ // not network arrivals and never make a block clean.
14204
+ this.#blockRebuiltEsis = /* @__PURE__ */ new Map();
13888
14205
  // Authored SSB_length per block (ISO/IEC 23008-1 §C.5.3), learned from the
13889
14206
  // first repair symbol. The FFmpeg moq_mmt publisher closes a block every D
13890
14207
  // media units, usually before it holds K symbols; under iso-ssbg1-v1
@@ -13893,10 +14210,14 @@ var FECManager = class _FECManager {
13893
14210
  // SSB_length source arrivals and recoverable from SSB_length received
13894
14211
  // symbols; waiting for K fails every one of them.
13895
14212
  this.#blockAuthoredLengths = /* @__PURE__ */ new Map();
14213
+ // Keys whose authored length is a repair-less span's (#openIsoSpan), until
14214
+ // a repair states the block there or the span resolves.
14215
+ this.#isoSpanKeys = /* @__PURE__ */ new Set();
13896
14216
  this.#ssbLengthConflictCount = 0;
13897
14217
  this.#blockRepairRsIds = /* @__PURE__ */ new Map();
13898
14218
  // RSB_length per block (C.5.3 Repair FEC Payload ID): how many repair
13899
- // symbols its repair group carries. Same lifecycle as #blockRepairRsIds.
14219
+ // symbols its repair group carries; 0 for a repair-less span no repair can
14220
+ // state (#openIsoSpan). Same lifecycle as #blockRepairRsIds.
13900
14221
  this.#blockRsbLengths = /* @__PURE__ */ new Map();
13901
14222
  /** fec-01 6.3.9 anchor state per stream key, one entry per held layer. */
13902
14223
  this.#heldLayerStates = /* @__PURE__ */ new Map();
@@ -14013,6 +14334,10 @@ var FECManager = class _FECManager {
14013
14334
  // ── Keyframe-protected repair policy (block-policy.ts) ──
14014
14335
  // One classifier per physical stream, built from that stream's geometry.
14015
14336
  this.#classifiers = /* @__PURE__ */ new Map();
14337
+ // A stream without catalog timing has no classifier, so the last RAP it
14338
+ // released stands in for one: "an MPU boundary bounds its RAPs" holds until
14339
+ // a second RAP is released inside one MPU (BLO-52085).
14340
+ this.#noSpanRaps = /* @__PURE__ */ new Map();
14016
14341
  // Geometry a stream-scoped configuration gave one stream (streamKey). ABR
14017
14342
  // rungs can share a packetId with a different framerate or GOP, so the
14018
14343
  // packet-level geometry is only the geometry of a packet whose streams
@@ -14080,13 +14405,17 @@ var FECManager = class _FECManager {
14080
14405
  this.#workerErrorCounts = /* @__PURE__ */ new Map();
14081
14406
  this.#decoderUnavailableEvents = 0;
14082
14407
  this.#repairSymbolSizeMismatchCount = 0;
14408
+ this.#unlistedRepairTrackRefusals = 0;
14083
14409
  // Event callbacks — block lifecycle notifications for MmtpRouter wiring.
14084
14410
  // NOTE: For sync WASM path, recovery routing is handled by MmtpRouter from
14085
14411
  // feedSourceSymbol/feedRepairSymbol return values. For Worker path, recovery
14086
14412
  // arrives via onBlockRecovered callback.
14087
14413
  this.onBlockStarted = null;
14088
14414
  this.onBlockComplete = null;
14089
- /** A block reached its fail bound. `blockClass` is its class at failure. */
14415
+ /**
14416
+ * A block reached its fail bound. `blockClass` is its class at failure.
14417
+ * `span` is set when what failed is a repair-less span starting at `sbn`.
14418
+ */
14090
14419
  this.onBlockFailed = null;
14091
14420
  /**
14092
14421
  * Fired once per stream when its Worker decoder stops being routable.
@@ -14128,12 +14457,24 @@ var FECManager = class _FECManager {
14128
14457
  * for it, which it must be.
14129
14458
  */
14130
14459
  this.#onUndelimitedLoss = null;
14460
+ /** Set with the loss handler: true takes an expired hole to close (`closeIsoHoles`). */
14461
+ this.#onIsoHoleExpired = null;
14131
14462
  /** A block every symbol of which vanished was created by SBN evidence. */
14132
14463
  this.onBlockVanished = null;
14133
14464
  /** A block reached a terminal state (completed, recovered, or failed). */
14134
14465
  this.onBlockResolved = null;
14135
14466
  /** A stream's SBN went backwards (or jumped implausibly): the source restarted. */
14136
14467
  this.onSourceDiscontinuity = null;
14468
+ /**
14469
+ * The span and tolerance the catalog states for a keyframe overlay
14470
+ * installed over a source track (draft-ramadan-moq-mmt-02 7.4.1: the
14471
+ * overlay instance's own interleaveDepthMs and reorderToleranceMs), or
14472
+ * undefined while none is installed. A stated block only a late source
14473
+ * can complete, and a frame whose gap may hide a RAP behind a span only a
14474
+ * late source can fill, also wait for that overlay's repair
14475
+ * (#overlayLateWaitMs).
14476
+ */
14477
+ this.keyframeOverlayTiming = null;
14137
14478
  // Worker-path callbacks — async recovery and stats from FecWorkerClient.
14138
14479
  /**
14139
14480
  * A recovered source symbol. Return false when admission refused the
@@ -14170,7 +14511,9 @@ var FECManager = class _FECManager {
14170
14511
  #pendingWorkerCleanupBounds;
14171
14512
  #blockSourceCounts;
14172
14513
  #blockSourceEsis;
14514
+ #blockRebuiltEsis;
14173
14515
  #blockAuthoredLengths;
14516
+ #isoSpanKeys;
14174
14517
  #ssbLengthConflictCount;
14175
14518
  #blockRepairRsIds;
14176
14519
  #blockRsbLengths;
@@ -14212,6 +14555,7 @@ var FECManager = class _FECManager {
14212
14555
  #orderedFrontiers;
14213
14556
  #orderedPendingBlocks;
14214
14557
  #classifiers;
14558
+ #noSpanRaps;
14215
14559
  #streamGeometries;
14216
14560
  #failedBlocks;
14217
14561
  #resolvedBlockClasses;
@@ -14235,7 +14579,9 @@ var FECManager = class _FECManager {
14235
14579
  #workerErrorCounts;
14236
14580
  #decoderUnavailableEvents;
14237
14581
  #repairSymbolSizeMismatchCount;
14582
+ #unlistedRepairTrackRefusals;
14238
14583
  #onUndelimitedLoss;
14584
+ #onIsoHoleExpired;
14239
14585
  #encodeTrackName(catalogTrackName) {
14240
14586
  let encoded = this.#encodedTrackNames.get(catalogTrackName);
14241
14587
  if (encoded === void 0) {
@@ -14707,7 +15053,10 @@ var FECManager = class _FECManager {
14707
15053
  timer.handle = null;
14708
15054
  this.#requestRepair(sbn, packetId, catalogTrackName);
14709
15055
  };
14710
- timer.handle = setTimeout(onFire, Math.max(0, deadlineMs - performance.now()));
15056
+ timer.handle = setTimeout(
15057
+ onFire,
15058
+ this.#receiptAtMs === void 0 ? Math.max(0, deadlineMs - performance.now()) : this.#receiptTimerDelayMs(deadlineMs, 0)
15059
+ );
14711
15060
  this.#repairDeadlines.set(key, timer);
14712
15061
  }
14713
15062
  #requestRepair(sbn, packetId, catalogTrackName, settledByOrder = false) {
@@ -14851,8 +15200,14 @@ var FECManager = class _FECManager {
14851
15200
  * Vanished blocks are not enumerated here: their starts are unknown until a
14852
15201
  * repair states them. The SS_IDs between two stated blocks become one
14853
15202
  * repair-less span when the later block's repair arrives (placeIsoRepair).
15203
+ *
15204
+ * A `held` source arrived before its block was known and is fed only now
15205
+ * that a repair, a span or a closed hole placed it: how far its block start
15206
+ * then lies behind the frontier measures how long the receiver held it, not
15207
+ * where the stream was, so only its SS_ID and packet_sequence_number judge
15208
+ * it (BLO-52085).
14854
15209
  */
14855
- #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn) {
15210
+ #noteSbnSeen(sbn, packetId, catalogTrackName, symbol, packetSequenceNumber, ssId = sbn, held = false) {
14856
15211
  const streamKey = this.#streamKey(packetId, catalogTrackName);
14857
15212
  const now = performance.now();
14858
15213
  const previous = (symbol === "source" ? this.#sourceFrontiers : this.#highestSbn).get(streamKey);
@@ -14873,6 +15228,7 @@ var FECManager = class _FECManager {
14873
15228
  };
14874
15229
  const discontinuity = () => {
14875
15230
  this.#classifiers.get(streamKey)?.noteSourceDiscontinuity();
15231
+ this.#noSpanRaps.delete(streamKey);
14876
15232
  this.#highestSbn.set(streamKey, { sbn, atMs: now });
14877
15233
  this.#sourceFrontiers.set(streamKey, { sbn, atMs: now });
14878
15234
  if (psn === void 0) this.#sourceAnchors.delete(streamKey);
@@ -14890,7 +15246,7 @@ var FECManager = class _FECManager {
14890
15246
  return sent <= 2147483647 && serial32Distance(from.ssId, to.ssId) <= sent + config.k;
14891
15247
  };
14892
15248
  if (!this.#blockPrecedes(previous.sbn, sbn)) {
14893
- if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
15249
+ if (symbol === "source" && window2 !== null && this.#blockPrecedes(sbn, previous.sbn) && (!held && this.#blocksBehind(sbn, previous.sbn, packetId) > this.#isoRetentionBlocks(packetId) || psn !== void 0 && anchor !== void 0 && serial32Precedes(ssId, anchor.ssId) && psn !== anchor.psn && !sentInOrder({ ssId, psn }, anchor))) {
14894
15250
  discontinuity();
14895
15251
  return;
14896
15252
  }
@@ -15152,17 +15508,21 @@ var FECManager = class _FECManager {
15152
15508
  this.#blockWaitDeadlinesMs.delete(key);
15153
15509
  this.#repairHoldUntilMs.delete(key);
15154
15510
  this.#traceLifecycle("timeout-queued", sbn, packetId, catalogTrackName);
15155
- this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName);
15511
+ this.#finalizeExpiredBlock(sbn, packetId, catalogTrackName, currentDeadlineMs ?? firedAtMs);
15156
15512
  };
15157
- timer.handle = setTimeout(onFire, Math.max(1, Math.ceil(deadlineMs - nowMs)));
15513
+ timer.handle = setTimeout(
15514
+ onFire,
15515
+ this.#receiptAtMs === void 0 ? Math.max(1, Math.ceil(deadlineMs - nowMs)) : this.#receiptTimerDelayMs(deadlineMs, 1)
15516
+ );
15158
15517
  this.#activeBlocks.set(key, timer);
15159
15518
  this.#indexBlockKey(key, sbn, packetId);
15160
15519
  }
15161
15520
  /**
15162
15521
  * Hand a block whose delivery is over to its decoder for finalization: the
15163
- * datagram deadline fired, or the ordered relay moved past it.
15522
+ * datagram deadline fired, or the ordered relay moved past it. `dueAtMs`
15523
+ * is when it was due: its deadline, or now.
15164
15524
  */
15165
- #finalizeExpiredBlock(sbn, packetId, catalogTrackName) {
15525
+ #finalizeExpiredBlock(sbn, packetId, catalogTrackName, dueAtMs = performance.now()) {
15166
15526
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
15167
15527
  if (this.#materializedBlocks.has(key) && !this.#blockPathCounts.has(key)) {
15168
15528
  this.#failBlock(sbn, packetId, catalogTrackName);
@@ -15178,7 +15538,7 @@ var FECManager = class _FECManager {
15178
15538
  if (workerClient) {
15179
15539
  this.#pendingWorkerCleanups.add(key);
15180
15540
  this.#pendingWorkerCleanupClients.set(key, workerClient);
15181
- this.#boundOwedCleanup(key, packetId, workerClient);
15541
+ this.#boundOwedCleanup(key, packetId, workerClient, dueAtMs);
15182
15542
  workerClient.cleanup(sbn);
15183
15543
  } else {
15184
15544
  const decoder = this.#decoderForPacket(packetId, catalogTrackName)?.client;
@@ -15285,6 +15645,9 @@ var FECManager = class _FECManager {
15285
15645
  }
15286
15646
  if (policyChanged) {
15287
15647
  this.#bumpEpoch(packetId);
15648
+ for (const key of [...this.#noSpanRaps.keys()]) {
15649
+ if (this.#belongsToPacket(key, packetId)) this.#noSpanRaps.delete(key);
15650
+ }
15288
15651
  for (const [key, classifier] of [...this.#classifiers]) {
15289
15652
  if (!this.#belongsToPacket(key, packetId)) continue;
15290
15653
  const stream = this.#parseStreamKey(key);
@@ -15385,6 +15748,7 @@ var FECManager = class _FECManager {
15385
15748
  packetId
15386
15749
  })),
15387
15750
  repairSymbolSizeMismatches: this.#repairSymbolSizeMismatchCount,
15751
+ unlistedRepairTrackRefusals: this.#unlistedRepairTrackRefusals,
15388
15752
  repairObjectRejects: [...this.#repairObjectRejects.values()].map((r) => ({ ...r })),
15389
15753
  workerErrors: Object.fromEntries(this.#workerErrorCounts)
15390
15754
  };
@@ -15487,7 +15851,9 @@ var FECManager = class _FECManager {
15487
15851
  }
15488
15852
  resetMap(this.#blockSourceCounts);
15489
15853
  resetMap(this.#blockSourceEsis);
15854
+ resetMap(this.#blockRebuiltEsis);
15490
15855
  resetMap(this.#blockAuthoredLengths);
15856
+ resetSet(this.#isoSpanKeys);
15491
15857
  resetMap(this.#blockRepairRsIds);
15492
15858
  resetMap(this.#blockRsbLengths);
15493
15859
  resetMap(this.#heldLayerStates);
@@ -15520,6 +15886,7 @@ var FECManager = class _FECManager {
15520
15886
  resetMap(this.#isoLocators);
15521
15887
  resetMap(this.#sourceAnchors);
15522
15888
  this.#classifiers.delete(this.#streamKey(packetId, catalogTrackName));
15889
+ this.#noSpanRaps.delete(this.#streamKey(packetId, catalogTrackName));
15523
15890
  this.#bumpEpoch(packetId);
15524
15891
  for (const [sbn, keys] of this.#blockKeysBySbn) {
15525
15892
  for (const key of keys.keys()) {
@@ -15610,7 +15977,9 @@ var FECManager = class _FECManager {
15610
15977
  dropMap(this.#pendingWorkerCleanupClients);
15611
15978
  dropMap(this.#blockSourceCounts);
15612
15979
  dropMap(this.#blockSourceEsis);
15980
+ dropMap(this.#blockRebuiltEsis);
15613
15981
  dropMap(this.#blockAuthoredLengths);
15982
+ dropSet(this.#isoSpanKeys);
15614
15983
  dropMap(this.#blockRepairRsIds);
15615
15984
  dropMap(this.#blockRsbLengths);
15616
15985
  dropMap(this.#blockPathCounts);
@@ -15626,6 +15995,7 @@ var FECManager = class _FECManager {
15626
15995
  dropMap(this.#isoLocators);
15627
15996
  dropMap(this.#sourceAnchors);
15628
15997
  dropMap(this.#classifiers);
15998
+ dropMap(this.#noSpanRaps);
15629
15999
  dropMap(this.#streamGeometries);
15630
16000
  dropSet(this.#pendingWorkerCleanups);
15631
16001
  dropSet(this.#completedBlocks);
@@ -15771,6 +16141,9 @@ var FECManager = class _FECManager {
15771
16141
  this.#unindexBlockKey(key);
15772
16142
  }
15773
16143
  }
16144
+ if (isSourceSymbol && source === "multicast") {
16145
+ this.#noteMulticastSource(this.#isoLocatorFor(packetId, catalogTrackName), sbn + esi >>> 0, packetId, catalogTrackName);
16146
+ }
15774
16147
  return true;
15775
16148
  }
15776
16149
  #observeBlockCatalogTrackName(blockKey, sbn, packetId, catalogTrackName) {
@@ -15880,8 +16253,10 @@ var FECManager = class _FECManager {
15880
16253
  }
15881
16254
  /**
15882
16255
  * An open block's accepted sources, distinct repair RS_IDs, authored K'
15883
- * (SSB_length) and RSB_length (each undefined until a repair stated it).
15884
- * Undefined for a block that is not open.
16256
+ * (SSB_length) and RSB_length (each undefined until a repair stated it; a
16257
+ * repair-less span states its length, and RSB_length 0 when it is longer
16258
+ * than K, since no repair can reach it). Undefined for a block that is not
16259
+ * open.
15885
16260
  */
15886
16261
  blockSymbolCounts(sbn, packetId, catalogTrackName) {
15887
16262
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -15949,8 +16324,9 @@ var FECManager = class _FECManager {
15949
16324
  return true;
15950
16325
  }
15951
16326
  /**
15952
- * Drop a block's repair hold: its FETCH ended without delivering. The block
15953
- * falls back to its multicast wait, which may already have passed.
16327
+ * Drop a block's repair hold: its FETCH ended without delivering, or brought
16328
+ * back only a repair that cannot complete it. The block falls back to its
16329
+ * multicast wait, which may already have passed.
15954
16330
  */
15955
16331
  releaseRepairHold(sbn, packetId, catalogTrackName) {
15956
16332
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
@@ -15996,7 +16372,7 @@ var FECManager = class _FECManager {
15996
16372
  }
15997
16373
  const trackConfig = this.#trackConfigs.get(packetId);
15998
16374
  if (trackConfig === void 0) return void 0;
15999
- return Math.max(1, trackConfig.timeoutMs - this.#repairDeadlineMs(trackConfig));
16375
+ return Math.max(1, this.#repairGraceMs(trackConfig, this.#multicastWaitMs(trackConfig)));
16000
16376
  }
16001
16377
  /** True once configureTrack/setFecDecoder/setFecWorker configured this packetId. */
16002
16378
  // -----------------------------------------------------------------------
@@ -16088,6 +16464,8 @@ var FECManager = class _FECManager {
16088
16464
  const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16089
16465
  const evictedBefore = locator.heldEvicted;
16090
16466
  const held = locator.hold(ssId, source);
16467
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16468
+ if (held && source.source === "multicast") this.#noteMulticastSource(locator, ssId, packetId, catalogTrackName);
16091
16469
  const evicted = locator.heldEvicted - evictedBefore;
16092
16470
  if (evicted > 0) {
16093
16471
  const before = this.#isoHeldEvictedCount;
@@ -16108,17 +16486,20 @@ var FECManager = class _FECManager {
16108
16486
  * contradicts a known block is refused (counted) and must be dropped.
16109
16487
  */
16110
16488
  placeIsoRepair(packetId, catalogTrackName, ssStart, ssbLength) {
16111
- const placement = this.#growingIsoLocatorFor(packetId, catalogTrackName).placeRepair(ssStart, ssbLength);
16489
+ const locator = this.#growingIsoLocatorFor(packetId, catalogTrackName);
16490
+ const placement = locator.placeRepair(ssStart, ssbLength);
16491
+ this.#settleExpiredIsoHoles(locator, packetId, catalogTrackName);
16112
16492
  if (placement.status !== "placed") {
16113
16493
  this.#isoRepairRefusedCount++;
16114
16494
  if (this.#isoRepairRefusedCount <= 5 || this.#isoRepairRefusedCount % 100 === 0) {
16115
16495
  console.warn(`[FECManager] packetId=${packetId} iso-ssbg1-v1 repair refused (${placement.status}): ${placement.reason}`);
16116
16496
  }
16497
+ if (placement.ofSpan !== void 0) this.releaseRepairHold(placement.ofSpan.start, packetId, catalogTrackName);
16117
16498
  return placement;
16118
16499
  }
16500
+ this.#isoSpanKeys.delete(this.#blockKey(placement.block.start, packetId, catalogTrackName));
16119
16501
  if (placement.span !== void 0) this.#openIsoSpan(placement.span, packetId, catalogTrackName);
16120
16502
  if (placement.hole !== void 0) {
16121
- const locator = this.#isoLocatorFor(packetId, catalogTrackName);
16122
16503
  const hole = placement.hole.block;
16123
16504
  const previous = locator.blockEndingAt(hole.start);
16124
16505
  const loss = {
@@ -16139,17 +16520,29 @@ var FECManager = class _FECManager {
16139
16520
  * `handler`, instead of a repair-less span; null restores spans. Set by the
16140
16521
  * range repair scheduler; applies to every stream from its next gap. The
16141
16522
  * handler and the deferral are one setting, so no hole is ever created with
16142
- * nobody to close it.
16523
+ * nobody to close it. `onExpired` is told of each pending hole the stream
16524
+ * runs past the locator's horizon (BLO-52085): returning true, it closes
16525
+ * the hole (`closeIsoHoles`), so the span it leaves still fails and is
16526
+ * reported; otherwise the hole is discarded with its sources.
16143
16527
  */
16144
- setUndelimitedLossHandler(handler) {
16528
+ setUndelimitedLossHandler(handler, onExpired = null) {
16145
16529
  this.#onUndelimitedLoss = handler;
16530
+ this.#onIsoHoleExpired = handler === null ? null : onExpired;
16146
16531
  this.#deferIsoGaps = handler !== null;
16147
16532
  for (const locator of this.#isoLocators.values()) locator.deferIncompleteGaps = this.#deferIsoGaps;
16148
16533
  }
16534
+ /** Hand each hole the locator's horizon passed to its owner, or discard it (setUndelimitedLossHandler). */
16535
+ #settleExpiredIsoHoles(locator, packetId, catalogTrackName) {
16536
+ for (const hole of locator.takeExpiredHoles()) {
16537
+ const expired = { packetId, catalogTrackName, holeStart: hole.start, holeLength: hole.length };
16538
+ if (this.#onIsoHoleExpired?.(expired) !== true) locator.closeHolesWithin(hole.start, hole.length);
16539
+ }
16540
+ }
16149
16541
  /**
16150
- * The range repair for a hole ended: every hole still pending inside
16151
- * `[start, start + length)` becomes a repair-less span. Returns those spans
16152
- * with the held sources they placed, for the caller to feed (MmtpRouter).
16542
+ * The range repair for a hole ended: every hole inside `[start, start +
16543
+ * length)`, pending or expired, becomes a repair-less span. Returns those
16544
+ * spans with the held sources they placed, for the caller to feed
16545
+ * (MmtpRouter).
16153
16546
  */
16154
16547
  closeIsoHoles(packetId, catalogTrackName, start, length) {
16155
16548
  const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
@@ -16165,10 +16558,25 @@ var FECManager = class _FECManager {
16165
16558
  * its placed sources exactly as on the wire (feedRepairSymbol). A span every
16166
16559
  * SS_ID of which vanished resolves through its deadline like any vanished
16167
16560
  * block.
16561
+ *
16562
+ * A span longer than K holds more than one block (SSB_length <= K), and the
16563
+ * locator states no block inside a span, only one exactly its range
16564
+ * (IsoBlockLocator.placeRepair): no repair, multicast or FETCHed, can ever
16565
+ * reach it. Its repair group is empty, so the repair scheduler FETCHes no
16566
+ * Group of it (group-cannot-complete). Every span still keeps its whole
16567
+ * wait (#lateSourceWaitMs): failing it early released the frames behind it
16568
+ * past a keyframe the overlay was still rebuilding (BLO-52085). The release
16569
+ * gate lets those frames go once only a late source can fill the gap
16570
+ * before them, as long after they arrived as the gap's decision allows
16571
+ * (isoRepairlessWaitMs).
16168
16572
  */
16169
16573
  #openIsoSpan(span, packetId, catalogTrackName) {
16170
16574
  const key = this.#blockKey(span.block.start, packetId, catalogTrackName);
16171
- if (!this.#blockAuthoredLengths.has(key)) this.#blockAuthoredLengths.set(key, span.block.length);
16575
+ if (!this.#blockAuthoredLengths.has(key)) {
16576
+ this.#blockAuthoredLengths.set(key, span.block.length);
16577
+ this.#isoSpanKeys.add(key);
16578
+ if (span.block.length > this.#isoLocatorFor(packetId, catalogTrackName).kMax) this.#blockRsbLengths.set(key, 0);
16579
+ }
16172
16580
  if (span.placed.length === 0) this.#materializeBlock(span.block.start, packetId, catalogTrackName, true);
16173
16581
  }
16174
16582
  /**
@@ -16206,6 +16614,62 @@ var FECManager = class _FECManager {
16206
16614
  }
16207
16615
  return lost;
16208
16616
  }
16617
+ /**
16618
+ * The release gate's wait, from a frame's arrival, for the SS_IDs strictly
16619
+ * between two released frames' SS_IDs once only a late source can still
16620
+ * fill them, else undefined. That is when every one missing (neither
16621
+ * arrived nor held) lies in a repair-less span longer than K, which no
16622
+ * repair can state a block of (#openIsoSpan), or in a stated block its
16623
+ * own repair group cannot complete every SS_ID of which it misses lies
16624
+ * between them (so the gap's decision covers all it lost), and a multicast
16625
+ * source at or past `toSsId` arrived, so each is lost or reordered behind
16626
+ * it (a MoQ source shows nothing: MoQ streams overtake one another). The
16627
+ * span or block itself keeps its own wait.
16628
+ *
16629
+ * The wait is the late-symbol allowance, unless `rapMayHide`: the gap may
16630
+ * hold a RAP packet an installed keyframe overlay can still rebuild (its
16631
+ * decision stalls, or it ends at a RAP that may lie past a whole MPU).
16632
+ * Then the frame waits as a stated block its group cannot complete does
16633
+ * (#overlayLateWaitMs): the allowance alone with no overlay installed, the
16634
+ * overlay's span plus the larger of the allowance and its tolerance, or,
16635
+ * for an overlay that states no span, the span's whole wait (undefined).
16636
+ * So does `rapNext` (the gap ends at the RAP that opens the next MPU) when
16637
+ * the gap holds a stated block's loss.
16638
+ */
16639
+ isoRepairlessWaitMs(packetId, catalogTrackName, fromSsId, toSsId, rapMayHide = false, rapNext = false) {
16640
+ const config = this.#trackConfigs.get(packetId);
16641
+ if (config === void 0 || !_FECManager.#hasCatalogTiming(config)) return void 0;
16642
+ const locator = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName));
16643
+ if (locator === void 0 || !locator.coversBetween(fromSsId, toSsId)) return void 0;
16644
+ const newestSource = locator.newestSource;
16645
+ if (newestSource === void 0 || serial32Precedes(newestSource, toSsId)) return void 0;
16646
+ let repairless = false;
16647
+ let stated = false;
16648
+ for (const block of locator.blocksBetween(fromSsId, toSsId)) {
16649
+ const key = this.#blockKey(block.start, packetId, catalogTrackName);
16650
+ if (this.#completedBlocks.has(key)) continue;
16651
+ if (block.span && block.length > locator.kMax) {
16652
+ repairless = true;
16653
+ continue;
16654
+ }
16655
+ const received = this.#blockSourceEsis.get(key);
16656
+ const rebuilt = this.#blockRebuiltEsis.get(key);
16657
+ let missesInGap = false;
16658
+ let missesOutside = false;
16659
+ for (let esi = 0; esi < block.length; esi++) {
16660
+ const ssId = serial32Add(block.start, esi);
16661
+ if (received?.has(esi) || locator.isHeld(ssId)) continue;
16662
+ if (serial32Precedes(fromSsId, ssId) && serial32Precedes(ssId, toSsId)) missesInGap = true;
16663
+ else if (!rebuilt?.has(esi)) missesOutside = true;
16664
+ }
16665
+ if (!missesInGap) continue;
16666
+ if (missesOutside || block.span || !this.#groupCannotComplete(key)) return void 0;
16667
+ repairless = stated = true;
16668
+ }
16669
+ if (!repairless) return void 0;
16670
+ const waitMs = rapMayHide || stated && rapNext ? this.#overlayLateWaitMs(packetId, catalogTrackName, config) : this.#multicastWaitMs(config) - config.interleaveDepthMs;
16671
+ return waitMs === void 0 ? void 0 : Math.max(0, waitMs);
16672
+ }
16209
16673
  /**
16210
16674
  * iso-ssbg1-v1 block location: repair symbols it refused, oversize sources,
16211
16675
  * the sources held now for a block no repair has stated yet, and the held
@@ -16256,11 +16720,14 @@ var FECManager = class _FECManager {
16256
16720
  /**
16257
16721
  * Whether an MPU boundary still bounds this stream's RAPs (see
16258
16722
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
16259
- * it does not. A stream with no classifier yet has shown nothing against it.
16723
+ * it does not. A stream with no classifier yet has shown nothing against it,
16724
+ * and neither has a stream without catalog timing until it releases two
16725
+ * RAPs inside one MPU.
16260
16726
  */
16261
16727
  mpuBoundsRapsFor(packetId, catalogTrackName) {
16262
- if (!this.#hasCatalogTimingForPacket(packetId)) return false;
16263
- return this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))?.mpuBoundsRaps ?? true;
16728
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16729
+ if (!this.#hasCatalogTimingForPacket(packetId)) return this.#noSpanRaps.get(streamKey)?.inside !== true;
16730
+ return this.#classifiers.get(streamKey)?.mpuBoundsRaps ?? true;
16264
16731
  }
16265
16732
  /** A block's class now, or frozen at its resolution. */
16266
16733
  blockClassFor(sbn, packetId, catalogTrackName) {
@@ -16286,7 +16753,14 @@ var FECManager = class _FECManager {
16286
16753
  * invariant (consecutive MPUs exactly one keyframe interval apart).
16287
16754
  */
16288
16755
  noteReleasedRap(packetId, catalogTrackName, mpu, presentationTime, mediaTimescale) {
16289
- if (!this.#trackConfigs.has(packetId) || !this.#hasCatalogTimingForPacket(packetId)) return;
16756
+ if (!this.#trackConfigs.has(packetId)) return;
16757
+ if (!this.#hasCatalogTimingForPacket(packetId)) {
16758
+ const streamKey = this.#streamKey(packetId, catalogTrackName);
16759
+ const last = this.#noSpanRaps.get(streamKey);
16760
+ const inside = last?.inside === true || last?.mpu === mpu && last.presentationTime !== presentationTime;
16761
+ this.#noSpanRaps.set(streamKey, { mpu, presentationTime, inside });
16762
+ return;
16763
+ }
16290
16764
  this.#applyClassifierChanges(
16291
16765
  packetId,
16292
16766
  catalogTrackName,
@@ -16499,11 +16973,14 @@ var FECManager = class _FECManager {
16499
16973
  });
16500
16974
  client.onCleanupComplete((sbn) => {
16501
16975
  if (this.#releasedWorkerClients.has(client)) return;
16502
- const cleanupKeys = [...this.#pendingWorkerCleanups].filter((key) => {
16976
+ const owed = [...this.#pendingWorkerCleanups].filter((key) => this.#pendingWorkerCleanupClients.get(key) === client);
16977
+ const cleanupKeys = owed.filter((key) => {
16503
16978
  const block = this.#parseBlockKey(key);
16504
- return block.packetId === packetId && block.sbn === sbn && this.#pendingWorkerCleanupClients.get(key) === client;
16979
+ return block.packetId === packetId && block.sbn === sbn;
16505
16980
  });
16506
- for (const key of cleanupKeys) this.#settleOwedCleanup(key, "cleanup-ack");
16981
+ const askedAtMs = Math.max(...cleanupKeys.map((key) => this.#pendingWorkerCleanupBounds.get(key)?.askedAtMs ?? -Infinity));
16982
+ const due = owed.filter((key) => !cleanupKeys.includes(key) && (this.#pendingWorkerCleanupBounds.get(key)?.dueAtMs ?? Infinity) <= askedAtMs);
16983
+ for (const key of [...cleanupKeys, ...due]) this.#settleOwedCleanup(key, "cleanup-ack");
16507
16984
  });
16508
16985
  client.onError((msg, code) => {
16509
16986
  const requestedKind = code ?? msg;
@@ -16573,9 +17050,11 @@ var FECManager = class _FECManager {
16573
17050
  * fail deadline already passed, so failing it is the decision that deadline
16574
17051
  * made. A late ack then finds nothing owed and is a no-op.
16575
17052
  */
16576
- #boundOwedCleanup(key, packetId, client) {
17053
+ #boundOwedCleanup(key, packetId, client, dueAtMs) {
16577
17054
  this.#clearOwedCleanupBound(key);
16578
17055
  const bound = {
17056
+ dueAtMs,
17057
+ askedAtMs: performance.now(),
16579
17058
  handle: setTimeout(() => {
16580
17059
  if (this.#pendingWorkerCleanupBounds.get(key) !== bound) return;
16581
17060
  this.#pendingWorkerCleanupBounds.delete(key);
@@ -16673,7 +17152,15 @@ var FECManager = class _FECManager {
16673
17152
  this.#isoSourceOversizeCount++;
16674
17153
  return null;
16675
17154
  }
16676
- const sbn = located.block.start;
17155
+ return this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, located.block.start);
17156
+ }
17157
+ /**
17158
+ * Hand one placed source symbol to the stream's decoder: its Worker, which
17159
+ * answers through onFrame (null here), or its synchronous decoder, whose
17160
+ * recovered block is returned. `sbn` is the SS_Start of the block a repair
17161
+ * stated for `ssId`.
17162
+ */
17163
+ #feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn) {
16677
17164
  const blockKey = this.#blockKey(sbn, packetId, catalogTrackName);
16678
17165
  const syncBlockOwner = this.#syncDecoderBlockOwners.get(blockKey);
16679
17166
  const workerClient = this.#routableWorkerForPacket(packetId, catalogTrackName);
@@ -16702,6 +17189,74 @@ var FECManager = class _FECManager {
16702
17189
  }
16703
17190
  return recovered;
16704
17191
  }
17192
+ /**
17193
+ * Feed a source symbol of this stream that another FEC instance over the
17194
+ * same packets rebuilt: a keyframe overlay recovery whose base SS_ID the
17195
+ * caller determined (draft-ramadan-moq-mmt-02 7.1, 7.4.4; joint decoding,
17196
+ * BLO-52085). It joins its block's decoder as a received source would, so
17197
+ * it reduces the erasures the block still has to solve, but it is not a
17198
+ * network arrival: no transport accounting, no classification evidence,
17199
+ * no deadline refresh, and it never makes a block clean.
17200
+ *
17201
+ * Only a block a repair stated takes one (a repair-less span has no
17202
+ * decoder block). A block that is terminal, or already holds that source,
17203
+ * does not. The symbol is the exact protected packet, unpadded, as
17204
+ * feedSourceSymbol takes it.
17205
+ *
17206
+ * `recovered` is the block the synchronous decoder completed with it; the
17207
+ * caller routes it and completes the block, as for any recovery. When
17208
+ * every source of the block is then present, received or rebuilt, and no
17209
+ * decoder returned it (a Worker answers asynchronously, and reports such a
17210
+ * block as clean on its own side), the block is completed here as
17211
+ * recovered, with nothing left to route.
17212
+ */
17213
+ feedRebuiltSourceSymbol(packetId, ssId, symbolData, catalogTrackName) {
17214
+ if (!this.#hasBlockProfile(packetId)) return NOT_TAKEN;
17215
+ const located = this.#isoLocatorFor(packetId, catalogTrackName).locate(ssId);
17216
+ if (located === null || located.block.span) return NOT_TAKEN;
17217
+ if (!ssbg1FitsSymbol(symbolData.byteLength, this.#trackConfig(packetId).symbolSize)) return NOT_TAKEN;
17218
+ const sbn = located.block.start;
17219
+ const key = this.#blockKey(sbn, packetId, catalogTrackName);
17220
+ if (this.#completedBlocks.has(key) || this.#blockSourceEsis.get(key)?.has(located.esi)) return NOT_TAKEN;
17221
+ let rebuilt = this.#blockRebuiltEsis.get(key);
17222
+ if (rebuilt?.has(located.esi)) return NOT_TAKEN;
17223
+ if (rebuilt === void 0) {
17224
+ rebuilt = /* @__PURE__ */ new Set();
17225
+ this.#blockRebuiltEsis.set(key, rebuilt);
17226
+ }
17227
+ const config = this.#trackConfigs.get(packetId);
17228
+ const wasShort = config !== void 0 && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) !== void 0;
17229
+ rebuilt.add(located.esi);
17230
+ const recovered = this.#feedDecoderSource(packetId, ssId, symbolData, catalogTrackName, sbn);
17231
+ if (recovered === null && !this.#completeWhenSourcesPresent(key, sbn, located.block.length, packetId, catalogTrackName)) {
17232
+ if (wasShort && this.#activeBlocks.has(key) && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) === void 0) {
17233
+ this.#armBlockTimeout(sbn, packetId, catalogTrackName, this.#multicastWaitMs(config));
17234
+ }
17235
+ }
17236
+ return { taken: true, recovered };
17237
+ }
17238
+ /**
17239
+ * A block that holds every one of its `length` sources, received or
17240
+ * rebuilt by another instance, with at least one rebuilt, is recovered:
17241
+ * every packet of it was delivered, by its own arrival or by the instance
17242
+ * that rebuilt it, so nothing is routed. Returns whether it completed it.
17243
+ */
17244
+ #completeWhenSourcesPresent(key, sbn, length, packetId, catalogTrackName) {
17245
+ const rebuilt = this.#blockRebuiltEsis.get(key);
17246
+ if (rebuilt === void 0 || this.#completedBlocks.has(key)) return false;
17247
+ let present = rebuilt.size;
17248
+ for (const esi of this.#blockSourceEsis.get(key) ?? []) if (!rebuilt.has(esi)) present++;
17249
+ if (present < length) return false;
17250
+ this.#traceLifecycle("recovered", sbn, packetId, catalogTrackName);
17251
+ this.countRecovery(packetId, sbn, catalogTrackName);
17252
+ this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17253
+ if (catalogTrackName === void 0) {
17254
+ this.onBlockComplete?.(sbn, packetId);
17255
+ } else {
17256
+ this.onBlockComplete?.(sbn, packetId, catalogTrackName);
17257
+ }
17258
+ return true;
17259
+ }
16705
17260
  /**
16706
17261
  * fec-01 4.5: a reed-solomon repair packet whose SSB_length + RSB_length
16707
17262
  * exceeds 255, or whose RS_ID is not below RSB_length, is discarded with the
@@ -16763,7 +17318,10 @@ var FECManager = class _FECManager {
16763
17318
  this.#layerAnchorHorizon(packetId),
16764
17319
  this.#sourceFrontiers.get(streamKey)?.sbn
16765
17320
  );
16766
- if (verdict === "discard") return false;
17321
+ if (verdict === "discard") {
17322
+ this.#unlistedRepairTrackRefusals++;
17323
+ return false;
17324
+ }
16767
17325
  if (verdict !== void 0) {
16768
17326
  this.#failClosed(streamKey, verdict, packetId, catalogTrackName);
16769
17327
  return false;
@@ -16904,8 +17462,115 @@ var FECManager = class _FECManager {
16904
17462
  this.#completeCleanBlock(blockKey, sbn, packetId, catalogTrackName);
16905
17463
  return null;
16906
17464
  }
17465
+ if (recovered === null) this.#shortenUnrecoverableWait(blockKey, sbn, packetId, catalogTrackName);
16907
17466
  return recovered;
16908
17467
  }
17468
+ /**
17469
+ * A first-arrival multicast source, held or placed. A datagram flow keeps
17470
+ * its sources in send order, so one that moves the stream's newest source
17471
+ * position past a block leaves the sources that block still misses
17472
+ * reordered behind it at best: it shortens the wait of every block it
17473
+ * passed that only a late source can complete. MoQ is left out: its streams
17474
+ * can overtake one another, so a MoQ source shows nothing about the sources
17475
+ * sent before it.
17476
+ */
17477
+ #noteMulticastSource(locator, ssId, packetId, catalogTrackName) {
17478
+ const previous = locator.newestSource;
17479
+ if (!locator.noteSource(ssId) || previous === void 0) return;
17480
+ for (const block of locator.blocksBetween(previous - 1 >>> 0, ssId)) {
17481
+ if (!serial32Precedes(serial32Add(block.start, block.length - 1), ssId)) continue;
17482
+ this.#shortenUnrecoverableWait(
17483
+ this.#blockKey(block.start, packetId, catalogTrackName),
17484
+ block.start,
17485
+ packetId,
17486
+ catalogTrackName
17487
+ );
17488
+ }
17489
+ }
17490
+ /**
17491
+ * The wait of a block that only a late source can complete (BLO-52085): a
17492
+ * repair stated it, its received sources plus every symbol its repair group
17493
+ * carries (RSB_length) are short of K' (the repair scheduler's
17494
+ * group-cannot-complete), and a later source of the stream has arrived, so
17495
+ * a source it misses is lost or reordered behind that one. The span, which
17496
+ * covers repair symbols paced after its sources, buys it nothing: it waits
17497
+ * the late-symbol allowance alone, the multicast wait less the span (the
17498
+ * catalog tolerance or the measured delivery gap). Undefined for any other
17499
+ * block. While a keyframe overlay is installed, the block waits for its
17500
+ * repair too (#overlayLateWaitMs). A repair-less span keeps its whole
17501
+ * wait, even one longer than K whose group is empty (#openIsoSpan): its
17502
+ * resolution is what releases the frames behind it, and failing it early
17503
+ * released them past a keyframe the overlay was still rebuilding, which
17504
+ * then arrived stale. The release gate lets them go instead
17505
+ * (isoRepairlessWaitMs).
17506
+ */
17507
+ #lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config) {
17508
+ if (this.#isoSpanKeys.has(key) || !this.#groupCannotComplete(key)) return void 0;
17509
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17510
+ const newestSource = this.#isoLocators.get(this.#streamKey(packetId, catalogTrackName))?.newestSource;
17511
+ if (newestSource === void 0 || !serial32Precedes(serial32Add(sbn, authoredLength - 1), newestSource)) {
17512
+ return void 0;
17513
+ }
17514
+ return this.#overlayLateWaitMs(packetId, catalogTrackName, config);
17515
+ }
17516
+ /**
17517
+ * A repair stated the block, and its sources plus every symbol its repair
17518
+ * group carries (RSB_length) are short of its SSB_length.
17519
+ */
17520
+ #groupCannotComplete(key) {
17521
+ const authoredLength = this.#blockAuthoredLengths.get(key);
17522
+ const rsbLength = this.#blockRsbLengths.get(key);
17523
+ if (authoredLength === void 0 || rsbLength === void 0) return false;
17524
+ let present = this.#blockSourceCounts.get(key) ?? 0;
17525
+ const received = this.#blockSourceEsis.get(key);
17526
+ for (const esi of this.#blockRebuiltEsis.get(key) ?? []) if (!received?.has(esi)) present++;
17527
+ return present + rsbLength < authoredLength;
17528
+ }
17529
+ /**
17530
+ * How long a loss only a late source or an installed keyframe overlay can
17531
+ * still fill waits once a later source passed it: the late-symbol
17532
+ * allowance alone (the multicast wait less the span) while no overlay is
17533
+ * installed. An installed one (keyframeOverlayTiming) may still rebuild a
17534
+ * RAP packet the loss took: a second FEC instance over the same packets
17535
+ * (draft-ramadan-moq-mmt-02 7.4), whose repair is paced across its own
17536
+ * span, unrelated to the base's. That packet can complete a stated block
17537
+ * (feedRebuiltSourceSymbol), or play behind a span; giving the loss up
17538
+ * first lets the release gate pass the keyframe, whose rebuild then lands
17539
+ * stale. The overlay repair of a packet the loss took goes out within the
17540
+ * overlay's span of that packet (fec-core-00 9.3), and the later source was
17541
+ * sent after it, so the loss waits that span plus the larger of the
17542
+ * allowance and the overlay's own tolerance. An overlay that states no
17543
+ * span (its block may then span keyframes), or one whose wait is not
17544
+ * shorter than the whole multicast wait, leaves the whole wait: undefined.
17545
+ */
17546
+ #overlayLateWaitMs(packetId, catalogTrackName, config) {
17547
+ const waitMs = this.#multicastWaitMs(config);
17548
+ const allowanceMs = waitMs - config.interleaveDepthMs;
17549
+ const overlay = this.keyframeOverlayTiming?.(packetId, catalogTrackName);
17550
+ if (overlay === void 0) return allowanceMs;
17551
+ const overlaySpanMs = overlay.interleaveDepthMs ?? 0;
17552
+ const overlayWaitMs = overlaySpanMs + Math.max(allowanceMs, overlay.reorderToleranceMs ?? 0);
17553
+ return overlaySpanMs > 0 && overlayWaitMs < waitMs ? overlayWaitMs : void 0;
17554
+ }
17555
+ /**
17556
+ * Bring an open block's wait in to its late-source wait, when it has one.
17557
+ * Never later than it is armed: only a source can complete such a block,
17558
+ * so a repair of its group (paced across the span) must not keep it open.
17559
+ */
17560
+ #shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName) {
17561
+ if (!this.#activeBlocks.has(key)) return;
17562
+ const config = this.#trackConfigs.get(packetId);
17563
+ if (config === void 0) return;
17564
+ const waitMs = this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, config);
17565
+ if (waitMs === void 0) return;
17566
+ const armedAtMs = this.#blockWaitDeadlinesMs.get(key);
17567
+ this.#armBlockTimeout(
17568
+ sbn,
17569
+ packetId,
17570
+ catalogTrackName,
17571
+ armedAtMs === void 0 ? waitMs : Math.min(waitMs, armedAtMs - this.#receiptNow())
17572
+ );
17573
+ }
16909
17574
  /**
16910
17575
  * Record a block's authored SSB_length from a repair symbol. Returns false,
16911
17576
  * leaving the block unchanged, when the symbol contradicts the block: a
@@ -17003,12 +17668,13 @@ var FECManager = class _FECManager {
17003
17668
  * the inactivity deadline on each symbol, records the symbol's in-band
17004
17669
  * classification evidence, and marks the block clean when all of its
17005
17670
  * authored source symbols arrived: the SSB_length a repair symbol declared,
17006
- * otherwise K.
17671
+ * otherwise K. `held` marks a source held unplaced since it arrived and
17672
+ * placed only now (see #noteSbnSeen).
17007
17673
  *
17008
17674
  * Throws for a packetId that was never configured, so a classified block
17009
17675
  * never reads the manager-global K or timeout.
17010
17676
  */
17011
- trackBlock(sbn, packetId, catalogTrackName, esi, evidence) {
17677
+ trackBlock(sbn, packetId, catalogTrackName, esi, evidence, held = false) {
17012
17678
  const trackConfig = this.#trackConfigs.get(packetId);
17013
17679
  if (trackConfig === void 0) {
17014
17680
  throw new Error(
@@ -17024,7 +17690,8 @@ var FECManager = class _FECManager {
17024
17690
  catalogTrackName,
17025
17691
  "source",
17026
17692
  evidence.packetSequenceNumber,
17027
- Number.isInteger(esi) ? sbn + esi >>> 0 : sbn
17693
+ Number.isInteger(esi) ? sbn + esi >>> 0 : sbn,
17694
+ held
17028
17695
  );
17029
17696
  const authoredLength = this.#blockAuthoredLengths.get(key) ?? k;
17030
17697
  if (Number.isInteger(esi) && esi >= authoredLength) {
@@ -17060,6 +17727,15 @@ var FECManager = class _FECManager {
17060
17727
  this.#completeCleanBlock(key, sbn, packetId, catalogTrackName);
17061
17728
  return;
17062
17729
  }
17730
+ if (this.#blockRebuiltEsis.has(key) && this.#completeWhenSourcesPresent(
17731
+ key,
17732
+ sbn,
17733
+ this.#isoLocatorFor(packetId, catalogTrackName).blockAt(sbn)?.length ?? authoredLength,
17734
+ packetId,
17735
+ catalogTrackName
17736
+ )) {
17737
+ return;
17738
+ }
17063
17739
  this.noteBlockActivity(sbn, packetId, catalogTrackName, true);
17064
17740
  }
17065
17741
  #completeCleanBlock(key, sbn, packetId, catalogTrackName) {
@@ -17068,7 +17744,9 @@ var FECManager = class _FECManager {
17068
17744
  this.cancelBlockTimeout(sbn, packetId, catalogTrackName);
17069
17745
  this.#blockSourceCounts.delete(key);
17070
17746
  this.#blockSourceEsis.delete(key);
17747
+ this.#blockRebuiltEsis.delete(key);
17071
17748
  this.#blockAuthoredLengths.delete(key);
17749
+ this.#isoSpanKeys.delete(key);
17072
17750
  this.#blockRepairRsIds.delete(key);
17073
17751
  this.#blockRsbLengths.delete(key);
17074
17752
  this.#markTerminal(key, sbn, packetId, true);
@@ -17099,6 +17777,19 @@ var FECManager = class _FECManager {
17099
17777
  #receiptNow() {
17100
17778
  return this.#receiptAtMs ?? performance.now();
17101
17779
  }
17780
+ /**
17781
+ * The whole-ms delay of a timer for `deadlineMs` armed inside a receipt
17782
+ * scope: counted from the receipt time, as the timer of a symbol fed when
17783
+ * it was received was, less the whole ms since. So it fires on the tick
17784
+ * that timer would have, never later than a delay counted from now, and
17785
+ * its handler still re-arms a timer that fires before its deadline.
17786
+ * Counted from now, a deadline set from the receipt time is rounded up
17787
+ * from another fraction of a ms (BLO-52085).
17788
+ */
17789
+ #receiptTimerDelayMs(deadlineMs, minMs) {
17790
+ const receivedAtMs = this.#receiptAtMs;
17791
+ return Math.max(minMs, Math.ceil(deadlineMs - receivedAtMs) - Math.ceil(performance.now() - receivedAtMs));
17792
+ }
17102
17793
  /**
17103
17794
  * A held packet admitted late arms from its (earlier) receipt time; that
17104
17795
  * never pulls in a deadline later activity already armed. Outside a
@@ -17134,10 +17825,20 @@ var FECManager = class _FECManager {
17134
17825
  this.#repairDeadlineMs(trackConfig)
17135
17826
  );
17136
17827
  }
17137
- this.#armBlockTimeout(sbn, packetId, catalogTrackName, timeoutMs);
17828
+ if (!sourceProgress && this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) !== void 0) {
17829
+ this.#shortenUnrecoverableWait(key, sbn, packetId, catalogTrackName);
17830
+ return;
17831
+ }
17832
+ this.#armBlockTimeout(
17833
+ sbn,
17834
+ packetId,
17835
+ catalogTrackName,
17836
+ this.#lateSourceWaitMs(key, sbn, packetId, catalogTrackName, trackConfig) ?? timeoutMs
17837
+ );
17138
17838
  }
17139
17839
  #failBlock(sbn, packetId, catalogTrackName) {
17140
17840
  const key = this.#blockKey(sbn, packetId, catalogTrackName);
17841
+ const span = this.#isoSpanKeys.delete(key) ? { length: this.#blockAuthoredLengths.get(key) ?? 0, sources: this.#blockSourceCounts.get(key) ?? 0 } : void 0;
17141
17842
  this.#traceLifecycle("failed", sbn, packetId, catalogTrackName);
17142
17843
  this.#clearRepairDeadline(key);
17143
17844
  this.#clearBlockTimer(key);
@@ -17147,6 +17848,7 @@ var FECManager = class _FECManager {
17147
17848
  }
17148
17849
  this.#blockSourceCounts.delete(key);
17149
17850
  this.#blockSourceEsis.delete(key);
17851
+ this.#blockRebuiltEsis.delete(key);
17150
17852
  this.#blockAuthoredLengths.delete(key);
17151
17853
  this.#blockRepairRsIds.delete(key);
17152
17854
  this.#blockRsbLengths.delete(key);
@@ -17156,7 +17858,8 @@ var FECManager = class _FECManager {
17156
17858
  this.#markPathBlockComplete(sbn, packetId, catalogTrackName);
17157
17859
  this.#fecStats.blocksFailed++;
17158
17860
  this.#statsForPacket(packetId).blocksFailed++;
17159
- this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17861
+ if (span === void 0) this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
17862
+ else this.onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
17160
17863
  this.onBlockResolved?.(sbn, packetId, catalogTrackName);
17161
17864
  }
17162
17865
  /**
@@ -17185,7 +17888,9 @@ var FECManager = class _FECManager {
17185
17888
  this.#retireBlockClass(key, block.sbn, block.packetId, block.catalogTrackName);
17186
17889
  this.#blockSourceCounts.delete(key);
17187
17890
  this.#blockSourceEsis.delete(key);
17891
+ this.#blockRebuiltEsis.delete(key);
17188
17892
  this.#blockAuthoredLengths.delete(key);
17893
+ this.#isoSpanKeys.delete(key);
17189
17894
  this.#blockRepairRsIds.delete(key);
17190
17895
  this.#blockRsbLengths.delete(key);
17191
17896
  this.#clearBlockTimer(key);
@@ -17276,7 +17981,9 @@ var FECManager = class _FECManager {
17276
17981
  this.#blockKeysBySbn.clear();
17277
17982
  this.#blockSourceCounts.clear();
17278
17983
  this.#blockSourceEsis.clear();
17984
+ this.#blockRebuiltEsis.clear();
17279
17985
  this.#blockAuthoredLengths.clear();
17986
+ this.#isoSpanKeys.clear();
17280
17987
  this.#blockRepairRsIds.clear();
17281
17988
  this.#blockRsbLengths.clear();
17282
17989
  this.#heldLayerStates.clear();
@@ -17301,6 +18008,7 @@ var FECManager = class _FECManager {
17301
18008
  this.#blockAnchorsMs.clear();
17302
18009
  this.#blockCatalogTrackNames.clear();
17303
18010
  this.#classifiers.clear();
18011
+ this.#noSpanRaps.clear();
17304
18012
  this.#streamGeometries.clear();
17305
18013
  this.#failedBlocks.clear();
17306
18014
  this.#resolvedBlockClasses.clear();
@@ -17831,9 +18539,21 @@ var IsoBmffTimingResolver = class {
17831
18539
  }
17832
18540
  #track = null;
17833
18541
  #fragments = /* @__PURE__ */ new Map();
18542
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
18543
+ #firstSamples = /* @__PURE__ */ new Map();
18544
+ /**
18545
+ * First sample and sample count of the newest fragments whose every slot was
18546
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
18547
+ * matches the combiner, since it retires an abandoned sample as well.
18548
+ */
18549
+ #delivered = /* @__PURE__ */ new Map();
17834
18550
  #pendingSamples = 0;
17835
18551
  #evictedSamples = 0;
17836
18552
  #lastMovieFragmentRejection = null;
18553
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
18554
+ get initialized() {
18555
+ return this.#track !== null;
18556
+ }
17837
18557
  get pendingSampleCount() {
17838
18558
  return this.#pendingSamples;
17839
18559
  }
@@ -17857,7 +18577,14 @@ var IsoBmffTimingResolver = class {
17857
18577
  this.#track = timing;
17858
18578
  return true;
17859
18579
  }
17860
- addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples) {
18580
+ /**
18581
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
18582
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
18583
+ * fragment whose samples are all done is a duplicate: admitting it again
18584
+ * would charge stale timing and could displace the live MPU's. A source
18585
+ * copy is still admitted again (a rendition switch re-arms timing that way).
18586
+ */
18587
+ addMovieFragment(mpuSequenceNumber2, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
17861
18588
  this.#lastMovieFragmentRejection = null;
17862
18589
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
17863
18590
  this.#lastMovieFragmentRejection = "invalid";
@@ -17883,6 +18610,8 @@ var IsoBmffTimingResolver = class {
17883
18610
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
17884
18611
  );
17885
18612
  }
18613
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
18614
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
17886
18615
  let freed = 0;
17887
18616
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
17888
18617
  freed += this.#evictOldestFragment();
@@ -17896,6 +18625,7 @@ var IsoBmffTimingResolver = class {
17896
18625
  return false;
17897
18626
  }
17898
18627
  this.#fragments.set(key, [...parsed.samples]);
18628
+ this.#firstSamples.set(key, parsed.samples[0]);
17899
18629
  this.#pendingSamples += parsed.samples.length;
17900
18630
  return true;
17901
18631
  }
@@ -17953,6 +18683,7 @@ var IsoBmffTimingResolver = class {
17953
18683
  let live = 0;
17954
18684
  for (const sample of samples) if (sample !== null) live++;
17955
18685
  this.#fragments.delete(oldest);
18686
+ this.#firstSamples.delete(oldest);
17956
18687
  this.#pendingSamples -= live;
17957
18688
  this.#evictedSamples += live;
17958
18689
  return live;
@@ -17968,12 +18699,23 @@ var IsoBmffTimingResolver = class {
17968
18699
  if (!samples || !samples[index]) return false;
17969
18700
  samples[index] = null;
17970
18701
  this.#pendingSamples--;
17971
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
18702
+ if (samples.every((value) => value === null)) {
18703
+ this.#fragments.delete(key);
18704
+ const first = this.#firstSamples.get(key);
18705
+ this.#firstSamples.delete(key);
18706
+ this.#delivered.delete(key);
18707
+ this.#delivered.set(key, { first, sampleCount: samples.length });
18708
+ if (this.#delivered.size > this.maxPendingSamples) {
18709
+ this.#delivered.delete(this.#delivered.keys().next().value);
18710
+ }
18711
+ }
17972
18712
  return true;
17973
18713
  }
17974
18714
  reset() {
17975
18715
  this.#track = null;
17976
18716
  this.#fragments.clear();
18717
+ this.#firstSamples.clear();
18718
+ this.#delivered.clear();
17977
18719
  this.#pendingSamples = 0;
17978
18720
  }
17979
18721
  };
@@ -18143,6 +18885,9 @@ function authoredGap(before, after) {
18143
18885
  function ssIdAfter(a, b) {
18144
18886
  return (a - b | 0) > 0;
18145
18887
  }
18888
+ function holdsRebuilt(stream) {
18889
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
18890
+ }
18146
18891
  var FecReleaseSequencer = class {
18147
18892
  #streams = /* @__PURE__ */ new Map();
18148
18893
  #gate;
@@ -18205,6 +18950,7 @@ var FecReleaseSequencer = class {
18205
18950
  stream.lastSbn = void 0;
18206
18951
  stream.discontinuity = false;
18207
18952
  stream.rapSsId = void 0;
18953
+ stream.sourced = false;
18208
18954
  }
18209
18955
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
18210
18956
  this.#recordStat("droppedStale");
@@ -18231,6 +18977,7 @@ var FecReleaseSequencer = class {
18231
18977
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
18232
18978
  else hi = mid;
18233
18979
  }
18980
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
18234
18981
  stream.buf.splice(lo, 0, frame);
18235
18982
  this.#drainUnlessDeferred(stream);
18236
18983
  }
@@ -18266,6 +19013,41 @@ var FecReleaseSequencer = class {
18266
19013
  }
18267
19014
  return false;
18268
19015
  }
19016
+ /**
19017
+ * These streams' sink is being replaced by one that has seen no source
19018
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
19019
+ * release to the sink being replaced the frames the unanchored path had
19020
+ * already released to it (#cursorPassed): there they waited in its queue,
19021
+ * which its replacement flushes. A stream that holds none is not drained:
19022
+ * it holds nothing the anchor kept back, and a drain would still force out
19023
+ * a frame held past the hold limit, which before the anchor waited for the
19024
+ * next push. Then treat the streams as unsourced until a source frame is
19025
+ * released.
19026
+ */
19027
+ unsource(packetId, catalogTrackName) {
19028
+ for (const stream of this.#streams.values()) {
19029
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
19030
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
19031
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
19032
+ else this.#drain(stream, true);
19033
+ }
19034
+ stream.sourced = false;
19035
+ }
19036
+ }
19037
+ }
19038
+ /**
19039
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
19040
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
19041
+ * packetId.
19042
+ */
19043
+ holdsRebuilt(packetId, catalogTrackName) {
19044
+ for (const stream of this.#streams.values()) {
19045
+ if (stream.packetId !== packetId) continue;
19046
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
19047
+ if (holdsRebuilt(stream)) return true;
19048
+ }
19049
+ return false;
19050
+ }
18269
19051
  /** Re-evaluate held gaps after FEC state changed. */
18270
19052
  poke(streamKey) {
18271
19053
  if (streamKey !== void 0) {
@@ -18357,16 +19139,32 @@ var FecReleaseSequencer = class {
18357
19139
  last: null,
18358
19140
  lastSbn: void 0,
18359
19141
  discontinuity: false,
18360
- rapSsId: void 0
19142
+ rapSsId: void 0,
19143
+ sourced: false,
19144
+ draining: 0
18361
19145
  };
18362
19146
  this.#streams.set(streamKey, stream);
18363
19147
  }
18364
19148
  return stream;
18365
19149
  }
18366
- #drain(stream) {
19150
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
19151
+ #drain(stream, asUnanchored = false) {
19152
+ stream.draining++;
19153
+ try {
19154
+ this.#drainLoop(stream, asUnanchored);
19155
+ } finally {
19156
+ stream.draining--;
19157
+ }
19158
+ }
19159
+ #drainLoop(stream, asUnanchored) {
18367
19160
  while (stream.buf.length > 0 && stream.last !== null) {
18368
19161
  const head = stream.buf[0];
18369
19162
  const last = stream.last;
19163
+ if (compareFrameOrder(head, last) <= 0) {
19164
+ stream.buf.shift();
19165
+ this.#release(stream, head, void 0);
19166
+ continue;
19167
+ }
18370
19168
  if (stream.discontinuity) {
18371
19169
  stream.discontinuity = false;
18372
19170
  stream.buf.shift();
@@ -18380,9 +19178,10 @@ var FecReleaseSequencer = class {
18380
19178
  }
18381
19179
  const headSbn = head.meta.fecSbn;
18382
19180
  const from = stream.lastSbn ?? headSbn;
18383
- const to = headSbn ?? stream.lastSbn;
19181
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
18384
19182
  let lost = [];
18385
19183
  const unanchored = from === void 0 && to === void 0;
19184
+ let unresolved = false;
18386
19185
  if (from !== void 0 && to !== void 0) {
18387
19186
  const resolved = this.#gate.resolvedLoss(
18388
19187
  stream.packetId,
@@ -18391,7 +19190,8 @@ var FecReleaseSequencer = class {
18391
19190
  Math.max(from, to),
18392
19191
  from
18393
19192
  );
18394
- if (resolved === null) {
19193
+ unresolved = resolved === null;
19194
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
18395
19195
  const heldMs = performance.now() - head.arrivedAtMs;
18396
19196
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
18397
19197
  this.#recordStat("forcedWindowFlushes");
@@ -18399,22 +19199,69 @@ var FecReleaseSequencer = class {
18399
19199
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
18400
19200
  continue;
18401
19201
  }
18402
- lost = resolved;
19202
+ lost = resolved ?? [];
18403
19203
  }
18404
19204
  stream.buf.shift();
18405
19205
  this.#release(
18406
19206
  stream,
18407
19207
  head,
18408
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
19208
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
18409
19209
  );
18410
19210
  }
18411
19211
  }
19212
+ /**
19213
+ * The head has waited out a gap only a late source can still fill
19214
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
19215
+ * the stream when it has (`wakeAt`), since no packet may come by then.
19216
+ */
19217
+ #unrepairableWaitOver(stream, last, head, from, to) {
19218
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
19219
+ if (waitMs === void 0) return false;
19220
+ const atMs = head.arrivedAtMs + waitMs;
19221
+ if (performance.now() >= atMs) return true;
19222
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
19223
+ return false;
19224
+ }
19225
+ /**
19226
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
19227
+ * source cursor holds it unanchored, and neither does a later frame behind
19228
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
19229
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
19230
+ * like each frame that arrived in front of it since (stale there). The head
19231
+ * then goes, decided as it would be unanchored, once a frame the base path
19232
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
19233
+ * marked one: the base path has passed that one, so a frame still missing
19234
+ * before it can only come from a repair. It also goes while no source frame
19235
+ * has been released, when the direct path shows a recovered frame at once.
19236
+ * And it goes at once while a staged switch decides on when frames arrive
19237
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
19238
+ * sink being replaced: unanchored, it had already reached the sink.
19239
+ * The scan also writes: the `passed` marks it sets stay on the frames,
19240
+ * and push marks a frame it inserts in front of a marked one from them.
19241
+ */
19242
+ #cursorPassed(stream, asUnanchored) {
19243
+ let at2 = -1;
19244
+ for (let i = 0; i < stream.buf.length; i++) {
19245
+ const frame = stream.buf[i];
19246
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
19247
+ frame.passed = true;
19248
+ if (at2 < 0) at2 = i;
19249
+ } else if (frame.passed !== true) break;
19250
+ }
19251
+ if (at2 < 0) return false;
19252
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at2 && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
19253
+ }
18412
19254
  #release(stream, frame, decision) {
19255
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
19256
+ if (stale) this.#recordStat("droppedStale");
18413
19257
  if (decision) frame.meta.gapBefore = decision;
18414
19258
  stream.last = frame;
18415
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
19259
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
19260
+ stream.lastSbn = frame.meta.fecSbn;
19261
+ }
19262
+ if (frame.meta.recovered !== true) stream.sourced = true;
18416
19263
  this.#gate.onReleased?.(frame.data, frame.meta);
18417
- this.#emit(frame.data, frame.meta);
19264
+ if (!stale) this.#emit(frame.data, frame.meta);
18418
19265
  }
18419
19266
  };
18420
19267
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -18455,6 +19302,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18455
19302
  this.#reclaimedTimingSamples = 0;
18456
19303
  this.#evictedTimingSamples = 0;
18457
19304
  this.#rejectedMovieFragments = 0;
19305
+ this.#recoveredHeadsAwaitingTiming = {
19306
+ held: 0,
19307
+ expired: 0,
19308
+ discarded: 0,
19309
+ superseded: 0
19310
+ };
18458
19311
  this.#sequencers = /* @__PURE__ */ new Map();
18459
19312
  this.#fecGate = null;
18460
19313
  this.#fecSequencer = null;
@@ -18563,6 +19416,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18563
19416
  #reclaimedTimingSamples;
18564
19417
  #evictedTimingSamples;
18565
19418
  #rejectedMovieFragments;
19419
+ #recoveredHeadsAwaitingTiming;
18566
19420
  #sequencers;
18567
19421
  #fecGate;
18568
19422
  #fecSequencer;
@@ -18668,11 +19522,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
18668
19522
  /**
18669
19523
  * Typed view of the ISO-BMFF timing-sample budget.
18670
19524
  *
18671
- * This is the acceptance signal for the budget ratchet: `pending` walking
18672
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
18673
- * and it is observable here rather than only as media silently stopping.
18674
- * Per repo policy this is a producer-owned counter -- never infer budget
18675
- * state by parsing logs.
19525
+ * Each stream admits timing against its own window of `capacity` slots
19526
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
19527
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
19528
+ * timing a stream declared and never delivered shows up there. `pending`
19529
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
19530
+ * a producer-owned counter -- never infer budget state by parsing logs.
18676
19531
  */
18677
19532
  get timingBudgetStats() {
18678
19533
  return {
@@ -18683,6 +19538,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18683
19538
  rejectedMovieFragments: this.#rejectedMovieFragments
18684
19539
  };
18685
19540
  }
19541
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
19542
+ get recoveredHeadsAwaitingTiming() {
19543
+ let pending = 0;
19544
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
19545
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
19546
+ }
19547
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
19548
+ }
18686
19549
  get reorderStats() {
18687
19550
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
18688
19551
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -18724,6 +19587,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
18724
19587
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
18725
19588
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
18726
19589
  }
19590
+ /** See FecReleaseSequencer.unsource. */
19591
+ unsourceFecRelease(packetId, catalogTrackName) {
19592
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
19593
+ }
19594
+ /** See FecReleaseSequencer.holdsRebuilt. */
19595
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
19596
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
19597
+ }
18727
19598
  /** Re-evaluate held gaps after FEC block state changed. */
18728
19599
  pokeFecRelease(packetId, catalogTrackName) {
18729
19600
  if (!this.#fecSequencer) return;
@@ -18811,10 +19682,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
18811
19682
  get reassemblerDataUnitsReturned() {
18812
19683
  return this.#reassemblerDataUnitsReturned;
18813
19684
  }
18814
- #countOutcome(token) {
18815
- const count = (this.#feedOutcomes.get(token) ?? 0) + 1;
18816
- this.#feedOutcomes.set(token, count);
18817
- this.#lastOutcome = token;
19685
+ #countOutcome(token2) {
19686
+ const count = (this.#feedOutcomes.get(token2) ?? 0) + 1;
19687
+ this.#feedOutcomes.set(token2, count);
19688
+ this.#lastOutcome = token2;
18818
19689
  this.#lastOutcomeCount = count;
18819
19690
  }
18820
19691
  #countDeferredOutcome(reason) {
@@ -18856,7 +19727,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18856
19727
  const now = Date.now();
18857
19728
  for (const { awaitingTiming } of this.#timingStreams.values()) {
18858
19729
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
18859
- awaitingTiming.shift();
19730
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
18860
19731
  }
18861
19732
  }
18862
19733
  }
@@ -18974,11 +19845,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
18974
19845
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
18975
19846
  return this.#drop("fragment-unexpected-fragmentation");
18976
19847
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
18977
- if (!resolver2) return this.#drop("fragment-no-resolver");
19848
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
18978
19849
  const pendingBefore = resolver2.pendingSampleCount;
18979
19850
  const evictedBefore = resolver2.evictedSampleCount;
18980
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
18981
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
19851
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
19852
+ const admitted = resolver2.addMovieFragment(
19853
+ mpu.mpuSequenceNumber,
19854
+ data,
19855
+ remaining,
19856
+ options?.recovered === true
19857
+ );
18982
19858
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
18983
19859
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
18984
19860
  if (!admitted) {
@@ -18998,7 +19874,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
18998
19874
  };
18999
19875
  }
19000
19876
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
19001
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
19877
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
19002
19878
  if (!resolver) return this.#drop("mfu-no-resolver");
19003
19879
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
19004
19880
  return this.#drop("mfu-empty-payload");
@@ -19019,6 +19895,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19019
19895
  mpuSequenceNumber: mpu.mpuSequenceNumber,
19020
19896
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
19021
19897
  sampleNumber: mfuDuHeader.sampleNumber,
19898
+ sequenceNumber: info.sequenceNumber,
19022
19899
  arrivedAt: Date.now()
19023
19900
  });
19024
19901
  return this.#drop("mfu-sample-timing-missing");
@@ -19044,7 +19921,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19044
19921
  info,
19045
19922
  resolver,
19046
19923
  options?.recovered === true,
19047
- options?.fecSbn
19924
+ options?.fecSbn,
19925
+ options?.fecSbnFirst
19048
19926
  );
19049
19927
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
19050
19928
  }
@@ -19137,7 +20015,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
19137
20015
  info,
19138
20016
  resolver,
19139
20017
  options?.recovered === true,
19140
- options?.fecSbn
20018
+ options?.fecSbn,
20019
+ options?.fecSbnFirst
19141
20020
  );
19142
20021
  if (outcome.record !== void 0) return outcome.record;
19143
20022
  return this.#drop(outcome.reason);
@@ -19157,7 +20036,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19157
20036
  * attribution exists to keep readable. Leaving the choice at the call site
19158
20037
  * is what keeps both true.
19159
20038
  */
19160
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
20039
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
19161
20040
  const timing = resolver.sampleTiming(
19162
20041
  combined.mpuSequenceNumber,
19163
20042
  combined.movieFragmentSequenceNumber,
@@ -19174,6 +20053,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19174
20053
  );
19175
20054
  if (!meta) return { reason: "combined-meta-build-failed" };
19176
20055
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
20056
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
19177
20057
  if (!resolver.consumeSample(
19178
20058
  combined.mpuSequenceNumber,
19179
20059
  combined.movieFragmentSequenceNumber,
@@ -19342,6 +20222,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
19342
20222
  }
19343
20223
  this.#emitFrame(data, meta);
19344
20224
  }
20225
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
20226
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
20227
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber2, movieFragmentSequenceNumber, sampleNumber) != null;
20228
+ }
19345
20229
  /**
19346
20230
  * Claim and return the authored timing for a recovered sample. Recovery does
19347
20231
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -19403,6 +20287,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
19403
20287
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
19404
20288
  this.#sequencers.clear();
19405
20289
  this.#fecSequencer?.discard();
20290
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
20291
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
20292
+ }
19406
20293
  this.#timingStreams.clear();
19407
20294
  this.#pendingTimingSamples = 0;
19408
20295
  this.#reliableMoqStartupGate.clear();
@@ -19421,10 +20308,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
19421
20308
  return resolver;
19422
20309
  }
19423
20310
  #awaitTiming(streamKey, head) {
19424
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
19425
- if (!awaitingTiming) return;
20311
+ const state = this.#timingStreams.get(streamKey);
20312
+ if (!state) return;
20313
+ if (!head.options?.recovered) {
20314
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
20315
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
20316
+ state.awaitingTiming = kept;
20317
+ }
20318
+ const awaitingTiming = state.awaitingTiming;
19426
20319
  awaitingTiming.push(head);
19427
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
20320
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
20321
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
20322
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
20323
+ }
20324
+ }
20325
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
20326
+ #leaveAwaitingTiming(head, outcome) {
20327
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
19428
20328
  }
19429
20329
  /**
19430
20330
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -19452,6 +20352,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
19452
20352
  const state = this.#timingStreams.get(streamKey);
19453
20353
  if (!state) return;
19454
20354
  this.#timingStreams.delete(streamKey);
20355
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
19455
20356
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
19456
20357
  if (this.#pendingTimingSamples < 0) {
19457
20358
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -22658,7 +23559,18 @@ function keyframeOverlaySsId(header) {
22658
23559
  if (ext?.type !== KEYFRAME_OVERLAY_EXTENSION_TYPE || ext.data.length !== 4) return void 0;
22659
23560
  return new DataView(ext.data.buffer, ext.data.byteOffset, 4).getUint32(0);
22660
23561
  }
23562
+ function overlayBaseSsId(anchor, overlaySsId, restoredPsn, headerPsn) {
23563
+ if (anchor.baseSsId === void 0 || headerPsn !== restoredPsn) return void 0;
23564
+ return serial32Add(anchor.baseSsId, overlaySsId - anchor.overlaySsId | 0);
23565
+ }
23566
+ function unstampedBaseSsId(offset, unstampedOffset, headerPsn) {
23567
+ if (offset === void 0 || offset !== unstampedOffset) return void 0;
23568
+ return headerPsn + offset >>> 0;
23569
+ }
23570
+ var OVERLAY_ROUTED_LIMIT = 1024;
23571
+ var OVERLAY_PENDING_LIMIT = 256;
22661
23572
  var OVERLAY_OFFSET_MPUS = 16;
23573
+ var OVERLAY_REBUILT_LIMIT = 256;
22662
23574
  var OVERLAY_MOQ_HORIZON_BLOCKS = 64;
22663
23575
  function assertStreamIdentity(role, stream) {
22664
23576
  if (stream === void 0 || !Number.isInteger(stream.packetId) || stream.packetId <= MMTP_SIGNALING_PACKET_ID || typeof stream.catalogTrackName !== "string" || stream.catalogTrackName.length === 0) {
@@ -22769,6 +23681,7 @@ var MmtpRouter = class {
22769
23681
  #provenance = /* @__PURE__ */ new Map();
22770
23682
  #onFlowProtected = null;
22771
23683
  #unadmittedListedDrops = 0;
23684
+ #admittedSourceDatagrams = 0;
22772
23685
  #unlistedRepairSetAside = 0;
22773
23686
  #assistBlocks = /* @__PURE__ */ new Map();
22774
23687
  #assistFailures = /* @__PURE__ */ new Map();
@@ -22825,6 +23738,26 @@ var MmtpRouter = class {
22825
23738
  * sequence is its SS_ID minus this; see #routeProcessedFecSymbols.
22826
23739
  */
22827
23740
  #ssIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23741
+ /**
23742
+ * Per stream, the SS_ID offset at which a base recovery last showed the
23743
+ * sender's own packet_sequence_number: a recovered packet's header psn
23744
+ * equal to its SS_ID minus that offset. While it equals the stream's
23745
+ * current offset, no hop re-stamps the stream, and a packet's protected psn
23746
+ * names its base SS_ID within unstampedBaseSsId's limits (joint decoding of
23747
+ * an MPU no member of which arrived).
23748
+ */
23749
+ #unstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
23750
+ /**
23751
+ * The same, shown by the overlay alone, before any base recovery did: a
23752
+ * packet it rebuilt whose base copy carries its protected psn
23753
+ * (#feedOverlaySource), or whose protected psn passes overlayBaseSsId's
23754
+ * test at that offset (#routeOverlayRecovered). A base SS_ID placed by it
23755
+ * anchors the release gate only (BLO-52085 D3): fed to the base, it would
23756
+ * make the base drop a late base copy of a keyframe the overlay never
23757
+ * finished, and lift a block's late-source cut, which nothing before
23758
+ * this offset did.
23759
+ */
23760
+ #overlayUnstampedSsIdSeqOffsetByStream = /* @__PURE__ */ new Map();
22828
23761
  /**
22829
23762
  * Streams whose multicast leg delivered a RAP-flagged source packet that was
22830
23763
  * not parsed, typically because its overlap copy was parsed first
@@ -22870,6 +23803,8 @@ var MmtpRouter = class {
22870
23803
  // end: a synchronous recovery completes its block BEFORE routing the
22871
23804
  // recovered frames, and releasing a held gap in between would strand them.
22872
23805
  #fecPokeDepth = 0;
23806
+ /** FecReleaseGate.wakeAt timers, by media stream key. */
23807
+ #fecWakes = /* @__PURE__ */ new Map();
22873
23808
  #pendingFecPokes = /* @__PURE__ */ new Map();
22874
23809
  // ── Phase 14: per-role packetId dispatch (D-26, D-27, D-28) ───────
22875
23810
  /** Maps packetId → TrackRole. Default: 'single' when absent (legacy path). */
@@ -22894,7 +23829,9 @@ var MmtpRouter = class {
22894
23829
  recovered: 0,
22895
23830
  restarts: 0,
22896
23831
  unsequencedDropped: 0,
22897
- protectedDropped: 0
23832
+ protectedDropped: 0,
23833
+ baseFed: 0,
23834
+ baseUndetermined: 0
22898
23835
  };
22899
23836
  /** Callback fired when a delta-track FEC block completes or fails. */
22900
23837
  #onDeltaBlockCompleteCb = null;
@@ -23067,7 +24004,7 @@ var MmtpRouter = class {
23067
24004
  const cb = this.#getFrameCallback(packetId);
23068
24005
  if (isVideo && !assembler) {
23069
24006
  if (frameMeta.recovered) {
23070
- this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb);
24007
+ this.#routeDirectRecoveredVideo(packetId, data, frameMeta, cb, meta.fecSbn);
23071
24008
  } else {
23072
24009
  this.#routeDirectSourceVideo(packetId, data, frameMeta, cb);
23073
24010
  }
@@ -23100,13 +24037,18 @@ var MmtpRouter = class {
23100
24037
  this.#onDeltaBlockCompleteCb?.(packetId, false);
23101
24038
  }
23102
24039
  };
23103
- this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass) => {
24040
+ this.#fecManager.onBlockFailed = (sbn, packetId, catalogTrackName, blockClass, span) => {
23104
24041
  this.#mseAssemblerFor(packetId, catalogTrackName)?.failBlock(sbn);
23105
24042
  if (this.#isCatalogTrackUnambiguous(packetId, catalogTrackName) && this.#packetIdRoles.get(packetId) === "delta") {
23106
24043
  this.#onDeltaBlockCompleteCb?.(packetId, true);
23107
24044
  }
23108
- onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
23109
- this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24045
+ if (span === void 0) {
24046
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24047
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass);
24048
+ } else {
24049
+ onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
24050
+ this.#onBlockFailed?.(sbn, packetId, catalogTrackName, blockClass, span);
24051
+ }
23110
24052
  };
23111
24053
  }
23112
24054
  }
@@ -23151,8 +24093,9 @@ var MmtpRouter = class {
23151
24093
  }
23152
24094
  /**
23153
24095
  * FEC-recovered source symbols whose reconstructed header named a
23154
- * packet_sequence_number other than the wire sequence their SS_ID maps to:
23155
- * a hop re-stamped the sequence after the sender protected the packet.
24096
+ * packet_sequence_number other than the wire sequence their SS_ID maps to,
24097
+ * or, rebuilt by the overlay, than their base copy carries: a hop
24098
+ * re-stamped the sequence after the sender protected the packet.
23156
24099
  */
23157
24100
  get restampedRecoveredSequenceCount() {
23158
24101
  return this.#restampedRecoveredSeqs;
@@ -23331,6 +24274,7 @@ var MmtpRouter = class {
23331
24274
  enableMseAssembler(packetId, config, catalogTrackName) {
23332
24275
  const assemblerKey = this.#mseAssemblerKey(packetId, catalogTrackName);
23333
24276
  const previous = this.#mseAssemblers.get(assemblerKey);
24277
+ this.#parser.unsourceFecRelease(packetId, catalogTrackName);
23334
24278
  if (previous) {
23335
24279
  previous.flush();
23336
24280
  previous.dispose();
@@ -23457,6 +24401,10 @@ var MmtpRouter = class {
23457
24401
  get keyframeOverlayStats() {
23458
24402
  return { ...this.#overlayStats };
23459
24403
  }
24404
+ /** Recovered FT=2 heads held for their FT=1, and how each left the wait (BLO-53369). */
24405
+ get recoveredHeadsAwaitingTiming() {
24406
+ return this.#parser.recoveredHeadsAwaitingTiming;
24407
+ }
23460
24408
  #isOverlayRepair(repairPacketId, repairTrackName) {
23461
24409
  return this.#overlayLegs.has(repairPacketId) || repairTrackName !== void 0 && this.#overlayRepairNames.has(repairTrackName);
23462
24410
  }
@@ -23477,7 +24425,8 @@ var MmtpRouter = class {
23477
24425
  fec,
23478
24426
  k,
23479
24427
  offsets: /* @__PURE__ */ new Map(),
23480
- moqBlocks: /* @__PURE__ */ new Set()
24428
+ moqBlocks: /* @__PURE__ */ new Set(),
24429
+ rebuilt: /* @__PURE__ */ new Map()
23481
24430
  };
23482
24431
  this.#overlays.set(repairPacketId, inst);
23483
24432
  return () => {
@@ -23507,12 +24456,18 @@ var MmtpRouter = class {
23507
24456
  */
23508
24457
  resetKeyframeOverlays(sourcePacketId, catalogTrackName) {
23509
24458
  for (const inst of this.#overlaysForSource(sourcePacketId, catalogTrackName)) this.#resetOverlay(inst);
24459
+ for (const [name, stream] of this.#streams.get(sourcePacketId) ?? []) {
24460
+ if (catalogTrackName !== void 0 && name !== catalogTrackName) continue;
24461
+ stream.overlayToBase.routed.clear();
24462
+ stream.overlayToBase.pending.clear();
24463
+ }
23510
24464
  }
23511
24465
  #resetOverlay(inst) {
23512
24466
  inst.fec.resetTrack(inst.repairPacketId, inst.streamName);
23513
24467
  inst.last = void 0;
23514
24468
  inst.offsets.clear();
23515
24469
  inst.moqBlocks.clear();
24470
+ inst.rebuilt.clear();
23516
24471
  }
23517
24472
  #overlaysForSource(sourcePacketId, catalogTrackName) {
23518
24473
  return [...this.#overlays.values()].filter(({ leg }) => leg.sourcePacketId === sourcePacketId && (catalogTrackName === void 0 || leg.sourceCatalogTrackName === void 0 || leg.sourceCatalogTrackName === catalogTrackName));
@@ -23563,18 +24518,33 @@ var MmtpRouter = class {
23563
24518
  * A source packet that carries a 0x8B01 overlay SS_ID is also a symbol of
23564
24519
  * every overlay installed for its source, at that SS_ID, with the bytes the
23565
24520
  * base protects: the packet minus its 4-byte SS_ID trailer, extension
23566
- * included (7.1, 7.4.3).
23567
- */
23568
- #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source) {
24521
+ * included (7.1, 7.4.3). `baseSsId` is that trailer's SS_ID, when the base
24522
+ * FEC reads it.
24523
+ *
24524
+ * The base copy of a packet an overlay rebuilt with no base SS_ID shows
24525
+ * what a base recovery of it would (#routeProcessedFecSymbols, BLO-52085):
24526
+ * its wire packet_sequence_number equal to the protected one rebuilt shows
24527
+ * the stream unstamped at the SS_ID offset it states, for the release gate
24528
+ * (#overlayUnstampedSsIdSeqOffsetByStream); any other shows a hop that
24529
+ * re-stamps it, which is counted (restampedRecoveredSequenceCount).
24530
+ */
24531
+ #feedOverlaySource(packetId, catalogTrackName, packet, header, sequenceNumber, rapFlag, source, baseSsId) {
23569
24532
  if (this.#overlays.size === 0) return;
23570
24533
  const ssId = keyframeOverlaySsId(header);
23571
24534
  if (ssId === void 0) return;
24535
+ let rebuiltPsn;
23572
24536
  for (const inst of this.#overlaysForSource(packetId, catalogTrackName)) {
23573
24537
  this.#noteOverlaySsId(inst, ssId, sequenceNumber);
24538
+ rebuiltPsn ??= inst.rebuilt.get(ssId);
24539
+ inst.rebuilt.delete(ssId);
23574
24540
  const identity = MmtpContainerParser.sourcePacketIdentity(packet, header);
23575
24541
  if (identity !== null) {
23576
24542
  inst.offsets.delete(identity.mpuSequenceNumber);
23577
- inst.offsets.set(identity.mpuSequenceNumber, ssId - sequenceNumber >>> 0);
24543
+ inst.offsets.set(identity.mpuSequenceNumber, {
24544
+ psnOffset: ssId - sequenceNumber >>> 0,
24545
+ overlaySsId: ssId,
24546
+ ...baseSsId === void 0 ? {} : { baseSsId }
24547
+ });
23578
24548
  if (inst.offsets.size > OVERLAY_OFFSET_MPUS) inst.offsets.delete(inst.offsets.keys().next().value);
23579
24549
  }
23580
24550
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23596,6 +24566,14 @@ var MmtpRouter = class {
23596
24566
  const recovered = fec.feedSourceSymbol(pid, ssId, symbolData, name);
23597
24567
  if (recovered && !alreadyCompleted) this.#routeOverlayRecovered(inst, coords.sbn, recovered);
23598
24568
  }
24569
+ if (rebuiltPsn === void 0 || this.#classifyPacketId(packetId) === null) return;
24570
+ const streamKey = this.#mediaStreamKey(packetId, catalogTrackName);
24571
+ if (rebuiltPsn !== sequenceNumber) {
24572
+ this.#restampedRecoveredSeqs++;
24573
+ } else if (baseSsId !== void 0) {
24574
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24575
+ if (offset === baseSsId - sequenceNumber >>> 0) this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24576
+ }
23599
24577
  }
23600
24578
  #noteOverlayMoqBlock(inst, blockStart) {
23601
24579
  inst.moqBlocks.add(blockStart);
@@ -23629,11 +24607,16 @@ var MmtpRouter = class {
23629
24607
  }
23630
24608
  /**
23631
24609
  * Route an overlay-recovered block's packets as source media of the
23632
- * overlay's source (7.2: an overlay coordinate yields no base SS_ID). No
23633
- * base-SS_ID derivation runs: no release-gate anchor, no parse ledger, no
23634
- * base re-stamp, no block advance. Each packet's wire sequence is restored
23635
- * from its keyframe's own offset; without one, a stream the base never
23636
- * re-stamped keeps the header's sequence and any other drops the packet.
24610
+ * overlay's source (7.2: an overlay coordinate yields no base SS_ID). A
24611
+ * packet whose base SS_ID is determined independently (overlayBaseSsId,
24612
+ * unstampedBaseSsId) enters the release gate at that SS_ID, as a packet
24613
+ * base FEC recovered does, so it waits behind base frames still in flight,
24614
+ * though not for its own MPU's packets (FrameMeta.fecSbnFirst) and no
24615
+ * longer than unanchored; one whose base SS_ID is undetermined has no
24616
+ * release-gate anchor. No parse ledger, no base re-stamp, no block
24617
+ * advance. Each packet's wire sequence is restored from its keyframe's own
24618
+ * offset; without one, a stream the base never re-stamped keeps the
24619
+ * header's sequence and any other drops the packet.
23637
24620
  */
23638
24621
  #routeOverlayRecovered(inst, blockStart, recovered) {
23639
24622
  const { fec, repairPacketId: pid, streamName: name } = inst;
@@ -23653,22 +24636,139 @@ var MmtpRouter = class {
23653
24636
  const streamKey = this.#mediaStreamKey(sourcePacketId, sourceName);
23654
24637
  const restamped = this.#restampedStreams.has(streamKey);
23655
24638
  const restored = /* @__PURE__ */ new Set();
24639
+ const baseSsIds = /* @__PURE__ */ new Map();
24640
+ const gateOnly = /* @__PURE__ */ new Set();
23656
24641
  const symbols = result.symbols.flatMap((sym) => {
23657
- const offset = inst.offsets.get(sym.fragment.mpuSequenceNumber);
23658
- if (offset !== void 0) {
23659
- const packetSequenceNumber = serial32Add(blockStart, sym.index) - offset >>> 0;
24642
+ const overlaySsId = serial32Add(blockStart, sym.index);
24643
+ const anchor = inst.offsets.get(sym.fragment.mpuSequenceNumber);
24644
+ if (anchor !== void 0) {
24645
+ const packetSequenceNumber = overlaySsId - anchor.psnOffset >>> 0;
23660
24646
  restored.add(packetSequenceNumber);
23661
- return [{ ...sym, packetSequenceNumber }];
24647
+ const out = { ...sym, packetSequenceNumber };
24648
+ const baseSsId = overlayBaseSsId(anchor, overlaySsId, packetSequenceNumber, sym.packetSequenceNumber);
24649
+ if (baseSsId !== void 0) {
24650
+ baseSsIds.set(sym.index, baseSsId);
24651
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24652
+ if (!this.#sourceSeqReceived(sourcePacketId, packetSequenceNumber, sourceName) && offset === baseSsId - packetSequenceNumber >>> 0) {
24653
+ this.#overlayUnstampedSsIdSeqOffsetByStream.set(streamKey, offset);
24654
+ }
24655
+ }
24656
+ return [out];
24657
+ }
24658
+ if (!restamped) {
24659
+ const offset = this.#ssIdSeqOffsetByStream.get(streamKey);
24660
+ const fedSsId = unstampedBaseSsId(offset, this.#unstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24661
+ const baseSsId = fedSsId ?? unstampedBaseSsId(offset, this.#overlayUnstampedSsIdSeqOffsetByStream.get(streamKey), sym.packetSequenceNumber);
24662
+ if (baseSsId !== void 0) {
24663
+ baseSsIds.set(sym.index, baseSsId);
24664
+ if (fedSsId === void 0) gateOnly.add(sym.index);
24665
+ } else {
24666
+ inst.rebuilt.set(overlaySsId, sym.packetSequenceNumber);
24667
+ if (inst.rebuilt.size > OVERLAY_REBUILT_LIMIT) inst.rebuilt.delete(inst.rebuilt.keys().next().value);
24668
+ }
24669
+ return [sym];
23662
24670
  }
23663
- if (!restamped) return [sym];
23664
24671
  this.#overlayStats.unsequencedDropped++;
23665
24672
  return [];
23666
24673
  });
23667
24674
  this.#overlayStats.recovered++;
24675
+ const mpuFirst = /* @__PURE__ */ new Map();
24676
+ for (const sym of symbols) {
24677
+ const ssId = baseSsIds.get(sym.index);
24678
+ const mpu = sym.fragment.mpuSequenceNumber;
24679
+ const first = mpuFirst.get(mpu);
24680
+ if (ssId !== void 0 && (first === void 0 || serial32Precedes(ssId, first))) mpuFirst.set(mpu, ssId);
24681
+ }
24682
+ const firstSsIds = /* @__PURE__ */ new Map();
24683
+ for (const sym of symbols) {
24684
+ if (baseSsIds.has(sym.index)) firstSsIds.set(sym.index, mpuFirst.get(sym.fragment.mpuSequenceNumber));
24685
+ }
23668
24686
  this.#routeProcessedFecSymbols(blockStart, { ...result, symbols }, sourcePacketId, sourceName, {
23669
- deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast"
24687
+ deliveryProvenance: inst.moqBlocks.has(blockStart) ? "mixed" : "multicast",
24688
+ baseSsIds,
24689
+ firstSsIds
23670
24690
  });
23671
24691
  this.#noteOverlayRecoveredRaps(sourcePacketId, sourceName, streamKey, symbols.filter((sym) => restored.has(sym.packetSequenceNumber)));
24692
+ this.#feedOverlayRecoveredToBase(inst, blockStart, symbols, gateOnly.size === 0 ? baseSsIds : new Map([...baseSsIds].filter(([index]) => !gateOnly.has(index))));
24693
+ }
24694
+ /**
24695
+ * Joint decoding (BLO-52085). A packet the overlay rebuilt is a source of
24696
+ * its base block too, once its base SS_ID is determined (overlayBaseSsId,
24697
+ * from a received member of its MPU, else unstampedBaseSsId at an offset a
24698
+ * base recovery showed; `baseSsIds` holds no other),
24699
+ * so it is fed to the base decoder as a rebuilt source
24700
+ * (FECManager.feedRebuiltSourceSymbol): the base block has one erasure
24701
+ * fewer to solve, and its repair can recover the block's other packets.
24702
+ * A base block no repair has stated yet takes it when one does
24703
+ * (#feedPendingRebuilt).
24704
+ *
24705
+ * The overlay route already handled each packet fed (delivered it, or
24706
+ * held an untimed head for its FT=1), so a base recovery routes none of
24707
+ * them again (#routeVerifiedFecSymbols): a second recovered copy of a
24708
+ * held head would wait in the parser for timing its first copy consumed.
24709
+ * Only an overlay block decoded from multicast symbols alone is fed: with
24710
+ * a MoQ symbol in it, the base block's recovery would depend on bytes
24711
+ * that crossed no multicast socket, which the provenance counted from the
24712
+ * block's own arrivals cannot show.
24713
+ */
24714
+ #feedOverlayRecoveredToBase(inst, blockStart, symbols, baseSsIds) {
24715
+ const fec = this.#fecManager;
24716
+ const owner = inst.leg.sourcePacketId;
24717
+ const name = inst.leg.sourceCatalogTrackName;
24718
+ if (!fec?.feedRebuiltSourceSymbol || inst.moqBlocks.has(blockStart)) return;
24719
+ if (this.#classifyPacketId(owner) === null || fec.isTrackConfigured?.(owner) === false) return;
24720
+ const { duplicates, overlayToBase: { routed } } = this.#stream(owner, name);
24721
+ const feeds = [];
24722
+ for (const sym of symbols) {
24723
+ if (duplicates.sourceSeqs.has(sym.packetSequenceNumber)) continue;
24724
+ const ssId = baseSsIds.get(sym.index);
24725
+ if (ssId === void 0) {
24726
+ this.#overlayStats.baseUndetermined++;
24727
+ continue;
24728
+ }
24729
+ routed.delete(ssId);
24730
+ routed.add(ssId);
24731
+ if (routed.size > OVERLAY_ROUTED_LIMIT) routed.delete(routed.values().next().value);
24732
+ feeds.push([ssId, sym.rawSymbol]);
24733
+ }
24734
+ for (const [ssId, symbolData] of feeds) {
24735
+ if (this.#classifyPacketId(owner) === null) return;
24736
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24737
+ }
24738
+ }
24739
+ /** Feed one rebuilt source to its base block, or keep it until a repair states that block. */
24740
+ #feedRebuiltToBase(owner, name, ssId, symbolData) {
24741
+ const fec = this.#fecManager;
24742
+ if (!fec?.feedRebuiltSourceSymbol) return;
24743
+ const coords = fec.locateIsoSource?.(owner, name, ssId);
24744
+ if (coords == null) {
24745
+ const pending = this.#stream(owner, name).overlayToBase.pending;
24746
+ pending.delete(ssId);
24747
+ pending.set(ssId, symbolData.slice());
24748
+ if (pending.size > OVERLAY_PENDING_LIMIT) pending.delete(pending.keys().next().value);
24749
+ return;
24750
+ }
24751
+ const fed = fec.feedRebuiltSourceSymbol(owner, ssId, symbolData, name);
24752
+ if (!fed.taken) return;
24753
+ this.#overlayStats.baseFed++;
24754
+ if (fed.recovered === null) return;
24755
+ const sbn = coords.sbn;
24756
+ this.#routeRecoveredBlock(sbn, fed.recovered, owner, name, () => {
24757
+ fec.cancelBlockTimeout(sbn, owner, name);
24758
+ fec.countRecovery(owner, sbn, name);
24759
+ fec.markBlockCompleted(sbn, owner, name);
24760
+ });
24761
+ }
24762
+ /** A repair stated `block`: the rebuilt sources that waited for it join it now. */
24763
+ #feedPendingRebuilt(owner, name, block) {
24764
+ const pending = this.#streams.get(owner)?.get(name)?.overlayToBase.pending;
24765
+ if (pending === void 0 || pending.size === 0) return;
24766
+ for (const [ssId, symbolData] of [...pending]) {
24767
+ if (this.#classifyPacketId(owner) === null) return;
24768
+ if (serial32Distance(block.start, ssId) >= block.length) continue;
24769
+ pending.delete(ssId);
24770
+ this.#feedRebuiltToBase(owner, name, ssId, symbolData);
24771
+ }
23672
24772
  }
23673
24773
  /** fec-multicast-00 §6.6: report each base block whose RAP MFU fragments
23674
24774
  * the overlay restored, when the keyframe's FT=0 and FT=1 are held too. A
@@ -23808,6 +24908,10 @@ var MmtpRouter = class {
23808
24908
  get unadmittedListedDropCount() {
23809
24909
  return this.#unadmittedListedDrops;
23810
24910
  }
24911
+ /** Source datagrams (multicast or MoQ) a protected flow's bc-provenance v2 receiver released: admitted at once or held, then admitted by a record. Repair symbols and user-agent-admitted datagrams are not counted. Counted at release, before this router's own track checks: a released datagram those drop, which only a track change between hold and release can cause, still counts, so this is not a count of routed media. */
24912
+ get admittedSourceDatagramCount() {
24913
+ return this.#admittedSourceDatagrams;
24914
+ }
23811
24915
  /** MoQ repair symbols of an unlisted track kept out of a governed FEC instance (7.2.7 step 2). */
23812
24916
  get unlistedRepairSetAsideCount() {
23813
24917
  return this.#unlistedRepairSetAside;
@@ -24294,6 +25398,8 @@ var MmtpRouter = class {
24294
25398
  )) return;
24295
25399
  fec.noteBlockActivity?.(blockStart, ownerPacketId, catalogTrackName);
24296
25400
  fec.noteRepairGroupLength?.(blockStart, ownerPacketId, repair.rsbLength, catalogTrackName);
25401
+ this.#feedPendingRebuilt(ownerPacketId, catalogTrackName, placement.block);
25402
+ if (this.#classifyPacketId(ownerPacketId) === null) return;
24297
25403
  const alreadyCompleted = fec.isBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
24298
25404
  const recovered = fec.feedRepairSymbol(
24299
25405
  ownerPacketId,
@@ -24344,7 +25450,7 @@ var MmtpRouter = class {
24344
25450
  catalogTrackName
24345
25451
  )) continue;
24346
25452
  if (fec.isTrackConfigured?.(ownerPacketId) !== false) {
24347
- fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence);
25453
+ fec.trackBlock(blockStart, ownerPacketId, catalogTrackName, esi, payload.evidence, true);
24348
25454
  this.#requestFecPoke(ownerPacketId, catalogTrackName);
24349
25455
  }
24350
25456
  if (payload.oversized) continue;
@@ -24431,6 +25537,8 @@ var MmtpRouter = class {
24431
25537
  this.#droppedPreSyncVideo.delete(streamKey);
24432
25538
  this.#latestVideoSeqByStream.delete(streamKey);
24433
25539
  this.#ssIdSeqOffsetByStream.delete(streamKey);
25540
+ this.#unstampedSsIdSeqOffsetByStream.delete(streamKey);
25541
+ this.#overlayUnstampedSsIdSeqOffsetByStream.delete(streamKey);
24434
25542
  this.#multicastRapTwinByStream.delete(streamKey);
24435
25543
  this.#lastDirectSourceVideoTsByStream.delete(streamKey);
24436
25544
  this.#lastDirectEmittedVideoTsByStream.delete(streamKey);
@@ -24557,6 +25665,12 @@ var MmtpRouter = class {
24557
25665
  * the outgoing stream stops. The hold is bounded by the incoming stream's
24558
25666
  * own RAP cadence, so no timer is involved.
24559
25667
  *
25668
+ * While the switch is staged, the FEC release gate lets a keyframe the
25669
+ * overlay rebuilt reach it, on either side, when the keyframe did before
25670
+ * the gate anchored it (FecReleaseGate.releaseUnanchored): the switch
25671
+ * decides on what each side delivered, and the commit discards the gate's
25672
+ * frames of the outgoing stream.
25673
+ *
24560
25674
  * The commit is one synchronous transition inside the frame path: the
24561
25675
  * outgoing stream's already-admitted frames are released (its queued FEC
24562
25676
  * gap fills only up to the RAP, since recovery can queue a frame ahead of
@@ -24607,6 +25721,9 @@ var MmtpRouter = class {
24607
25721
  droppedIncomingFrames: 0
24608
25722
  };
24609
25723
  this.#staged = state;
25724
+ if (this.#parser.fecReleaseHoldsRebuilt(from.packetId, from.catalogTrackName)) {
25725
+ this.#requestFecPoke(from.packetId, from.catalogTrackName);
25726
+ }
24610
25727
  return {
24611
25728
  cancel: () => {
24612
25729
  if (this.#staged !== state) return false;
@@ -24689,7 +25806,17 @@ var MmtpRouter = class {
24689
25806
  */
24690
25807
  #routeParsedFrame(data, meta) {
24691
25808
  if (this.#classifyPacketId(meta.packetId) === null) return;
24692
- if (this.#staged !== null && this.#interceptSwitchFrame(data, meta)) return;
25809
+ if (this.#staged !== null) {
25810
+ let consumed = false;
25811
+ this.#fecPokeDepth++;
25812
+ try {
25813
+ consumed = this.#interceptSwitchFrame(data, meta);
25814
+ } finally {
25815
+ this.#fecPokeDepth--;
25816
+ this.#flushPendingFecPokes();
25817
+ }
25818
+ if (consumed) return;
25819
+ }
24693
25820
  this.#deliverParsedFrame(data, meta);
24694
25821
  }
24695
25822
  #commitStreamSwitch(state, rap, reason) {
@@ -24738,6 +25865,8 @@ var MmtpRouter = class {
24738
25865
  this.#disposed = true;
24739
25866
  this.#staged = null;
24740
25867
  this.cancelKeyframeLostTimer();
25868
+ for (const { timer } of this.#fecWakes.values()) clearTimeout(timer);
25869
+ this.#fecWakes.clear();
24741
25870
  this.#parser.dispose();
24742
25871
  this.#streams.clear();
24743
25872
  this.#trackPacketCallbacks.clear();
@@ -24841,12 +25970,16 @@ var MmtpRouter = class {
24841
25970
  this.#parser.deferFecRelease(work);
24842
25971
  } finally {
24843
25972
  this.#fecPokeDepth--;
24844
- if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
24845
- const pokes = [...this.#pendingFecPokes.values()];
24846
- this.#pendingFecPokes.clear();
24847
- for (const poke of pokes) {
24848
- this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24849
- }
25973
+ this.#flushPendingFecPokes();
25974
+ }
25975
+ }
25976
+ /** Run the pokes requested while #fecPokeDepth was raised, once it is 0. */
25977
+ #flushPendingFecPokes() {
25978
+ if (this.#fecPokeDepth === 0 && this.#pendingFecPokes.size > 0 && !this.#disposed) {
25979
+ const pokes = [...this.#pendingFecPokes.values()];
25980
+ this.#pendingFecPokes.clear();
25981
+ for (const poke of pokes) {
25982
+ this.#parser.pokeFecRelease(poke.packetId, poke.catalogTrackName);
24850
25983
  }
24851
25984
  }
24852
25985
  }
@@ -24915,6 +26048,31 @@ var MmtpRouter = class {
24915
26048
  if (!fec?.terminalRetentionMsForPacket) return Infinity;
24916
26049
  return fec.terminalRetentionMsForPacket(packetId) ?? 0;
24917
26050
  },
26051
+ // Once no repair can fill a gap (FECManager.isoRepairlessWaitMs: only a
26052
+ // late source can), its frame waits the late-symbol allowance when the
26053
+ // gap holds no RAP an installed keyframe overlay could still rebuild:
26054
+ // lost deltas of one MPU (delta-lost), the tail of the MPU before a RAP
26055
+ // that opens the next one while MPU boundaries bound RAPs (rap-next,
26056
+ // unless the gap holds a stated block's loss: the overlay may rebuild
26057
+ // that MPU's FT=0, and the block's group then complete it), or
26058
+ // an audio gap. A gap that may hold one (rap-lost, rap-unknown, or any
26059
+ // other rap-next, whose gap may hold a whole MPU and the keyframe the
26060
+ // overlay protects) waits for that overlay's repair too (BLO-52085
26061
+ // D4). The FEC check comes first: most held gaps are not behind such a
26062
+ // span, and deciding one scans both frames' bitstreams.
26063
+ unrepairableWaitMs: (before, after, fromSbn, toSbn) => {
26064
+ const fec = this.#fecManager;
26065
+ const { packetId, catalogTrackName } = after.meta;
26066
+ const allowanceMs = fec?.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn);
26067
+ if (!fec || allowanceMs === void 0) return void 0;
26068
+ const decision = this.#decideGap(before, after, [], false);
26069
+ const mpu = before.meta.mpuSequenceNumber;
26070
+ const intoNextMpu = decision.reason === "rap-next" && mpu !== void 0 && after.meta.mpuSequenceNumber === mpu + 1 >>> 0 && fec.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
26071
+ if (decision.action === "stall" || decision.reason === "rap-next" && !intoNextMpu) {
26072
+ return fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, true);
26073
+ }
26074
+ return decision.reason === "rap-next" ? fec.isoRepairlessWaitMs?.(packetId, catalogTrackName, fromSbn, toSbn, false, true) : allowanceMs;
26075
+ },
24918
26076
  decide: (before, after, lostBlocks, discontinuity) => {
24919
26077
  const decision = this.#decideGap(before, after, lostBlocks, discontinuity);
24920
26078
  this.#onFrameGap?.(decision);
@@ -24924,6 +26082,28 @@ var MmtpRouter = class {
24924
26082
  onRap: (packetId, catalogTrackName, ssId) => {
24925
26083
  for (const observer of this.#fecRapObservers) observer(packetId, catalogTrackName, ssId);
24926
26084
  },
26085
+ // One timer per stream, at the earliest wake asked: its drain re-arms
26086
+ // for the next frame still waiting.
26087
+ wakeAt: (packetId, catalogTrackName, atMs) => {
26088
+ if (this.#disposed) return;
26089
+ const key = this.#mediaStreamKey(packetId, catalogTrackName);
26090
+ const armed = this.#fecWakes.get(key);
26091
+ if (armed !== void 0 && armed.atMs <= atMs) return;
26092
+ if (armed !== void 0) clearTimeout(armed.timer);
26093
+ const timer = setTimeout(() => {
26094
+ this.#fecWakes.delete(key);
26095
+ this.#requestFecPoke(packetId, catalogTrackName);
26096
+ }, Math.max(0, Math.ceil(atMs - performance.now())));
26097
+ this.#fecWakes.set(key, { atMs, timer });
26098
+ },
26099
+ // A staged switch commits on when each side's frames reach it
26100
+ // (#interceptSwitchFrame): both sides' overlay keyframes reach it when
26101
+ // they did unanchored.
26102
+ releaseUnanchored: (packetId, catalogTrackName) => {
26103
+ const staged = this.#staged;
26104
+ const stream = { packetId, ...catalogTrackName === void 0 ? {} : { catalogTrackName } };
26105
+ return staged !== null && (isStream(stream, staged.from) || isStream(stream, staged.to));
26106
+ },
24927
26107
  onReleased: (data, meta) => {
24928
26108
  if (meta.trackType !== "video" || meta.mpuSequenceNumber === void 0) return;
24929
26109
  const timing = meta.authoredTiming;
@@ -24951,7 +26131,7 @@ var MmtpRouter = class {
24951
26131
  #decideGap(before, after, lostBlocks, discontinuity) {
24952
26132
  const { packetId, catalogTrackName } = after.meta;
24953
26133
  const trackKind = this.#classifyPacketId(packetId) === false ? "audio" : "video";
24954
- const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying";
26134
+ const positionsTrusted = this.#fecManager?.classifierModeFor?.(packetId, catalogTrackName).mode === "classifying" && before.meta.movieFragmentSequenceNumber === after.meta.movieFragmentSequenceNumber;
24955
26135
  const mpuTrusted = this.#fecManager?.mpuBoundsRapsFor?.(packetId, catalogTrackName) === true;
24956
26136
  const evidence = (frame) => {
24957
26137
  const timing = frame.meta.authoredTiming;
@@ -25065,6 +26245,7 @@ var MmtpRouter = class {
25065
26245
  const parsed = this.#parser.parsePacket(packet);
25066
26246
  if (!parsed) return;
25067
26247
  const info = parsed.info;
26248
+ if (manifestAdmitted && !info.isRepair && ingress?.admittedBy !== USER_AGENT_VERIFIED) this.#admittedSourceDatagrams++;
25068
26249
  if (source === "multicast" && !manifestAdmitted) {
25069
26250
  this.#fecManager?.noteMulticastArrival?.(info.packetId, info.sequenceNumber);
25070
26251
  }
@@ -25346,7 +26527,8 @@ var MmtpRouter = class {
25346
26527
  parsed.header,
25347
26528
  info.sequenceNumber,
25348
26529
  info.rapFlag,
25349
- source
26530
+ source,
26531
+ fecPayloadId?.ssId
25350
26532
  );
25351
26533
  }
25352
26534
  }
@@ -25372,7 +26554,8 @@ var MmtpRouter = class {
25372
26554
  source: parserOptions?.source,
25373
26555
  deliveryProvenance: parserOptions?.deliveryProvenance,
25374
26556
  catalogTrackName: parserOptions?.catalogTrackName,
25375
- ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn }
26557
+ ...parserOptions?.fecSbn === void 0 ? {} : { fecSbn: parserOptions.fecSbn },
26558
+ ...parserOptions?.fecSbnFirst === void 0 ? {} : { fecSbnFirst: parserOptions.fecSbnFirst }
25376
26559
  };
25377
26560
  if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
25378
26561
  else this.#parser.feed(packet, feedOptions);
@@ -25496,7 +26679,8 @@ var MmtpRouter = class {
25496
26679
  if (stream === void 0) {
25497
26680
  stream = {
25498
26681
  key: JSON.stringify([packetId, catalogTrackName ?? null]),
25499
- duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId))
26682
+ duplicates: new StreamDuplicateLedgers(() => this.duplicateHorizonFor(packetId)),
26683
+ overlayToBase: { routed: /* @__PURE__ */ new Set(), pending: /* @__PURE__ */ new Map() }
25500
26684
  };
25501
26685
  byName.set(catalogTrackName, stream);
25502
26686
  }
@@ -25611,8 +26795,16 @@ var MmtpRouter = class {
25611
26795
  this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
25612
26796
  this.#emitDirectVideo(packetId, data, meta, cb);
25613
26797
  }
25614
- #routeDirectRecoveredVideo(packetId, data, meta, cb) {
26798
+ #routeDirectRecoveredVideo(packetId, data, meta, cb, fecSbn) {
25615
26799
  const streamKey = this.#mediaStreamKey(packetId, meta.catalogTrackName);
26800
+ if (this.#isFecTrack(packetId)) {
26801
+ const high = this.#deliveredVideoHighWaterByStream.get(streamKey);
26802
+ if (fecSbn !== void 0 || high !== void 0 && authoredAdjacent(high, meta)) {
26803
+ this.#drainDirectRecoveredVideo(streamKey, packetId, (frame) => frame.timestamp <= meta.timestamp, cb);
26804
+ this.#emitDirectVideo(packetId, data, meta, cb);
26805
+ return;
26806
+ }
26807
+ }
25616
26808
  this.#enqueueDirectRecoveredVideo(packetId, data, meta);
25617
26809
  const lastSourceTs = this.#lastDirectSourceVideoTsByStream.get(streamKey);
25618
26810
  this.#drainDirectRecoveredVideo(
@@ -25766,6 +26958,13 @@ var MmtpRouter = class {
25766
26958
  * frames by epoch only if pre-protection input ever matters.
25767
26959
  */
25768
26960
  #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
26961
+ const overlayRouted = ownerPacketId == null ? void 0 : this.#streams.get(ownerPacketId)?.get(catalogTrackName)?.overlayToBase.routed;
26962
+ if (overlayRouted !== void 0 && overlayRouted.size > 0) {
26963
+ result = {
26964
+ ...result,
26965
+ symbols: result.symbols.filter((sym) => !overlayRouted.has(this.#fecAnchorForRecovered(blockId, sym.index)))
26966
+ };
26967
+ }
25769
26968
  const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
25770
26969
  const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
25771
26970
  const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
@@ -25822,7 +27021,12 @@ var MmtpRouter = class {
25822
27021
  #routeProcessedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, overlay) {
25823
27022
  if (ownerPacketId == null) return;
25824
27023
  if (this.#classifyPacketId(ownerPacketId) === null) return;
25825
- const fecSbnOf = (index) => overlay ? {} : { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
27024
+ const fecSbnOf = (index) => {
27025
+ if (!overlay) return { fecSbn: this.#fecAnchorForRecovered(blockId, index) };
27026
+ const fecSbn = overlay.baseSsIds.get(index);
27027
+ const fecSbnFirst = overlay.firstSsIds.get(index);
27028
+ return fecSbn === void 0 || fecSbnFirst === void 0 ? {} : { fecSbn, fecSbnFirst };
27029
+ };
25826
27030
  const streamKey = this.#mediaStreamKey(ownerPacketId, catalogTrackName);
25827
27031
  const ssIdSeqOffset = overlay ? void 0 : this.#ssIdSeqOffsetByStream.get(streamKey);
25828
27032
  if (ssIdSeqOffset !== void 0) {
@@ -25830,7 +27034,10 @@ var MmtpRouter = class {
25830
27034
  ...result,
25831
27035
  symbols: result.symbols.map((sym) => {
25832
27036
  const wire = this.#fecAnchorForRecovered(blockId, sym.index) - ssIdSeqOffset >>> 0;
25833
- if (wire === sym.packetSequenceNumber) return sym;
27037
+ if (wire === sym.packetSequenceNumber) {
27038
+ this.#unstampedSsIdSeqOffsetByStream.set(streamKey, ssIdSeqOffset);
27039
+ return sym;
27040
+ }
25834
27041
  this.#restampedRecoveredSeqs++;
25835
27042
  this.#restampedStreams.add(streamKey);
25836
27043
  return { ...sym, packetSequenceNumber: wire };
@@ -25866,6 +27073,29 @@ var MmtpRouter = class {
25866
27073
  }
25867
27074
  );
25868
27075
  }
27076
+ const untimedHead = (sym) => sym.fragmentType === 2 && sym.fragment.fragmentationIndicator === 1 && sym.fragment.movieFragmentSequenceNumber !== void 0 && sym.fragment.sampleNumber !== void 0 && !this.#parser.hasAuthoredTimingFor(
27077
+ ownerPacketId,
27078
+ sym.fragment.mpuSequenceNumber,
27079
+ sym.fragment.movieFragmentSequenceNumber,
27080
+ sym.fragment.sampleNumber,
27081
+ catalogTrackName
27082
+ );
27083
+ for (const sym of result.symbols) {
27084
+ if (!untimedHead(sym) || this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) continue;
27085
+ this.#feedViaParser(
27086
+ sym.rawSymbol,
27087
+ { packetId: ownerPacketId, sequenceNumber: sym.packetSequenceNumber },
27088
+ void 0,
27089
+ {
27090
+ skipFecPayloadId: true,
27091
+ recovered: true,
27092
+ deliveryProvenance,
27093
+ ...fecSbnOf(sym.index),
27094
+ ...catalogTrackName === void 0 ? {} : { catalogTrackName }
27095
+ }
27096
+ );
27097
+ }
27098
+ result = { ...result, symbols: result.symbols.filter((sym) => !untimedHead(sym)) };
25869
27099
  const gated = this.#isFecTrack(ownerPacketId);
25870
27100
  const assembler = this.#mseAssemblerFor(ownerPacketId, catalogTrackName);
25871
27101
  if (assembler) {
@@ -27592,6 +28822,12 @@ function isNonNegativeSafeInteger(value) {
27592
28822
  function isSymbolCounts(value) {
27593
28823
  return isRecord(value) && hasExactKeys(value, ["multicast", "moq"]) && isNonNegativeSafeInteger(value["multicast"]) && isNonNegativeSafeInteger(value["moq"]);
27594
28824
  }
28825
+ function isSpanFailure(value) {
28826
+ if (!isRecord(value) || !hasExactKeys(value, ["length", "sources"])) return false;
28827
+ const length = value["length"];
28828
+ const sources = value["sources"];
28829
+ return Number.isSafeInteger(length) && length > 0 && isNonNegativeSafeInteger(sources) && sources < length;
28830
+ }
27595
28831
  function isNullableNonNegative(value) {
27596
28832
  return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0;
27597
28833
  }
@@ -27611,7 +28847,10 @@ function isRepairLifecycleEvent(value) {
27611
28847
  case "recovered":
27612
28848
  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"]);
27613
28849
  case "failed":
27614
- return hasExactKeys(value, ["version", "type", "block", "blockClass", "symbols"]) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]);
28850
+ return hasExactKeys(
28851
+ value,
28852
+ "span" in value ? ["version", "type", "block", "blockClass", "symbols", "span"] : ["version", "type", "block", "blockClass", "symbols"]
28853
+ ) && isRepairBlockIdentity(block) && BLOCK_CLASSES.has(value["blockClass"]) && isSymbolCounts(value["symbols"]) && (!("span" in value) || isSpanFailure(value["span"]));
27615
28854
  case "repair-preempted":
27616
28855
  case "repair-deferred":
27617
28856
  return hasExactKeys(value, ["version", "type", "block"]) && isRepairBlockIdentity(block);
@@ -27820,6 +29059,8 @@ var MulticastManager = class {
27820
29059
  /** Live joinRepairEndpoints() releases → the repair owners they registered,
27821
29060
  * re-applied after configureMultiTrack() clears catalog-derived owners. */
27822
29061
  #repairReleases = /* @__PURE__ */ new Map();
29062
+ /** Protected repair flows owned by each live repair-endpoint release. */
29063
+ #repairProvenanceFlows = /* @__PURE__ */ new Map();
27823
29064
  /** Each source's catalog keyframe overlay, from its `ok` binding. */
27824
29065
  #overlayBindings = /* @__PURE__ */ new Map();
27825
29066
  /** Installed overlay decoders (`setKeyframeOverlayDecoder`), by source. */
@@ -27877,7 +29118,7 @@ var MulticastManager = class {
27877
29118
  onPublisherRestart: (packetId, catalogTrackName) => {
27878
29119
  this.#resetStreamOutsideRouter(packetId, catalogTrackName);
27879
29120
  },
27880
- onBlockFailed: (sbn, packetId, catalogTrackName, blockClass) => {
29121
+ onBlockFailed: (sbn, packetId, catalogTrackName, blockClass, span) => {
27881
29122
  const pathCount = this.#fec.blockPathCount(
27882
29123
  sbn,
27883
29124
  packetId,
@@ -27895,7 +29136,8 @@ var MulticastManager = class {
27895
29136
  symbols: {
27896
29137
  multicast: pathCount?.multicastSymbols ?? 0,
27897
29138
  moq: pathCount?.moqSymbols ?? 0
27898
- }
29139
+ },
29140
+ ...span === void 0 ? {} : { span }
27899
29141
  });
27900
29142
  },
27901
29143
  onFrameGap: (decision) => {
@@ -27983,6 +29225,11 @@ var MulticastManager = class {
27983
29225
  this.#fec.onBlockVanished = (_sbn, packetId, catalogTrackName) => {
27984
29226
  this.#statsFor(packetId, catalogTrackName).vanishedBlocks++;
27985
29227
  };
29228
+ this.#fec.keyframeOverlayTiming = (packetId, catalogTrackName) => {
29229
+ const binding = this.#overlayInstalls.has(packetId) ? this.#overlayBindings.get(packetId) : void 0;
29230
+ if (binding === void 0) return void 0;
29231
+ return catalogTrackName === void 0 || catalogTrackName === binding.sourceCatalogTrackName ? binding.geometry : void 0;
29232
+ };
27986
29233
  this.#fec.onDecoderUnavailable = (event) => {
27987
29234
  this.#emitRepairLifecycle({
27988
29235
  version: 2,
@@ -28485,6 +29732,9 @@ var MulticastManager = class {
28485
29732
  this.#transport.onFailback((reason) => {
28486
29733
  const joined = this.#provenanceJoin;
28487
29734
  if (joined !== null) this.#router.unprotectProvenanceFlow(joined.flow);
29735
+ for (const flows of this.#repairProvenanceFlows.values()) {
29736
+ for (const flow of flows) this.#router.unprotectProvenanceFlow(flow);
29737
+ }
28488
29738
  this.#onFailback?.(reason);
28489
29739
  });
28490
29740
  }
@@ -28519,6 +29769,12 @@ var MulticastManager = class {
28519
29769
  "[MulticastManager] join: provenance flow (S, G, port) must match sourceAddress ?? senderAddress, groupAddress and port"
28520
29770
  );
28521
29771
  }
29772
+ if (provenanceFlow !== void 0) {
29773
+ const flow = multicastProvenanceFlowKey(provenanceFlow);
29774
+ if ([...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29775
+ throw new TypeError(`[MulticastManager] join: provenance flow already registered by a repair endpoint: ${flow}`);
29776
+ }
29777
+ }
28522
29778
  const staged = this.#renditionSwitch;
28523
29779
  if (staged !== null) this.#endRenditionSwitch(staged, { reason: "superseded" }, false);
28524
29780
  this.configureFec(config);
@@ -28526,8 +29782,8 @@ var MulticastManager = class {
28526
29782
  const selectedPacketIds = config.packetIds?.length ? new Set(config.packetIds) : null;
28527
29783
  const catalogTracks = config.tracks?.filter(({ packetId }) => selectedPacketIds === null || selectedPacketIds.has(packetId));
28528
29784
  const ingressTracks = catalogTracks ? catalogTracks : selectedPacketIds === null ? void 0 : [...selectedPacketIds].map((packetId) => ({ name: "", packetId }));
28529
- this.#releaseProvenanceJoin();
28530
29785
  const provenance = config.provenance;
29786
+ this.#releaseProvenanceJoin();
28531
29787
  const protectedTracks = ingressTracks ?? provenance?.flow.tracks;
28532
29788
  const ingress = protectedTracks === void 0 ? void 0 : {
28533
29789
  tracks: Object.freeze(
@@ -28580,8 +29836,13 @@ var MulticastManager = class {
28580
29836
  * feeds the flow's receiver; media datagrams are held until one admits them.
28581
29837
  */
28582
29838
  #joinProvenance(provenance, ingress) {
29839
+ this.#router.registerProvenanceFlow(ingress, this.#provenanceReceiver(provenance));
29840
+ this.#hookFailback();
29841
+ this.#provenanceJoin = { flow: ingress.flow };
29842
+ }
29843
+ #provenanceReceiver(provenance) {
28583
29844
  const { flow, auth } = provenance;
28584
- const receiver = new BcProvenanceV2Receiver({
29845
+ return new BcProvenanceV2Receiver({
28585
29846
  ...provenance.receiver,
28586
29847
  // The caller's ctx when it passes one, else the catalog's: an explicit
28587
29848
  // `catalogCtx: undefined` must not switch off the 7.2.4 ctx check.
@@ -28598,9 +29859,6 @@ var MulticastManager = class {
28598
29859
  maxAuthDelayMs: flow.maxAuthDelayMs,
28599
29860
  manifestTimerMs: flow.manifestTimerMs
28600
29861
  });
28601
- this.#router.registerProvenanceFlow(ingress, receiver);
28602
- this.#hookFailback();
28603
- this.#provenanceJoin = { flow: ingress.flow };
28604
29862
  }
28605
29863
  /** Un-protect: drop the flow's hold queues (no expiry counted). */
28606
29864
  #releaseProvenanceJoin() {
@@ -28631,8 +29889,25 @@ var MulticastManager = class {
28631
29889
  * callback delivers must come from a subscription opened on
28632
29890
  * `options.gateway`. A callback that also merges another source (a MoQ or
28633
29891
  * WebSocket repair feed) must not name a native provider here.
29892
+ *
29893
+ * An endpoint's `provenance` makes its group a protected flow of its own
29894
+ * (multicast-02 7.2.7), registered here and released with the group; its
29895
+ * records ride in band on the group's port. On the user-agent path a
29896
+ * flow-less repair group of a protected track is set aside, never read, so
29897
+ * a player joining a protected catalog's repair groups passes it.
28634
29898
  */
28635
29899
  joinRepairEndpoints(endpoints, provider, options) {
29900
+ for (const { provenance, flow, source, group, port: port2 } of endpoints) {
29901
+ if (provenance === void 0) continue;
29902
+ if (flow !== void 0) {
29903
+ throw new TypeError("[MulticastManager] joinRepairEndpoints: an endpoint names provenance or flow, never both");
29904
+ }
29905
+ if (!sameIpAddress(source, provenance.flow.source) || !sameIpAddress(group, provenance.flow.groupAddress) || port2 !== provenance.flow.port) {
29906
+ throw new RangeError(
29907
+ "[MulticastManager] joinRepairEndpoints: provenance flow (S, G, port) must match the endpoint's source, group and port"
29908
+ );
29909
+ }
29910
+ }
28636
29911
  const releases = [];
28637
29912
  let released = false;
28638
29913
  const safely = (each) => {
@@ -28642,17 +29917,36 @@ var MulticastManager = class {
28642
29917
  console.warn("[MulticastManager] repair group release failed", error);
28643
29918
  }
28644
29919
  };
29920
+ const usedFlows = new Set(endpoints.flatMap(({ flow }) => flow === void 0 ? [] : [flow]));
29921
+ const preparedProvenance = endpoints.map((endpoint) => {
29922
+ if (endpoint.provenance === void 0) return void 0;
29923
+ const flow = multicastProvenanceFlowKey(endpoint.provenance.flow);
29924
+ if (usedFlows.has(flow) || this.#provenanceJoin?.flow === flow || [...this.#repairProvenanceFlows.values()].some((flows) => flows.includes(flow))) {
29925
+ throw new TypeError(`[MulticastManager] joinRepairEndpoints: provenance flow already registered: ${flow}`);
29926
+ }
29927
+ usedFlows.add(flow);
29928
+ return { flow, receiver: this.#provenanceReceiver(endpoint.provenance) };
29929
+ });
29930
+ const provenanceFlows = [];
28645
29931
  const repairOwners = endpoints.flatMap((endpoint) => endpoint.repairOwners.map((owner) => owner.instance !== "keyframe" ? owner : {
28646
29932
  ...owner,
28647
29933
  ownerTrackName: endpoint.tracks.find((t) => t.packetId === owner.ownerPacketId)?.name,
28648
29934
  repairTrackName: endpoint.tracks.find((t) => t.packetId === owner.packetId)?.name
28649
29935
  }));
28650
29936
  this.#applyRepairOwners(repairOwners);
28651
- for (const endpoint of endpoints) {
29937
+ for (const [index, endpoint] of endpoints.entries()) {
29938
+ const flow = endpoint.provenance === void 0 ? endpoint.flow : multicastProvenanceFlowKey(endpoint.provenance.flow);
28652
29939
  const ingress = {
28653
29940
  tracks: Object.freeze(endpoint.tracks.map(({ name, packetId }) => Object.freeze({ name, packetId }))),
28654
- ...endpoint.flow === void 0 ? {} : { flow: endpoint.flow }
29941
+ ...flow === void 0 ? {} : { flow }
28655
29942
  };
29943
+ if (endpoint.provenance !== void 0) {
29944
+ const prepared = preparedProvenance[index];
29945
+ if (prepared === void 0) throw new Error("[MulticastManager] repair provenance preparation missing");
29946
+ this.#router.registerProvenanceFlow(ingress, prepared.receiver);
29947
+ provenanceFlows.push(prepared.flow);
29948
+ releases.push(() => this.#router.releaseProvenanceFlow(flow));
29949
+ }
28656
29950
  let sender;
28657
29951
  const feed = (packet, sourceAddress, ingressToFeed) => {
28658
29952
  if (released) return;
@@ -28678,10 +29972,11 @@ var MulticastManager = class {
28678
29972
  mode: endpoint.mode,
28679
29973
  amtRelay: endpoint.amtRelay,
28680
29974
  amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : void 0),
29975
+ amtDiscovery: endpoint.amtDiscovery,
28681
29976
  packetIds: endpoint.packetIds,
28682
29977
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
28683
29978
  // A protected repair group's records ride in band on its port (7.2.3).
28684
- ...endpoint.flow === void 0 ? {} : { protected: true }
29979
+ ...flow === void 0 ? {} : { protected: true }
28685
29980
  }, ingress).then((joined) => {
28686
29981
  if (!joined && !released) fail(transport.lastJoinOutcome);
28687
29982
  });
@@ -28690,9 +29985,12 @@ var MulticastManager = class {
28690
29985
  if (released) return;
28691
29986
  released = true;
28692
29987
  this.#repairReleases.delete(release);
29988
+ this.#repairProvenanceFlows.delete(release);
28693
29989
  for (const each of releases.splice(0)) safely(each);
28694
29990
  };
28695
29991
  this.#repairReleases.set(release, repairOwners);
29992
+ this.#repairProvenanceFlows.set(release, provenanceFlows);
29993
+ if (provenanceFlows.length) this.#hookFailback();
28696
29994
  return release;
28697
29995
  }
28698
29996
  #applyRepairOwners(owners) {
@@ -29178,7 +30476,8 @@ var MulticastManager = class {
29178
30476
  blockProfile: parseFecBlockProfile(
29179
30477
  geometry2.blockProfile,
29180
30478
  `tracks[${JSON.stringify(track.name)}].fec keyframe overlay blockProfile`
29181
- )
30479
+ ),
30480
+ geometry: geometry2
29182
30481
  });
29183
30482
  }
29184
30483
  }
@@ -29217,7 +30516,7 @@ var MulticastManager = class {
29217
30516
  for (const [sourcePacketId, install] of [...this.#overlayInstalls]) {
29218
30517
  const before = this.#overlayBindings.get(sourcePacketId);
29219
30518
  const after = overlayBindings.get(sourcePacketId);
29220
- const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => after[key] === before[key]);
30519
+ const same = before !== void 0 && after !== void 0 && Object.keys(after).every((key) => key === "geometry" || after[key] === before[key]);
29221
30520
  if (!same) install.dispose();
29222
30521
  else if (this.#router.hasKeyframeOverlay(after.repairPacketId)) this.#router.resetKeyframeOverlays(sourcePacketId);
29223
30522
  else install.reattach();
@@ -29274,10 +30573,12 @@ var MulticastManager = class {
29274
30573
  * Register the range repair scheduler (draft-ramadan-moq-fec §7.5): from now
29275
30574
  * on an iso-ssbg1-v1 gap missing a source and every repair is kept as a
29276
30575
  * pending hole and reported here, and `closeIsoHoles` must be called for it
29277
- * once its range FETCH ends (or none is sent).
30576
+ * once its range FETCH ends (or none is sent). `onExpired` is told of a
30577
+ * pending hole the stream runs past the locator's horizon: returning true,
30578
+ * the caller closes it (`closeIsoHoles`); otherwise it is discarded.
29278
30579
  */
29279
- onUndelimitedLoss(cb) {
29280
- this.#fec.setUndelimitedLossHandler(cb);
30580
+ onUndelimitedLoss(cb, onExpired) {
30581
+ this.#fec.setUndelimitedLossHandler(cb, onExpired ?? null);
29281
30582
  }
29282
30583
  /**
29283
30584
  * Report each stream whose FEC fails closed at runtime (fec-01 6.3.9), e.g.
@@ -29513,7 +30814,8 @@ var MulticastManager = class {
29513
30814
  "stream" in event ? { ...event, stream: Object.freeze({ ...event.stream }) } : {
29514
30815
  ...event,
29515
30816
  block: Object.freeze({ ...event.block }),
29516
- ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {}
30817
+ ..."symbols" in event ? { symbols: Object.freeze({ ...event.symbols }) } : {},
30818
+ ..."span" in event && event.span !== void 0 ? { span: Object.freeze({ ...event.span }) } : {}
29517
30819
  }
29518
30820
  );
29519
30821
  if (this.#logRepairLifecycle) {
@@ -29626,7 +30928,7 @@ async function setupFecWorkerForTrack(opts) {
29626
30928
  blockProfile,
29627
30929
  k: opts.fecK,
29628
30930
  // P as this receiver joined it, not the catalog total: the worker snapshot
29629
- // and CMCD `x-bc-fec-p` are read from this. Identity on a single layer.
30931
+ // and CMCD `com.blockcast-fp` are read from this. Identity on a single layer.
29630
30932
  repairCount: opts.joinedRepairCount ?? opts.fecRepairCount,
29631
30933
  symbolSize: opts.fecSymbolSize,
29632
30934
  interleaveDepth: interleaveDepthBlocks,
@@ -30168,24 +31470,24 @@ var MediaRouter = class {
30168
31470
  if (!this.#multicastVideoKeyed) return;
30169
31471
  if (this.#requireAudio && !this.#multicastAudioReceived) return;
30170
31472
  if (this.#requireAudio && !this.#moqAudioWarmed) return;
30171
- const token = ++this.#sourceSwitchToken;
31473
+ const token2 = ++this.#sourceSwitchToken;
30172
31474
  const maybeReady = this.#onSourceSwitch?.("multicast");
30173
31475
  if (!maybeReady || typeof maybeReady.then !== "function") {
30174
- this.#commitMulticastActivation(token);
31476
+ this.#commitMulticastActivation(token2);
30175
31477
  return;
30176
31478
  }
30177
31479
  const ready = Promise.resolve(maybeReady);
30178
- this.#pendingMulticastToken = token;
31480
+ this.#pendingMulticastToken = token2;
30179
31481
  this.#sourceSwitchReady = ready;
30180
31482
  void ready.then(
30181
- () => this.#commitMulticastActivation(token),
30182
- (err) => this.#rejectMulticastActivation(token, err)
31483
+ () => this.#commitMulticastActivation(token2),
31484
+ (err) => this.#rejectMulticastActivation(token2, err)
30183
31485
  ).finally(() => {
30184
31486
  if (this.#sourceSwitchReady === ready) this.#sourceSwitchReady = null;
30185
31487
  });
30186
31488
  }
30187
- #commitMulticastActivation(token) {
30188
- if (token !== this.#sourceSwitchToken) return;
31489
+ #commitMulticastActivation(token2) {
31490
+ if (token2 !== this.#sourceSwitchToken) return;
30189
31491
  this.#active = "multicast";
30190
31492
  this.#suppressed = true;
30191
31493
  this.#pendingMulticastToken = null;
@@ -30196,9 +31498,9 @@ var MediaRouter = class {
30196
31498
  if (video) this.#onVideoFrame?.(video.data, video.meta);
30197
31499
  if (audio) this.#onAudioFrame?.(audio.data, audio.meta);
30198
31500
  }
30199
- #rejectMulticastActivation(token, err) {
30200
- if (token !== this.#sourceSwitchToken) return;
30201
- if (this.#pendingMulticastToken === token) this.#pendingMulticastToken = null;
31501
+ #rejectMulticastActivation(token2, err) {
31502
+ if (token2 !== this.#sourceSwitchToken) return;
31503
+ if (this.#pendingMulticastToken === token2) this.#pendingMulticastToken = null;
30202
31504
  this.#pendingMulticastVideo = null;
30203
31505
  this.#pendingMulticastAudio = null;
30204
31506
  console.warn("[MediaRouter] onSourceSwitch(multicast) failed", err);
@@ -31167,63 +32469,65 @@ var FecStarvationDetector = class {
31167
32469
 
31168
32470
  // src/cmcd-producer.ts
31169
32471
  var PLAY_MODES = ["full", "base-only", "single-track"];
31170
- function sanitize(value) {
31171
- return value.replace(/[,\r\n]/g, "");
31172
- }
31173
- function buildFecParams(stats) {
31174
- const params = {};
31175
- const cfg = stats.config;
31176
- params["x-bc-fec-algo"] = cfg.algorithm;
31177
- params["x-bc-fec-k"] = cfg.k;
31178
- params["x-bc-fec-p"] = cfg.repairCount;
31179
- params["x-bc-fec-recovery"] = parseFloat((stats.recoveryRate / 100).toFixed(4));
31180
- return params;
31181
- }
31182
- function buildTransportParams(snap) {
31183
- if (!snap) return {};
31184
- const params = {};
31185
- params["x-bc-transport"] = snap.transport;
31186
- if (snap.multicastGroup != null) {
31187
- params["x-bc-multicast-group"] = snap.multicastGroup;
31188
- }
31189
- if (snap.multicastSource != null) {
31190
- params["x-bc-multicast-source"] = snap.multicastSource;
31191
- }
31192
- if (snap.amtRelay != null) {
31193
- params["x-bc-amt-relay"] = snap.amtRelay;
31194
- }
31195
- return params;
31196
- }
31197
- function formatQueryString(params) {
31198
- return Object.keys(params).sort().map((key) => {
31199
- const v = params[key];
31200
- if (typeof v === "string") return `${key}=${sanitize(v)}`;
31201
- return `${key}=${v}`;
32472
+ var DEFAULT_INTERVAL_MS = 3e4;
32473
+ var CUSTOM_PREFIX = "com.blockcast-";
32474
+ var MAX_CUSTOM_VALUE = 64;
32475
+ var TRANSPORT_TOKEN = {
32476
+ native: "ssm",
32477
+ amt: "amt",
32478
+ moq: "moq"
32479
+ };
32480
+ function sfString(value) {
32481
+ return `"${value.replace(/[^\x20-\x7e]/g, "").replace(/[\\"]/g, "\\$&")}"`;
32482
+ }
32483
+ function encodeCmcdRecord(record) {
32484
+ return Object.keys(record).sort().map((key) => {
32485
+ const value = record[key];
32486
+ if (typeof value === "number") return `${key}=${value}`;
32487
+ if (typeof value === "string") return `${key}=${sfString(value)}`;
32488
+ if (Array.isArray(value)) return `${key}=(${value.map(sfString).join(" ")})`;
32489
+ return `${key}=${value.token}`;
31202
32490
  }).join(",");
31203
32491
  }
32492
+ var token = (value) => ({ token: value });
32493
+ function putCustom(record, name, value) {
32494
+ if (value === void 0) return;
32495
+ if (typeof value === "number") value = String(value);
32496
+ if (typeof value === "string" && value.length > MAX_CUSTOM_VALUE) return;
32497
+ record[CUSTOM_PREFIX + name] = value;
32498
+ }
31204
32499
  var CmcdProducer = class {
31205
- #onCmcdParams;
31206
32500
  #onCmcdPost;
32501
+ #intervalMs;
32502
+ #sessionId;
32503
+ #now;
32504
+ #sn = 0;
32505
+ #lastHeartbeat = null;
31207
32506
  #transport;
31208
32507
  #lastStats;
31209
- // Phase 14 state — Plan 03 Task 2 (D-12, D-15).
31210
32508
  #playMode = null;
31211
32509
  #deltaFailRate = null;
31212
32510
  #switchMiscount = 0;
31213
32511
  #manifestStats = null;
31214
32512
  #fecFailClosed = null;
32513
+ /** Video-block resolutions from the repair lifecycle; null until the player feeds one. */
32514
+ #lifecycle = null;
31215
32515
  constructor(options) {
31216
- this.#onCmcdParams = options.onCmcdParams;
31217
32516
  this.#onCmcdPost = options.onCmcdPost;
32517
+ this.#intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
32518
+ if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {
32519
+ throw new Error(`[CmcdProducer] invalid intervalMs "${String(options.intervalMs)}"; expected a positive number`);
32520
+ }
32521
+ this.#sessionId = options.sessionId ?? globalThis.crypto.randomUUID();
32522
+ this.#now = options.now ?? Date.now;
31218
32523
  }
31219
32524
  /** Update the stored transport state. Called by player wiring layer. */
31220
32525
  updateTransport(snapshot) {
31221
32526
  this.#transport = snapshot;
31222
32527
  }
31223
32528
  /**
31224
- * Set the current play-mode. Emitted as `x-bc-play-mode` on subsequent
31225
- * snapshots. Throws on any value outside {'full','base-only','single-track'}
31226
- * (CLAUDE.md: error on bad init).
32529
+ * Set the current play-mode, reported as `com.blockcast-pm`. Throws on any
32530
+ * value outside {'full','base-only','single-track'} (CLAUDE.md: error on bad init).
31227
32531
  */
31228
32532
  updatePlayMode(mode) {
31229
32533
  if (typeof mode !== "string" || !PLAY_MODES.includes(mode)) {
@@ -31234,9 +32538,8 @@ var CmcdProducer = class {
31234
32538
  this.#playMode = mode;
31235
32539
  }
31236
32540
  /**
31237
- * Set the delta-track FEC block-failure rate (0..1 inclusive). Emitted as
31238
- * `x-bc-delta-fail-rate` on snapshots when play-mode is 'full' or 'base-only'.
31239
- * Omitted on single-track streams.
32541
+ * Set the delta-track FEC block-failure rate (0..1 inclusive), reported as
32542
+ * `com.blockcast-dfr` when play-mode is 'full' or 'base-only'.
31240
32543
  */
31241
32544
  updateDeltaFailRate(rate) {
31242
32545
  if (typeof rate !== "number" || !Number.isFinite(rate) || rate < 0 || rate > 1) {
@@ -31246,112 +32549,139 @@ var CmcdProducer = class {
31246
32549
  }
31247
32550
  this.#deltaFailRate = rate;
31248
32551
  }
31249
- /**
31250
- * Bump the cumulative switching-set misalignment counter. Emitted as
31251
- * `x-bc-switch-miscount` on snapshots when the counter is > 0.
31252
- */
32552
+ /** Bump the cumulative switching-set misalignment counter (`com.blockcast-sm`). */
31253
32553
  incrementSwitchMiscount() {
31254
32554
  this.#switchMiscount += 1;
31255
32555
  }
31256
32556
  /**
31257
- * Record that FEC failed closed at runtime (fec-01 6.3.9). Every later
31258
- * snapshot carries `x-bc-fec-fail-closed` (the reason code) and
31259
- * `x-bc-fec-fail-layer` (the held layer i whose total B_i was undercut), so a
31260
- * stream playing without FEC is told apart from one with no loss.
32557
+ * Record that FEC failed closed at runtime (fec-01 6.3.9). Reported at once
32558
+ * as `e=e` with the reason code in `ec`, and on every later counter report
32559
+ * as `com.blockcast-ffc` / `com.blockcast-ffl` (the held layer whose total
32560
+ * B_i was undercut), so a stream playing without FEC is told apart from one
32561
+ * with no loss.
31261
32562
  */
31262
32563
  updateFecFailClosed(reason) {
32564
+ const changed = this.#fecFailClosed?.code !== reason.code || this.#fecFailClosed?.layer !== reason.layer;
31263
32565
  this.#fecFailClosed = reason;
32566
+ if (changed) this.#post([{ ...this.#base("e"), ec: [reason.code] }]);
31264
32567
  }
31265
32568
  updateManifestVerification(stats) {
31266
32569
  this.#manifestStats = stats;
31267
32570
  }
31268
32571
  /**
31269
- * One-shot emit of `x-bc-switch-drift-us` for a single misalignment event.
31270
- * Does NOT mutate snapshot state — subsequent onSnapshot() calls will not
31271
- * include the drift key until the next emitSwitchDrift(). Mirrors the
31272
- * existing onTransition() pattern.
32572
+ * Count a video block's resolution from the repair lifecycle: recovered in
32573
+ * band (`com.blockcast-fbr`), recovered by repair FETCH (`-fbq`), or failed
32574
+ * as a keyframe-class block (`-fbfk`). Audio blocks are not counted, matching
32575
+ * the video-track `-fbf`. Until the player feeds this, the three are absent.
31273
32576
  */
32577
+ onRepairLifecycle(event) {
32578
+ this.#lifecycle ??= { inband: 0, fetch: 0, failedKeyframe: 0 };
32579
+ if (event.type === "recovered" && event.blockClass !== "audio") {
32580
+ if (event.via === "inband") this.#lifecycle.inband++;
32581
+ else this.#lifecycle.fetch++;
32582
+ } else if (event.type === "failed" && event.blockClass === "keyframe") {
32583
+ this.#lifecycle.failedKeyframe++;
32584
+ }
32585
+ }
32586
+ /** One-shot custom event `com.blockcast-switch-drift` for a single misalignment. */
31274
32587
  emitSwitchDrift(driftUs) {
31275
32588
  if (typeof driftUs !== "number" || !Number.isFinite(driftUs) || driftUs < 0) {
31276
32589
  throw new Error(
31277
32590
  `[CmcdProducer] invalid drift-us "${String(driftUs)}"; expected a non-negative finite number`
31278
32591
  );
31279
32592
  }
31280
- const params = {};
31281
- if (this.#lastStats) Object.assign(params, buildFecParams(this.#lastStats));
31282
- Object.assign(params, buildTransportParams(this.#transport));
31283
- if (this.#switchMiscount > 0) params["x-bc-switch-miscount"] = this.#switchMiscount;
31284
- params["x-bc-switch-drift-us"] = driftUs;
31285
- this.#emit(params);
32593
+ const record = { ...this.#base("ce"), cen: CUSTOM_PREFIX + "switch-drift" };
32594
+ putCustom(record, "sdu", Math.round(driftUs));
32595
+ this.#post([record]);
31286
32596
  }
31287
- /**
31288
- * Process a FecTrackStats snapshot. Finds the video track, builds
31289
- * x-bc-* vendor keys, and fires both delivery callbacks.
31290
- */
32597
+ /** Take a FecTrackStats snapshot (first video track) and send the heartbeat when due. */
31291
32598
  onSnapshot(data) {
31292
32599
  const videoTrack = data.tracks.find((t) => t.config.trackType === "video");
31293
32600
  if (!videoTrack) return;
31294
32601
  this.#lastStats = videoTrack;
31295
- const params = {
31296
- ...buildFecParams(videoTrack),
31297
- ...buildTransportParams(this.#transport)
31298
- };
31299
- if (this.#playMode !== null) {
31300
- params["x-bc-play-mode"] = this.#playMode;
31301
- }
31302
- if (this.#fecFailClosed) {
31303
- params["x-bc-fec-fail-closed"] = this.#fecFailClosed.code;
31304
- params["x-bc-fec-fail-layer"] = this.#fecFailClosed.layer;
31305
- }
31306
- if (this.#playMode !== null && this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
31307
- params["x-bc-delta-fail-rate"] = parseFloat(this.#deltaFailRate.toFixed(4));
31308
- }
31309
- if (this.#switchMiscount > 0) {
31310
- params["x-bc-switch-miscount"] = this.#switchMiscount;
31311
- }
31312
- if (this.#manifestStats) {
31313
- params["x-bc-manifest-verified"] = this.#manifestStats.verified > 0;
31314
- params["x-bc-manifest-failures"] = Object.values(this.#manifestStats.failures).reduce((total, count) => total + count, 0);
31315
- }
31316
- this.#emit(params);
32602
+ this.#heartbeat();
31317
32603
  }
31318
32604
  /**
31319
- * Emit transport state without inventing FEC metrics. Cadence is owned by
31320
- * the caller because only the transport integration knows when state changed.
32605
+ * Take transport state for receivers that do not own FEC stats, and send the
32606
+ * heartbeat when due.
31321
32607
  */
31322
32608
  onTransportSnapshot(data) {
31323
32609
  if (!Number.isFinite(data.timestampMs) || data.timestampMs < 0) {
31324
32610
  throw new Error("[CmcdProducer] transport snapshot timestamp must be a non-negative finite number");
31325
32611
  }
31326
32612
  if (data.playMode !== void 0) this.updatePlayMode(data.playMode);
31327
- if (data.switchMiscount !== void 0 && (!Number.isSafeInteger(data.switchMiscount) || data.switchMiscount < 0)) {
31328
- throw new Error("[CmcdProducer] transport snapshot switch-miscount must be a non-negative safe integer");
32613
+ if (data.switchMiscount !== void 0) {
32614
+ if (!Number.isSafeInteger(data.switchMiscount) || data.switchMiscount < 0) {
32615
+ throw new Error("[CmcdProducer] transport snapshot switch-miscount must be a non-negative safe integer");
32616
+ }
32617
+ this.#switchMiscount = data.switchMiscount;
31329
32618
  }
31330
32619
  this.#transport = data.transport;
31331
- const params = buildTransportParams(data.transport);
31332
- if (this.#playMode !== null) params["x-bc-play-mode"] = this.#playMode;
31333
- const switchMiscount = data.switchMiscount ?? this.#switchMiscount;
31334
- if (switchMiscount > 0) params["x-bc-switch-miscount"] = switchMiscount;
31335
- this.#emit(params);
32620
+ this.#heartbeat();
31336
32621
  }
31337
- /**
31338
- * Signal a transport transition event. Fires an immediate out-of-band
31339
- * emit with x-bc-ct set. The subsequent onSnapshot() will NOT include
31340
- * x-bc-ct (one-shot).
31341
- */
32622
+ /** Report a transport transition at once, as custom event `com.blockcast-ct`. */
31342
32623
  onTransition(event) {
31343
- const params = {};
31344
- if (this.#lastStats) {
31345
- Object.assign(params, buildFecParams(this.#lastStats));
32624
+ const record = { ...this.#base("ce"), cen: CUSTOM_PREFIX + "ct" };
32625
+ putCustom(record, "ct", token(event));
32626
+ this.#putTransport(record);
32627
+ this.#post([record]);
32628
+ }
32629
+ #base(event) {
32630
+ return { e: token(event), sid: this.#sessionId, sn: this.#sn++, ts: Math.floor(this.#now()), v: 2 };
32631
+ }
32632
+ #heartbeat() {
32633
+ const now = this.#now();
32634
+ if (this.#lastHeartbeat !== null && now - this.#lastHeartbeat < this.#intervalMs) return;
32635
+ this.#lastHeartbeat = now;
32636
+ this.#post([this.#base("t"), this.#counters()]);
32637
+ }
32638
+ #putTransport(record) {
32639
+ const snap = this.#transport;
32640
+ if (!snap) return;
32641
+ putCustom(record, "tr", token(TRANSPORT_TOKEN[snap.transport]));
32642
+ if (snap.multicastGroup != null && snap.multicastSource != null) {
32643
+ putCustom(record, "sg", `${snap.multicastGroup}@${snap.multicastSource}`);
32644
+ }
32645
+ putCustom(record, "ar", snap.amtRelay);
32646
+ }
32647
+ /** The `e=ce` counter report. */
32648
+ #counters() {
32649
+ const record = { ...this.#base("ce"), cen: CUSTOM_PREFIX + "fec" };
32650
+ const stats = this.#lastStats;
32651
+ if (stats) {
32652
+ putCustom(record, "fa", stats.config.algorithm);
32653
+ putCustom(record, "fk", stats.config.k);
32654
+ putCustom(record, "fp", stats.config.repairCount);
32655
+ putCustom(record, "pr", stats.sourceSymbols);
32656
+ putCustom(record, "pl", stats.sourcePacketsMissing);
32657
+ putCustom(record, "pu", stats.sourcePacketsUnrecovered);
32658
+ putCustom(record, "fbf", stats.blocksFailed);
32659
+ }
32660
+ if (this.#lifecycle) {
32661
+ putCustom(record, "fbr", this.#lifecycle.inband);
32662
+ putCustom(record, "fbq", this.#lifecycle.fetch);
32663
+ putCustom(record, "fbfk", this.#lifecycle.failedKeyframe);
32664
+ }
32665
+ this.#putTransport(record);
32666
+ if (this.#playMode !== null) {
32667
+ putCustom(record, "pm", token(this.#playMode));
32668
+ if (this.#playMode !== "single-track" && this.#deltaFailRate !== null) {
32669
+ putCustom(record, "dfr", this.#deltaFailRate.toFixed(3));
32670
+ }
32671
+ }
32672
+ if (this.#fecFailClosed) {
32673
+ putCustom(record, "ffc", token(this.#fecFailClosed.code));
32674
+ putCustom(record, "ffl", this.#fecFailClosed.layer);
32675
+ }
32676
+ if (this.#switchMiscount > 0) putCustom(record, "sm", this.#switchMiscount);
32677
+ if (this.#manifestStats) {
32678
+ putCustom(record, "mv", this.#manifestStats.verified);
32679
+ putCustom(record, "mf", Object.values(this.#manifestStats.failures).reduce((a, b) => a + b, 0));
31346
32680
  }
31347
- Object.assign(params, buildTransportParams(this.#transport));
31348
- params["x-bc-ct"] = event;
31349
- this.#emit(params);
32681
+ return record;
31350
32682
  }
31351
- /** Fire both delivery callbacks with the given params. */
31352
- #emit(params) {
31353
- this.#onCmcdParams?.(params);
31354
- this.#onCmcdPost?.(formatQueryString(params));
32683
+ #post(records) {
32684
+ this.#onCmcdPost?.(records.map(encodeCmcdRecord).join("\n"));
31355
32685
  }
31356
32686
  };
31357
32687
 
@@ -31447,18 +32777,31 @@ function resolveRepairLayers(catalog, source) {
31447
32777
  totalBaseRepairSymbols: binding.totalBaseRepairSymbols
31448
32778
  };
31449
32779
  }
32780
+ function valueAt(catalog, pointer) {
32781
+ let node = catalog;
32782
+ for (const segment of pointer.split("/").slice(1)) {
32783
+ if (typeof node !== "object" || node === null) return void 0;
32784
+ node = node[segment.replace(/~1/g, "/").replace(/~0/g, "~")];
32785
+ }
32786
+ return node;
32787
+ }
32788
+ function catalogTrackDeliveryMode(catalog, source) {
32789
+ const binding = bindingOf(catalog, source);
32790
+ const entry = binding ? valueAt(catalog, binding.pointer) : void 0;
32791
+ return entry?.deliveryMode === "stream" ? "stream" : "datagram";
32792
+ }
31450
32793
  function moqtPriority2(value) {
31451
32794
  return Number.isSafeInteger(value) && value >= 0 && value <= 255 ? value : null;
31452
32795
  }
31453
32796
  function catalogRepairTarget(catalog, source) {
31454
32797
  const binding = bindingOf(catalog, source);
31455
32798
  if (binding?.status !== "ok" || !(binding.base.interleaveDepthMs ?? 0)) return null;
31456
- const layerZero = binding.layers[0];
32799
+ const layerZero2 = binding.layers[0];
31457
32800
  const m = /^\/tracks\/(\d+)$/.exec(binding.pointer);
31458
32801
  const tracks = catalog.tracks;
31459
32802
  const entry = m && Array.isArray(tracks) ? tracks[Number(m[1])] : void 0;
31460
32803
  const sourcePriority = entry ? moqtPriority2(entry["priority"]) : null;
31461
- return { repairTrack: layerZero.repairTrackName, sourcePriority, repairPriority: layerZero.priority };
32804
+ return { repairTrack: layerZero2.repairTrackName, sourcePriority, repairPriority: layerZero2.priority };
31462
32805
  }
31463
32806
  function numericField(value) {
31464
32807
  const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
@@ -31490,6 +32833,7 @@ function fecParams(catalog, track, fps, sampleRate) {
31490
32833
  repairTrackName: base.repairTrack,
31491
32834
  repairLayers: repair.baseLayers,
31492
32835
  repairOverlays: repair.overlays,
32836
+ deliveryMode: catalogTrackDeliveryMode(catalog, track),
31493
32837
  ...mediaRate
31494
32838
  };
31495
32839
  }
@@ -31540,7 +32884,14 @@ function resolveCatalogTrackFec(catalog, tracks) {
31540
32884
  var PATH_BITS = { moq: 1, multicast: 2 };
31541
32885
  var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
31542
32886
  var MmtpFecSession = class {
32887
+ /** P_0 = B_0, the held total every repair packet is checked against. */
32888
+ get repairSymbols() {
32889
+ return this.#repairSymbols;
32890
+ }
31543
32891
  #decoder;
32892
+ #repairSymbols;
32893
+ /** The message entry a catalog-less session was built from; undefined under a catalog. */
32894
+ #message;
31544
32895
  /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
31545
32896
  #blocks = /* @__PURE__ */ new Map();
31546
32897
  /** SS_Starts of settled blocks, so a later repair for one is refused. */
@@ -31578,6 +32929,24 @@ var MmtpFecSession = class {
31578
32929
  * `interleaveDepthMs` or `reorderToleranceMs`. None is defaulted.
31579
32930
  */
31580
32931
  constructor(config) {
32932
+ if (config && "alFecFlow" in config) {
32933
+ const message = alFecRaptorQFlowConfig(config.alFecFlow);
32934
+ if (!message) {
32935
+ throw new Error("MmtpFecSession: the AL-FEC entry is outside draft-ramadan-moq-mmt-02 8.3 (iso-ssbg1-v1)");
32936
+ }
32937
+ this.#message = message;
32938
+ this.blockProfile = parseFecBlockProfile("iso-ssbg1-v1", "alFecFlow");
32939
+ this.algorithm = message.fecCodeId === FEC_CODE_RAPTORQ ? "raptorq" : "reed-solomon";
32940
+ this.sourceSymbols = message.maximumK;
32941
+ this.#repairSymbols = message.maximumP;
32942
+ this.symbolSize = message.repairSymbolSize;
32943
+ this.retentionBlocks = requirePositiveInteger(config.retentionBlocks, "retentionBlocks");
32944
+ this.#repairPacketId = message.repairFlowId;
32945
+ this.#heldLayers = layerZero(message.maximumP);
32946
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
32947
+ this.#decoder = buildDecoder(config.Decoder, this);
32948
+ return;
32949
+ }
31581
32950
  const fec = config?.fec;
31582
32951
  if (!fec || typeof fec !== "object") {
31583
32952
  throw new Error("MmtpFecSession: the catalog fec instance is required");
@@ -31588,7 +32957,7 @@ var MmtpFecSession = class {
31588
32957
  }
31589
32958
  this.algorithm = fec.scheme;
31590
32959
  this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
31591
- this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
32960
+ this.#repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
31592
32961
  this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
31593
32962
  const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
31594
32963
  const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
@@ -31608,17 +32977,30 @@ var MmtpFecSession = class {
31608
32977
  config.heldLayers
31609
32978
  );
31610
32979
  this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
31611
- if (typeof config.Decoder !== "function") {
31612
- throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
31613
- }
31614
- const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
31615
- try {
31616
- decoder.configure_params(this.sourceSymbols, this.symbolSize);
31617
- } catch (error) {
31618
- decoder.free();
31619
- throw error;
31620
- }
31621
- this.#decoder = decoder;
32980
+ this.#decoder = buildDecoder(config.Decoder, this);
32981
+ }
32982
+ /**
32983
+ * A later version of the AL-FEC message, catalog-less sessions only. A
32984
+ * maximum_p_for_repair_flow above the held total raises it (`raised`): the
32985
+ * anchored check restarts at the new total, so a block generated under the
32986
+ * previous one stays valid before the first block carrying the new total
32987
+ * (fec-core-00 7.3.2, mmt-02 8.3). A field at or below it changes nothing
32988
+ * (`unchanged`): no publisher lowers it, and the check catches a wire that
32989
+ * does. An entry with another asset, repair flow, code point, K or T, or
32990
+ * one outside 8.3, is `refused`: that is a new source encoding, which needs
32991
+ * a new session. A latched fail-closed stays latched either way.
32992
+ */
32993
+ updateAlFecFlow(flow) {
32994
+ const held = this.#message;
32995
+ if (!held) throw new Error("MmtpFecSession: updateAlFecFlow() needs a session built from an AL-FEC entry");
32996
+ const next = alFecRaptorQFlowConfig(flow);
32997
+ if (!next || next.sourcePacketIds[0] !== held.sourcePacketIds[0] || next.repairFlowId !== held.repairFlowId || next.fecCodeId !== held.fecCodeId || next.maximumK !== held.maximumK || next.repairSymbolSize !== held.repairSymbolSize) {
32998
+ return "refused";
32999
+ }
33000
+ if (next.maximumP <= this.#repairSymbols) return "unchanged";
33001
+ this.#repairSymbols = next.maximumP;
33002
+ this.#heldLayers = layerZero(next.maximumP);
33003
+ return "raised";
31622
33004
  }
31623
33005
  /** True once release() ran. */
31624
33006
  get released() {
@@ -31713,7 +33095,7 @@ var MmtpFecSession = class {
31713
33095
  }
31714
33096
  if (admission.reject) {
31715
33097
  const verdict2 = this.#heldLayers.failsClosed(
31716
- repairTrackName,
33098
+ this.#trackFor(repairTrackName),
31717
33099
  frame.ssStart,
31718
33100
  frame.rsbLength,
31719
33101
  this.#anchorHorizon,
@@ -31728,7 +33110,7 @@ var MmtpFecSession = class {
31728
33110
  this.#repairPacketId ??= frame.packetId;
31729
33111
  if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
31730
33112
  const verdict = this.#heldLayers.admit(
31731
- repairTrackName,
33113
+ this.#trackFor(repairTrackName),
31732
33114
  frame.ssStart,
31733
33115
  frame.rsbLength,
31734
33116
  this.#anchorHorizon,
@@ -31787,6 +33169,10 @@ var MmtpFecSession = class {
31787
33169
  decoder.free();
31788
33170
  return true;
31789
33171
  }
33172
+ /** Catalog-less: layer 0 has no own-track clause (mmt-02 8.3), so no track name is judged. */
33173
+ #trackFor(repairTrackName) {
33174
+ return this.#message ? void 0 : repairTrackName;
33175
+ }
31790
33176
  #drop(reason) {
31791
33177
  this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
31792
33178
  return [];
@@ -31908,6 +33294,22 @@ var MmtpFecSession = class {
31908
33294
  }
31909
33295
  }
31910
33296
  };
33297
+ function layerZero(total) {
33298
+ return new HeldLayerAdmission([{ layer: 0, repairTrackName: "", rsIdOffset: 0, repairSymbols: total }]);
33299
+ }
33300
+ function buildDecoder(Decoder, session) {
33301
+ if (typeof Decoder !== "function") {
33302
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
33303
+ }
33304
+ const decoder = new Decoder(session.retentionBlocks, session.blockProfile, session.algorithm);
33305
+ try {
33306
+ decoder.configure_params(session.sourceSymbols, session.symbolSize);
33307
+ } catch (error) {
33308
+ decoder.free();
33309
+ throw error;
33310
+ }
33311
+ return decoder;
33312
+ }
31911
33313
  function requirePositiveInteger(value, path) {
31912
33314
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
31913
33315
  throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
@@ -31921,8 +33323,171 @@ function requireNumber(value, path) {
31921
33323
  return value;
31922
33324
  }
31923
33325
 
33326
+ // src/repair-layer-subscriptions.ts
33327
+ var SERIAL32_HALF2 = 2147483648;
33328
+ var RepairLayerSubscriptions = class {
33329
+ #opts;
33330
+ #windowPackets;
33331
+ #margin;
33332
+ #dropAfterWindows;
33333
+ #source;
33334
+ #layerCount = 0;
33335
+ #subs = /* @__PURE__ */ new Map();
33336
+ #disposed = false;
33337
+ #lastSeq;
33338
+ #expected = 0;
33339
+ #lost = 0;
33340
+ #wantFewer = 0;
33341
+ #lossRate = null;
33342
+ #repairPackets = 0;
33343
+ #repairBytes = 0;
33344
+ #staleDropped = 0;
33345
+ constructor(opts) {
33346
+ this.#opts = opts;
33347
+ this.#source = opts.source;
33348
+ this.#windowPackets = opts.windowPackets ?? 500;
33349
+ this.#margin = opts.margin ?? 2;
33350
+ this.#dropAfterWindows = opts.dropAfterWindows ?? 3;
33351
+ }
33352
+ get layerCount() {
33353
+ return this.#layerCount;
33354
+ }
33355
+ /**
33356
+ * One source packet's MMTP `packet_sequence_number`, in arrival order.
33357
+ * The sequence is per `packet_id`: pass the packets of ONE packet_id only,
33358
+ * or interleaved sequences read as loss.
33359
+ */
33360
+ noteSourceSequence(seq) {
33361
+ if (this.#disposed || this.#delivery() === "stream") return;
33362
+ seq >>>= 0;
33363
+ if (this.#lastSeq === void 0) {
33364
+ this.#lastSeq = seq;
33365
+ return;
33366
+ }
33367
+ const d = serial32Distance(this.#lastSeq, seq);
33368
+ if (d === 0) return;
33369
+ const back = d >= SERIAL32_HALF2 ? 2 ** 32 - d : 0;
33370
+ if (d > this.#windowPackets && (back === 0 || back > this.#windowPackets)) {
33371
+ this.#lastSeq = seq;
33372
+ this.#expected = 0;
33373
+ this.#lost = 0;
33374
+ return;
33375
+ }
33376
+ if (back === 0) {
33377
+ this.#expected += d;
33378
+ this.#lost += d - 1;
33379
+ this.#lastSeq = seq;
33380
+ } else if (this.#lost > 0) {
33381
+ this.#lost -= 1;
33382
+ }
33383
+ if (this.#expected >= this.#windowPackets) this.#closeWindow();
33384
+ }
33385
+ /** ABR switch R -> R': close R's tracks, carry the layer count to R'. */
33386
+ switchSource(next) {
33387
+ if (this.#disposed) return;
33388
+ this.#closeAll();
33389
+ this.#source = next;
33390
+ this.#lastSeq = void 0;
33391
+ this.#expected = 0;
33392
+ this.#lost = 0;
33393
+ this.#wantFewer = 0;
33394
+ this.#layerCount = this.#delivery() === "stream" ? 0 : Math.min(this.#layerCount, this.#layers().length);
33395
+ this.#reconcile();
33396
+ }
33397
+ snapshot() {
33398
+ return {
33399
+ delivery: this.#delivery(),
33400
+ layerCount: this.#layerCount,
33401
+ subscribedTracks: [...this.#subs.keys()],
33402
+ repairPackets: this.#repairPackets,
33403
+ repairBytes: this.#repairBytes,
33404
+ staleDropped: this.#staleDropped,
33405
+ lossRate: this.#lossRate
33406
+ };
33407
+ }
33408
+ dispose() {
33409
+ if (this.#disposed) return;
33410
+ this.#closeAll();
33411
+ this.#disposed = true;
33412
+ }
33413
+ #delivery() {
33414
+ return this.#source.deliveryMode === "stream" ? "stream" : "datagram";
33415
+ }
33416
+ #layers() {
33417
+ return this.#source.repairLayers ?? [];
33418
+ }
33419
+ #closeWindow() {
33420
+ const rate = this.#lost / this.#expected;
33421
+ this.#lossRate = rate;
33422
+ this.#expected = 0;
33423
+ this.#lost = 0;
33424
+ const target = this.#targetLayers(rate);
33425
+ if (target > this.#layerCount) {
33426
+ this.#wantFewer = 0;
33427
+ this.#layerCount = target;
33428
+ } else if (target < this.#layerCount) {
33429
+ this.#wantFewer += 1;
33430
+ if (this.#wantFewer >= this.#dropAfterWindows) {
33431
+ this.#wantFewer = 0;
33432
+ this.#layerCount -= 1;
33433
+ }
33434
+ } else {
33435
+ this.#wantFewer = 0;
33436
+ }
33437
+ this.#reconcile();
33438
+ }
33439
+ /** Fewest base layers whose summed P covers margin x the measured loss of K. */
33440
+ #targetLayers(rate) {
33441
+ if (rate <= 0) return 0;
33442
+ const needed = Math.ceil(rate * this.#source.fecK * this.#margin);
33443
+ const layers = this.#layers();
33444
+ let held = 0;
33445
+ for (let n = 0; n < layers.length; n++) {
33446
+ held += layers[n].repairSymbols;
33447
+ if (held >= needed) return n + 1;
33448
+ }
33449
+ return layers.length;
33450
+ }
33451
+ /** Stream delivery never leaves layer count 0, so it never subscribes. */
33452
+ #reconcile() {
33453
+ const want = /* @__PURE__ */ new Map();
33454
+ for (const layer of this.#layers().slice(0, this.#layerCount)) {
33455
+ want.set(layer.repairTrackName, layer.priority);
33456
+ }
33457
+ const overlay = this.#source.repairOverlays?.[0];
33458
+ if (this.#layerCount > 0 && overlay) want.set(overlay.repairTrackName, overlay.priority);
33459
+ for (const [name, entry] of this.#subs) {
33460
+ if (!want.has(name)) {
33461
+ entry.sub.close();
33462
+ this.#subs.delete(name);
33463
+ }
33464
+ }
33465
+ for (const [name, priority] of want) {
33466
+ if (this.#subs.has(name)) continue;
33467
+ const entry = {};
33468
+ entry.sub = this.#opts.subscribe(name, priority, (packet) => this.#onPacket(name, entry, packet));
33469
+ this.#subs.set(name, entry);
33470
+ }
33471
+ }
33472
+ /** Fenced on the entry itself, so a closed subscription is stale even if its track is re-added. */
33473
+ #onPacket(name, entry, packet) {
33474
+ if (this.#disposed || this.#subs.get(name) !== entry) {
33475
+ this.#staleDropped += 1;
33476
+ return;
33477
+ }
33478
+ this.#repairPackets += 1;
33479
+ this.#repairBytes += packet.byteLength;
33480
+ this.#opts.feed(packet, name);
33481
+ }
33482
+ #closeAll() {
33483
+ for (const entry of this.#subs.values()) entry.sub.close();
33484
+ this.#subs.clear();
33485
+ }
33486
+ };
33487
+
31924
33488
  // src/repair-fetch.ts
31925
33489
  var MOQT_PRIORITY_MAX = 255;
33490
+ var WALK_LEAD_MS = 3;
31926
33491
  var SOURCE_MEDIA_PRIORITY_MAX = REPAIR_PRIORITY_MIN - 1;
31927
33492
  function isMoqtPriority(value) {
31928
33493
  return Number.isSafeInteger(value) && value >= 0 && value <= MOQT_PRIORITY_MAX;
@@ -31973,8 +33538,17 @@ function wireRepairFetch(mc, opts) {
31973
33538
  mc.noteRepairScheduling(type, entry.sbn, entry.packetId, entry.catalogTrackName);
31974
33539
  };
31975
33540
  const clearEntry = (entry) => {
31976
- if (entry.range) mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, entry.range.holeLength);
31977
- else clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33541
+ const { range } = entry;
33542
+ if (range) {
33543
+ atReport(range, () => mc.closeIsoHoles(entry.packetId, entry.catalogTrackName, entry.sbn, range.holeLength));
33544
+ } else {
33545
+ clearRepair(entry.sbn, entry.packetId, entry.catalogTrackName);
33546
+ }
33547
+ };
33548
+ const atReport = (range, work) => {
33549
+ const fec = mc.fecManager;
33550
+ if (range.groups !== null || fec.withReceiptTime === void 0) work();
33551
+ else fec.withReceiptTime(range.reportedAt, work);
31978
33552
  };
31979
33553
  const releaseHold = (entry) => {
31980
33554
  if (entry.range) return;
@@ -31986,7 +33560,7 @@ function wireRepairFetch(mc, opts) {
31986
33560
  if (!run) return;
31987
33561
  entry.running = null;
31988
33562
  run.stopped = reason;
31989
- run.controller.abort();
33563
+ run.controller.abort(reason);
31990
33564
  if (reason === "preempted") releaseHold(entry);
31991
33565
  mc.noteRepairStopped?.(reason, entry.sbn, entry.packetId, entry.catalogTrackName);
31992
33566
  };
@@ -32041,21 +33615,42 @@ function wireRepairFetch(mc, opts) {
32041
33615
  const admit = (entry, now) => {
32042
33616
  const budgetMs = entry.deadlineAt - now;
32043
33617
  const rttMs = readRtt();
32044
- const reason = !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < budgetMs ? null : "rtt-exceeds-budget";
33618
+ const reason = refusal(entry, now, rttMs);
32045
33619
  if (reason === null) return rttMs;
32046
33620
  skip(entry, reason, rttMs, budgetMs);
32047
33621
  return null;
32048
33622
  };
33623
+ const refusal = (entry, now, rttMs) => !entry.range && !groupCanComplete(entry.sbn, entry.packetId, entry.catalogTrackName) ? "group-cannot-complete" : rttMs === null ? "rtt-unmeasured" : rttMs < entry.deadlineAt - now ? null : "rtt-exceeds-budget";
32049
33624
  const retire = (entry) => {
32050
33625
  if (entries.get(entry.key) === entry) entries.delete(entry.key);
32051
33626
  if (entry.expiry !== void 0) clearTimeout(entry.expiry);
32052
33627
  };
32053
- const outstandingBelow = (priority) => {
33628
+ const holdsBack = (entry, priority, videoWalks = true) => {
33629
+ if (entry.priority >= priority) return false;
33630
+ const { walk } = entry;
33631
+ if (walk === void 0) return true;
33632
+ if (entry.priority !== 0 || !videoWalks) return false;
33633
+ return entry.running === null || walk.group !== null && !walk.group.controller.signal.aborted;
33634
+ };
33635
+ const outstandingBelow = (priority, videoWalks = true) => {
32054
33636
  for (const entry of entries.values()) {
32055
- if (entry.priority < priority) return true;
33637
+ if (holdsBack(entry, priority, videoWalks)) return true;
32056
33638
  }
32057
33639
  return false;
32058
33640
  };
33641
+ const yieldVideoWalks = (queued) => {
33642
+ const now = performance.now();
33643
+ const rttMs = readRtt();
33644
+ const due = queued.some((entry) => entry.priority !== 0 && entry.walk === void 0 && !outstandingBelow(entry.priority, false) && refusal(entry, now, rttMs) === null);
33645
+ if (!due) return;
33646
+ for (const entry of entries.values()) {
33647
+ const walk = entry.walk;
33648
+ if (entry.priority !== 0 || walk === void 0 || walk.group === null) continue;
33649
+ if (walk.group.controller.signal.aborted) continue;
33650
+ walk.yielded = true;
33651
+ walk.group.controller.abort();
33652
+ }
33653
+ };
32059
33654
  const preemptBestEffort = () => {
32060
33655
  for (const entry of entries.values()) {
32061
33656
  if (entry.priority === 0 || !entry.running) continue;
@@ -32084,7 +33679,8 @@ function wireRepairFetch(mc, opts) {
32084
33679
  }
32085
33680
  const rttMs = admit(entry, now);
32086
33681
  if (rttMs === null) return;
32087
- if (entry.priority === 0) preemptBestEffort();
33682
+ if (entry.priority === 0 && entry.walk === void 0) preemptBestEffort();
33683
+ if (entry.range === void 0) leaveWalkedGroup(entry);
32088
33684
  if (counted) entry.attempts++;
32089
33685
  mc.noteRepairFetchSent?.(entry.priority, entry.sbn, entry.packetId, entry.catalogTrackName, {
32090
33686
  rttMs,
@@ -32106,6 +33702,14 @@ function wireRepairFetch(mc, opts) {
32106
33702
  }
32107
33703
  void execute(entry, run);
32108
33704
  };
33705
+ const leaveWalkedGroup = (block) => {
33706
+ for (const entry of entries.values()) {
33707
+ const group = entry.walk?.group;
33708
+ if (group?.sbn === block.sbn && entry.packetId === block.packetId && entry.catalogTrackName === block.catalogTrackName) {
33709
+ group.controller.abort();
33710
+ }
33711
+ }
33712
+ };
32109
33713
  const dispatch = () => {
32110
33714
  if (disposed) return;
32111
33715
  const now = performance.now();
@@ -32130,6 +33734,7 @@ function wireRepairFetch(mc, opts) {
32130
33734
  for (const entry of queued) {
32131
33735
  if (entry.priority === 0) start(entry);
32132
33736
  }
33737
+ yieldVideoWalks(queued);
32133
33738
  if (outstandingBelow(1)) return;
32134
33739
  for (const entry of queued) {
32135
33740
  if (entry.priority === 1) start(entry);
@@ -32156,6 +33761,16 @@ function wireRepairFetch(mc, opts) {
32156
33761
  }
32157
33762
  return counts.sources + counts.repairGroupLength >= counts.authoredLength;
32158
33763
  };
33764
+ const groupServed = (sbn, packetId, catalogTrackName) => {
33765
+ if (mc.fecManager.blockSymbolCounts === void 0) return false;
33766
+ const counts = symbolCounts(sbn, packetId, catalogTrackName);
33767
+ if (counts === void 0 || counts.authoredLength === void 0) return true;
33768
+ return counts.sources + counts.repairs >= counts.authoredLength || !groupCanComplete(sbn, packetId, catalogTrackName);
33769
+ };
33770
+ const statedEnd = (sbn, packetId, catalogTrackName) => {
33771
+ const length = symbolCounts(sbn, packetId, catalogTrackName)?.authoredLength;
33772
+ return length === void 0 ? void 0 : serial32Add(sbn, length);
33773
+ };
32159
33774
  const finish = (entry, run, fed, error) => {
32160
33775
  if (run.stopped !== null || entry.running !== run || entries.get(entry.key) !== entry) {
32161
33776
  return;
@@ -32200,27 +33815,81 @@ function wireRepairFetch(mc, opts) {
32200
33815
  signal: run.controller.signal,
32201
33816
  subscriberPriority: entry.subscriberPriority
32202
33817
  };
33818
+ const { range } = entry;
33819
+ const feed = (packet) => {
33820
+ if (entry.catalogTrackName === void 0) {
33821
+ mc.processRepairFromMoQ(packet, entry.packetId);
33822
+ } else {
33823
+ mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
33824
+ }
33825
+ };
32203
33826
  try {
32204
- const packets = entry.range ? opts.rangeTransport({
33827
+ const packets = range === void 0 ? opts.transport({ ...common, sbn: entry.sbn }) : entry.walk !== void 0 ? walkHole(entry, entry.walk, range, common) : opts.rangeTransport({
32205
33828
  ...common,
32206
- startGroup: entry.range.startGroup,
32207
- endGroup: entry.range.endGroup,
32208
- lostSsId: entry.range.lostSsId
32209
- }) : opts.transport({ ...common, sbn: entry.sbn });
33829
+ startGroup: range.groups.startGroup,
33830
+ endGroup: range.groups.endGroup,
33831
+ lostSsId: range.lostSsId
33832
+ });
32210
33833
  for await (const packet of packets) {
32211
33834
  if (run.stopped !== null || entry.running !== run) break;
32212
33835
  fed++;
32213
- if (entry.catalogTrackName === void 0) {
32214
- mc.processRepairFromMoQ(packet, entry.packetId);
32215
- } else {
32216
- mc.processRepairFromMoQ(packet, entry.packetId, entry.catalogTrackName);
32217
- }
33836
+ if (range === void 0) feed(packet);
33837
+ else atReport(range, () => feed(packet));
32218
33838
  }
32219
33839
  finish(entry, run, fed, void 0);
32220
33840
  } catch (error) {
32221
33841
  finish(entry, run, fed, error ?? new Error("repair transport rejected"));
32222
33842
  }
32223
33843
  };
33844
+ async function* walkHole(entry, walk, hole, common) {
33845
+ const lostAt = serial32Distance(entry.sbn, hole.lostSsId);
33846
+ for (let first = true; !common.signal.aborted; first = false) {
33847
+ if (!first && entry.priority !== 0 && outstandingBelow(1)) {
33848
+ stop(entry, "preempted");
33849
+ note("repair-preempted", entry);
33850
+ return;
33851
+ }
33852
+ if (!first && entry.priority === 0) {
33853
+ dispatch();
33854
+ if (common.signal.aborted) return;
33855
+ }
33856
+ const sbn = walk.next;
33857
+ let next;
33858
+ if (entries.get(requestKey(sbn, entry.packetId, entry.catalogTrackName))?.running == null) {
33859
+ const rsIds = /* @__PURE__ */ new Set();
33860
+ const group = new AbortController();
33861
+ const cancel = () => group.abort(common.signal.reason);
33862
+ common.signal.addEventListener("abort", cancel, { once: true });
33863
+ walk.group = { sbn, controller: group };
33864
+ try {
33865
+ for await (const packet of opts.transport({ ...common, sbn, signal: group.signal })) {
33866
+ yield packet;
33867
+ const id = extractRepairFecPayloadId(packet);
33868
+ if (id === null || id.ssStart !== sbn || id.ssbLength === 0) continue;
33869
+ next ??= serial32Add(sbn, id.ssbLength);
33870
+ rsIds.add(id.rsId);
33871
+ if (rsIds.size >= id.rsbLength || groupServed(sbn, entry.packetId, entry.catalogTrackName)) {
33872
+ group.abort();
33873
+ break;
33874
+ }
33875
+ }
33876
+ } catch (error) {
33877
+ if (!group.signal.aborted || common.signal.aborted) throw error;
33878
+ } finally {
33879
+ common.signal.removeEventListener("abort", cancel);
33880
+ walk.group = null;
33881
+ }
33882
+ if (walk.yielded) {
33883
+ walk.yielded = false;
33884
+ continue;
33885
+ }
33886
+ }
33887
+ next ??= statedEnd(sbn, entry.packetId, entry.catalogTrackName);
33888
+ if (next === void 0) return;
33889
+ if (serial32Distance(entry.sbn, next) > lostAt) return;
33890
+ walk.next = next;
33891
+ }
33892
+ }
32224
33893
  const removeResetObserver = mc.addTrackResetObserver((packetId, catalogTrackName) => {
32225
33894
  for (const entry of [...entries.values()]) {
32226
33895
  if (entry.packetId !== packetId || entry.catalogTrackName !== catalogTrackName) continue;
@@ -32416,7 +34085,37 @@ function wireRepairFetch(mc, opts) {
32416
34085
  throw error;
32417
34086
  }
32418
34087
  };
32419
- if (opts.rangeTransport !== void 0) {
34088
+ const trackKind = (packetId) => {
34089
+ try {
34090
+ return mc.fecManager.trackKindFor?.(packetId);
34091
+ } catch {
34092
+ return void 0;
34093
+ }
34094
+ };
34095
+ const walkDeadlineAt = (packetId, now, deadlineAt) => {
34096
+ let repairDeadlineMs;
34097
+ try {
34098
+ repairDeadlineMs = mc.fecManager.repairDeadlineMsForPacket?.(packetId);
34099
+ } catch {
34100
+ repairDeadlineMs = void 0;
34101
+ }
34102
+ if (repairDeadlineMs === void 0 || !Number.isFinite(repairDeadlineMs)) return deadlineAt;
34103
+ return Math.min(deadlineAt, now + repairDeadlineMs - WALK_LEAD_MS);
34104
+ };
34105
+ const onHoleExpired = (hole) => {
34106
+ if (disposed) return false;
34107
+ const entry = [...entries.values()].find((candidate) => candidate.walk !== void 0 && candidate.packetId === hole.packetId && candidate.catalogTrackName === hole.catalogTrackName && serial32Distance(candidate.sbn, hole.holeStart) < candidate.range.holeLength);
34108
+ if (entry === void 0) return false;
34109
+ queueMicrotask(() => {
34110
+ if (entries.get(entry.key) !== entry) return;
34111
+ retire(entry);
34112
+ stop(entry, "expired");
34113
+ clearEntry(entry);
34114
+ dispatch();
34115
+ });
34116
+ return true;
34117
+ };
34118
+ if (mc.onUndelimitedLoss !== void 0 && mc.closeIsoHoles !== void 0) {
32420
34119
  mc.onUndelimitedLoss((loss) => {
32421
34120
  const { packetId, catalogTrackName, holeStart, holeLength } = loss;
32422
34121
  const close = () => mc.closeIsoHoles(packetId, catalogTrackName, holeStart, holeLength);
@@ -32424,9 +34123,11 @@ function wireRepairFetch(mc, opts) {
32424
34123
  const blockProfile = blockProfileOf(packetId);
32425
34124
  const target = opts.resolveTarget(packetId, catalogTrackName);
32426
34125
  if (!target) return close();
32427
- const priority = repairPriorityForClass("unknown");
32428
- const range = rangeFor(loss, target.repairTrack);
32429
- if (range === null) {
34126
+ const walked = opts.rangeTransport === void 0;
34127
+ const holeClass = walked && trackKind(packetId) === "audio" ? "audio" : "unknown";
34128
+ const priority = repairPriorityForClass(holeClass);
34129
+ const groups = walked ? null : rangeFor(loss, target.repairTrack);
34130
+ if (!walked && groups === null) {
32430
34131
  close();
32431
34132
  mc.noteRepairSkipped("range-no-anchor", { rttMs: readRtt(), budgetMs: 0, priority }, holeStart, packetId, catalogTrackName);
32432
34133
  return;
@@ -32437,8 +34138,10 @@ function wireRepairFetch(mc, opts) {
32437
34138
  packetId,
32438
34139
  ...catalogTrackName === void 0 ? {} : { catalogTrackName }
32439
34140
  };
32440
- const wire = wirePriority(identity, "unknown");
32441
- const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, performance.now(), "unknown");
34141
+ const wire = wirePriority(identity, holeClass);
34142
+ if (wire === null) return close();
34143
+ const now = performance.now();
34144
+ const deadline = presentationDeadlineAt(holeStart, packetId, catalogTrackName, now, holeClass);
32442
34145
  if (deadline === null) {
32443
34146
  close();
32444
34147
  mc.noteRepairSkipped(
@@ -32450,6 +34153,7 @@ function wireRepairFetch(mc, opts) {
32450
34153
  );
32451
34154
  return;
32452
34155
  }
34156
+ const deadlineAt = walked ? walkDeadlineAt(packetId, now, deadline.deadlineAt) : deadline.deadlineAt;
32453
34157
  const entry = {
32454
34158
  key: JSON.stringify(["range", packetId, catalogTrackName ?? null, holeStart]),
32455
34159
  ...identity,
@@ -32457,15 +34161,16 @@ function wireRepairFetch(mc, opts) {
32457
34161
  blockProfile,
32458
34162
  priority,
32459
34163
  subscriberPriority: wire.subscriberPriority,
32460
- deadlineAt: deadline.deadlineAt,
32461
- playoutDeadlineAt: deadline.deadlineAt - deadline.extensionMs,
34164
+ deadlineAt,
34165
+ playoutDeadlineAt: deadlineAt - deadline.extensionMs,
32462
34166
  anchorAt: deadline.anchorAt,
32463
34167
  delayMs: deadline.delayMs,
32464
34168
  bound: deadline.bound,
32465
34169
  order: enqueueOrder++,
32466
34170
  attempts: 0,
32467
34171
  running: null,
32468
- range: { ...range, lostSsId: loss.lostSsId, holeLength }
34172
+ range: { lostSsId: loss.lostSsId, holeLength, groups, reportedAt: now },
34173
+ ...walked ? { walk: { next: holeStart, group: null, yielded: false } } : {}
32469
34174
  };
32470
34175
  const previous = entries.get(entry.key);
32471
34176
  if (previous) {
@@ -32475,7 +34180,7 @@ function wireRepairFetch(mc, opts) {
32475
34180
  entries.set(entry.key, entry);
32476
34181
  entry.expiry = setTimeout(dispatch, Math.max(0, entry.deadlineAt - performance.now()) + 1);
32477
34182
  dispatch();
32478
- });
34183
+ }, onHoleExpired);
32479
34184
  }
32480
34185
  const removeRapObserver = mc.addRapCompleteObserver?.((packetId) => {
32481
34186
  queueMicrotask(() => {
@@ -32566,6 +34271,7 @@ export {
32566
34271
  REPAIR_LIFECYCLE_LOG_PREFIX,
32567
34272
  REPAIR_PRIORITY_MAX,
32568
34273
  REPAIR_PRIORITY_MIN,
34274
+ RepairLayerSubscriptions,
32569
34275
  SOURCE_MEDIA_PRIORITY_MAX,
32570
34276
  SampleCombineError,
32571
34277
  SampleCombiner,
@@ -32590,6 +34296,7 @@ export {
32590
34296
  catalogGroupDurationMs,
32591
34297
  catalogKeyframeCadenceMs,
32592
34298
  catalogRepairTarget,
34299
+ catalogTrackDeliveryMode,
32593
34300
  catalogTrackFecUnavailable,
32594
34301
  classifyH264Keyframe,
32595
34302
  classifyHevcKeyframe,
@@ -32610,6 +34317,7 @@ export {
32610
34317
  detectH264Keyframe,
32611
34318
  detectHevcKeyframe,
32612
34319
  driftCheck,
34320
+ encodeCmcdRecord,
32613
34321
  encodeDataSegment,
32614
34322
  encodeFecSourceInfo,
32615
34323
  encodeLocTimestamp,
@@ -32686,6 +34394,7 @@ export {
32686
34394
  resolveGroupDurationMs,
32687
34395
  resolveGroupDurationTicks,
32688
34396
  resolveRepairLayers,
34397
+ runtimeFecCatalogReport,
32689
34398
  secondsFromTicks,
32690
34399
  setupFecWorkerForTrack,
32691
34400
  setupTrackPipeline,