@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
@@ -10,6 +10,8 @@ var PACKET_TYPE_MPU = 0;
10
10
  var PACKET_TYPE_REPAIR = 3;
11
11
  var MMTP_SIGNALING_PACKET_ID = 0;
12
12
  var MMTP_PACKET_ID_MAX = 65535;
13
+ var FEC_CODE_REED_SOLOMON = 1;
14
+ var FEC_CODE_RAPTORQ = 3;
13
15
  function parseMMTPHeader(buffer) {
14
16
  if (buffer.length < MMTP_HEADER_SIZE) {
15
17
  throw new Error(`MMTP packet too small: ${buffer.length} bytes`);
@@ -150,30 +152,26 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
150
152
  const authLength = view2.getUint16(2, false);
151
153
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
152
154
  }
153
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
155
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
154
156
  if (declaredEnd > payload.length)
155
157
  return null;
156
158
  if (options?.skipFecId) {
157
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
159
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
158
160
  }
159
- const overlay = options?.overlayDeclared === true && rapFlag;
160
161
  if (fecType === 1) {
161
- const fecStart = payload.length - sourceFecTrailerSize(overlay);
162
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
162
163
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
163
164
  return null;
164
165
  }
165
- return { hasFecId: true, hasOverlayFecId: overlay };
166
+ return { hasFecId: true };
166
167
  }
167
- if (fecType !== 0 || overlay)
168
+ if (fecType !== 0)
168
169
  return null;
169
170
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
170
- return { hasFecId: false, hasOverlayFecId: false };
171
+ return { hasFecId: false };
171
172
  }
172
173
  return null;
173
174
  }
174
- function sourceFecTrailerSize(overlay) {
175
- return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
176
- }
177
175
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
178
176
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
179
177
  return {
@@ -226,11 +224,11 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
226
224
  if ("rejection" in layoutResult)
227
225
  return layoutResult;
228
226
  const { layout } = layoutResult;
229
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
227
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
230
228
  if (!trailerLayout) {
231
229
  if (!options?.skipFecId && header.fecType === 1) {
232
230
  const observed = payload.length - layout.dataEnd;
233
- const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
231
+ const expected = SOURCE_FEC_PAYLOAD_ID_SIZE;
234
232
  if (observed !== expected) {
235
233
  return {
236
234
  rejection: {
@@ -262,13 +260,10 @@ function extractPlannedMfu(mmtpPacket, result) {
262
260
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
263
261
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
264
262
  const data = payload.subarray(mfuOffset, dataEnd);
265
- const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
266
- const ssIdAt = (offset) => ({
267
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
268
- });
269
- const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
270
- const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
271
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
263
+ const fecPayloadId = trailerLayout.hasFecId ? {
264
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, 4).getUint32(0, false)
265
+ } : null;
266
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
272
267
  }
273
268
  function sourceFecPayloadIdOf(mmtpPacket, header) {
274
269
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -360,6 +355,50 @@ var NTP_SHORT_BITS = 32;
360
355
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
361
356
  var NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1);
362
357
 
358
+ // ../mmt-base/dist/signalling.js
359
+ var FEC_CODING_STRUCTURE_ONE_STAGE = 1;
360
+ var SSBG_MODE_1 = 1;
361
+ var RAPTORQ_MAX_SOURCE_SYMBOLS = 56403;
362
+ var REPAIR_SYMBOL_ID_MAX = 16777215;
363
+ var MIN_REPAIR_SYMBOL_SIZE = 14;
364
+ var REED_SOLOMON_MAX_BLOCK = 255;
365
+ function alFecRaptorQFlowConfig(flow) {
366
+ if (flow.fecCodingStructure !== FEC_CODING_STRUCTURE_ONE_STAGE || flow.repairFlows.length !== 1)
367
+ return null;
368
+ if (flow.ssbgMode !== SSBG_MODE_1 || flow.ffsrptsFlag !== 0 || flow.fecPayloadIdMode !== 0)
369
+ return null;
370
+ if (flow.packetIds.length !== 1)
371
+ return null;
372
+ const repair = flow.repairFlows[0];
373
+ const { fecCodeId, maximumK: k, maximumP: p } = repair;
374
+ const t = flow.repairSymbolSize;
375
+ if (t < MIN_REPAIR_SYMBOL_SIZE || k < 1 || p < 1 || k + p - 1 > REPAIR_SYMBOL_ID_MAX)
376
+ return null;
377
+ if (fecCodeId === FEC_CODE_RAPTORQ) {
378
+ if (t % 8 !== 0 || k > RAPTORQ_MAX_SOURCE_SYMBOLS)
379
+ return null;
380
+ } else if (fecCodeId === FEC_CODE_REED_SOLOMON) {
381
+ if (k + p > REED_SOLOMON_MAX_BLOCK)
382
+ return null;
383
+ } else {
384
+ return null;
385
+ }
386
+ if (repair.repairFlowId === MMTP_SIGNALING_PACKET_ID || repair.repairFlowId === flow.packetIds[0])
387
+ return null;
388
+ return {
389
+ sourcePacketIds: [...flow.packetIds],
390
+ repairFlowId: repair.repairFlowId,
391
+ fecCodeId,
392
+ ssbgMode: flow.ssbgMode,
393
+ fecPayloadIdMode: flow.fecPayloadIdMode,
394
+ repairSymbolSize: t,
395
+ maximumK: k,
396
+ maximumP: p,
397
+ protectionWindowTime: repair.protectionWindowTime,
398
+ protectionWindowSize: repair.protectionWindowSize
399
+ };
400
+ }
401
+
363
402
  // ../mmt-base/dist/serial-number.js
364
403
  var SERIAL32_SPAN = 4294967296;
365
404
  var SERIAL32_HALF = 2147483648;
@@ -856,13 +895,25 @@ function fecCatalogTracks(catalog) {
856
895
  });
857
896
  return { tracks, pointers };
858
897
  }
859
- function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
898
+ function runtimeView(catalog, receiver) {
860
899
  const { tracks, pointers } = fecCatalogTracks(catalog);
861
900
  const report = validateFecCatalog({ tracks }, receiver);
862
901
  const at = (path) => {
863
902
  const m = /^\/tracks\/(\d+)(.*)$/.exec(path);
864
903
  return m ? pointers[Number(m[1])] + m[2] : path;
865
904
  };
905
+ return { tracks, pointers, report, at };
906
+ }
907
+ function runtimeFecCatalogReport(catalog, receiver = RUNTIME_FEC_RECEIVER) {
908
+ const { report, at } = runtimeView(catalog, receiver);
909
+ const issue = (i) => Object.freeze({ code: i.code, path: at(i.path) });
910
+ return Object.freeze({
911
+ instances: Object.freeze(report.instances.map((i) => Object.freeze({ ...i, path: at(i.path), issues: Object.freeze(i.issues.map(issue)) }))),
912
+ issues: Object.freeze(report.issues.map(issue))
913
+ });
914
+ }
915
+ function resolveFecBindings(catalog, receiver = RUNTIME_FEC_RECEIVER) {
916
+ const { tracks, pointers, report, at } = runtimeView(catalog, receiver);
866
917
  const trackAt = (i) => recordOf(tracks[i]) ?? {};
867
918
  const nameAt = (i) => i === null ? void 0 : trackAt(i)["name"];
868
919
  const why = (i) => Object.freeze({
@@ -4537,9 +4588,10 @@ function isH264IntraSlice(nal) {
4537
4588
  const sliceType = readH264SliceType(nal);
4538
4589
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
4539
4590
  }
4591
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
4540
4592
  function readH264SliceType(nal) {
4541
4593
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
4542
- const rbsp = removeEmulationPrevention(nal.subarray(1));
4594
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
4543
4595
  const state = { bitOffset: 0 };
4544
4596
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
4545
4597
  return readUnsignedExpGolomb(rbsp, state);
@@ -4686,6 +4738,96 @@ if (void 0) {
4686
4738
  ]))).toBe(false);
4687
4739
  });
4688
4740
  });
4741
+ describe("readH264SliceType", () => {
4742
+ const wholeNalSliceType = (nal) => {
4743
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
4744
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
4745
+ const state = { bitOffset: 0 };
4746
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
4747
+ return readUnsignedExpGolomb(rbsp, state);
4748
+ };
4749
+ const hex2 = (text2) => Uint8Array.from(text2.match(/../g), (byte) => parseInt(byte, 16));
4750
+ const ue = (value) => {
4751
+ const code = (value + 1).toString(2);
4752
+ return "0".repeat(code.length - 1) + code;
4753
+ };
4754
+ const sliceNal = (bits) => {
4755
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
4756
+ const nal = [1];
4757
+ let zeros = 0;
4758
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
4759
+ if (zeros >= 2 && byte <= 3) {
4760
+ nal.push(3);
4761
+ zeros = 0;
4762
+ }
4763
+ nal.push(byte);
4764
+ zeros = byte === 0 ? zeros + 1 : 0;
4765
+ }
4766
+ return Uint8Array.from(nal);
4767
+ };
4768
+ const x264Slices = [
4769
+ ["64x48 P", hex2("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
4770
+ ["64x48 B", hex2("419e414212fffeeade283707cb70f7"), 6, false],
4771
+ ["64x48 non-IDR I", hex2(
4772
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
4773
+ ), 7, true],
4774
+ ["1280x720 B, escape at byte 10", hex2(
4775
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
4776
+ ), 6, false],
4777
+ ["1280x720 P, escape at byte 15", hex2(
4778
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
4779
+ ), 5, false],
4780
+ ["1280x720 B, escape at byte 22", hex2("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
4781
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex2(
4782
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
4783
+ ), null, true],
4784
+ ["7680x4320 P, first_mb_in_slice 32640", hex2(
4785
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
4786
+ ), 5, false],
4787
+ ["7680x4320 P, first_mb_in_slice 97440", hex2(
4788
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
4789
+ ), 5, false]
4790
+ ];
4791
+ const syntheticSlices = [
4792
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
4793
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
4794
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
4795
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
4796
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
4797
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
4798
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
4799
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
4800
+ ];
4801
+ test("reads the slice_type of real and synthetic slices", () => {
4802
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
4803
+ expect(readH264SliceType(nal), name).toBe(sliceType);
4804
+ }
4805
+ });
4806
+ test("matches the whole-NAL unescape at every truncation", () => {
4807
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
4808
+ for (let end = 0; end <= nal.length; end++) {
4809
+ const cut = nal.subarray(0, end);
4810
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
4811
+ }
4812
+ }
4813
+ });
4814
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
4815
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
4816
+ let seed = 1;
4817
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
4818
+ for (let i = 0; i < 5e3; i++) {
4819
+ const nal = new Uint8Array(2 + next() % 63);
4820
+ nal[0] = 65;
4821
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
4822
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
4823
+ }
4824
+ });
4825
+ test("classifies the x264 slices as keyframes or not", () => {
4826
+ for (const [name, nal, , keyframe] of x264Slices) {
4827
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
4828
+ }
4829
+ });
4830
+ });
4689
4831
  describe("avccToAnnexB", () => {
4690
4832
  test("converts with SPS/PPS on keyframe", () => {
4691
4833
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -5529,9 +5671,21 @@ var IsoBmffTimingResolver = class {
5529
5671
  }
5530
5672
  #track = null;
5531
5673
  #fragments = /* @__PURE__ */ new Map();
5674
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
5675
+ #firstSamples = /* @__PURE__ */ new Map();
5676
+ /**
5677
+ * First sample and sample count of the newest fragments whose every slot was
5678
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
5679
+ * matches the combiner, since it retires an abandoned sample as well.
5680
+ */
5681
+ #delivered = /* @__PURE__ */ new Map();
5532
5682
  #pendingSamples = 0;
5533
5683
  #evictedSamples = 0;
5534
5684
  #lastMovieFragmentRejection = null;
5685
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
5686
+ get initialized() {
5687
+ return this.#track !== null;
5688
+ }
5535
5689
  get pendingSampleCount() {
5536
5690
  return this.#pendingSamples;
5537
5691
  }
@@ -5555,7 +5709,14 @@ var IsoBmffTimingResolver = class {
5555
5709
  this.#track = timing;
5556
5710
  return true;
5557
5711
  }
5558
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
5712
+ /**
5713
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
5714
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
5715
+ * fragment whose samples are all done is a duplicate: admitting it again
5716
+ * would charge stale timing and could displace the live MPU's. A source
5717
+ * copy is still admitted again (a rendition switch re-arms timing that way).
5718
+ */
5719
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
5559
5720
  this.#lastMovieFragmentRejection = null;
5560
5721
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
5561
5722
  this.#lastMovieFragmentRejection = "invalid";
@@ -5581,6 +5742,8 @@ var IsoBmffTimingResolver = class {
5581
5742
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
5582
5743
  );
5583
5744
  }
5745
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
5746
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
5584
5747
  let freed = 0;
5585
5748
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
5586
5749
  freed += this.#evictOldestFragment();
@@ -5594,6 +5757,7 @@ var IsoBmffTimingResolver = class {
5594
5757
  return false;
5595
5758
  }
5596
5759
  this.#fragments.set(key, [...parsed.samples]);
5760
+ this.#firstSamples.set(key, parsed.samples[0]);
5597
5761
  this.#pendingSamples += parsed.samples.length;
5598
5762
  return true;
5599
5763
  }
@@ -5651,6 +5815,7 @@ var IsoBmffTimingResolver = class {
5651
5815
  let live = 0;
5652
5816
  for (const sample of samples) if (sample !== null) live++;
5653
5817
  this.#fragments.delete(oldest);
5818
+ this.#firstSamples.delete(oldest);
5654
5819
  this.#pendingSamples -= live;
5655
5820
  this.#evictedSamples += live;
5656
5821
  return live;
@@ -5666,12 +5831,23 @@ var IsoBmffTimingResolver = class {
5666
5831
  if (!samples || !samples[index]) return false;
5667
5832
  samples[index] = null;
5668
5833
  this.#pendingSamples--;
5669
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
5834
+ if (samples.every((value) => value === null)) {
5835
+ this.#fragments.delete(key);
5836
+ const first = this.#firstSamples.get(key);
5837
+ this.#firstSamples.delete(key);
5838
+ this.#delivered.delete(key);
5839
+ this.#delivered.set(key, { first, sampleCount: samples.length });
5840
+ if (this.#delivered.size > this.maxPendingSamples) {
5841
+ this.#delivered.delete(this.#delivered.keys().next().value);
5842
+ }
5843
+ }
5670
5844
  return true;
5671
5845
  }
5672
5846
  reset() {
5673
5847
  this.#track = null;
5674
5848
  this.#fragments.clear();
5849
+ this.#firstSamples.clear();
5850
+ this.#delivered.clear();
5675
5851
  this.#pendingSamples = 0;
5676
5852
  }
5677
5853
  };
@@ -5841,6 +6017,9 @@ function authoredGap(before, after) {
5841
6017
  function ssIdAfter(a, b) {
5842
6018
  return (a - b | 0) > 0;
5843
6019
  }
6020
+ function holdsRebuilt(stream) {
6021
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
6022
+ }
5844
6023
  var FecReleaseSequencer = class {
5845
6024
  #streams = /* @__PURE__ */ new Map();
5846
6025
  #gate;
@@ -5903,6 +6082,7 @@ var FecReleaseSequencer = class {
5903
6082
  stream.lastSbn = void 0;
5904
6083
  stream.discontinuity = false;
5905
6084
  stream.rapSsId = void 0;
6085
+ stream.sourced = false;
5906
6086
  }
5907
6087
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
5908
6088
  this.#recordStat("droppedStale");
@@ -5929,6 +6109,7 @@ var FecReleaseSequencer = class {
5929
6109
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
5930
6110
  else hi = mid;
5931
6111
  }
6112
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
5932
6113
  stream.buf.splice(lo, 0, frame);
5933
6114
  this.#drainUnlessDeferred(stream);
5934
6115
  }
@@ -5964,6 +6145,41 @@ var FecReleaseSequencer = class {
5964
6145
  }
5965
6146
  return false;
5966
6147
  }
6148
+ /**
6149
+ * These streams' sink is being replaced by one that has seen no source
6150
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
6151
+ * release to the sink being replaced the frames the unanchored path had
6152
+ * already released to it (#cursorPassed): there they waited in its queue,
6153
+ * which its replacement flushes. A stream that holds none is not drained:
6154
+ * it holds nothing the anchor kept back, and a drain would still force out
6155
+ * a frame held past the hold limit, which before the anchor waited for the
6156
+ * next push. Then treat the streams as unsourced until a source frame is
6157
+ * released.
6158
+ */
6159
+ unsource(packetId, catalogTrackName) {
6160
+ for (const stream of this.#streams.values()) {
6161
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
6162
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
6163
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
6164
+ else this.#drain(stream, true);
6165
+ }
6166
+ stream.sourced = false;
6167
+ }
6168
+ }
6169
+ }
6170
+ /**
6171
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
6172
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
6173
+ * packetId.
6174
+ */
6175
+ holdsRebuilt(packetId, catalogTrackName) {
6176
+ for (const stream of this.#streams.values()) {
6177
+ if (stream.packetId !== packetId) continue;
6178
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
6179
+ if (holdsRebuilt(stream)) return true;
6180
+ }
6181
+ return false;
6182
+ }
5967
6183
  /** Re-evaluate held gaps after FEC state changed. */
5968
6184
  poke(streamKey) {
5969
6185
  if (streamKey !== void 0) {
@@ -6055,16 +6271,32 @@ var FecReleaseSequencer = class {
6055
6271
  last: null,
6056
6272
  lastSbn: void 0,
6057
6273
  discontinuity: false,
6058
- rapSsId: void 0
6274
+ rapSsId: void 0,
6275
+ sourced: false,
6276
+ draining: 0
6059
6277
  };
6060
6278
  this.#streams.set(streamKey, stream);
6061
6279
  }
6062
6280
  return stream;
6063
6281
  }
6064
- #drain(stream) {
6282
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
6283
+ #drain(stream, asUnanchored = false) {
6284
+ stream.draining++;
6285
+ try {
6286
+ this.#drainLoop(stream, asUnanchored);
6287
+ } finally {
6288
+ stream.draining--;
6289
+ }
6290
+ }
6291
+ #drainLoop(stream, asUnanchored) {
6065
6292
  while (stream.buf.length > 0 && stream.last !== null) {
6066
6293
  const head = stream.buf[0];
6067
6294
  const last = stream.last;
6295
+ if (compareFrameOrder(head, last) <= 0) {
6296
+ stream.buf.shift();
6297
+ this.#release(stream, head, void 0);
6298
+ continue;
6299
+ }
6068
6300
  if (stream.discontinuity) {
6069
6301
  stream.discontinuity = false;
6070
6302
  stream.buf.shift();
@@ -6078,9 +6310,10 @@ var FecReleaseSequencer = class {
6078
6310
  }
6079
6311
  const headSbn = head.meta.fecSbn;
6080
6312
  const from = stream.lastSbn ?? headSbn;
6081
- const to = headSbn ?? stream.lastSbn;
6313
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
6082
6314
  let lost = [];
6083
6315
  const unanchored = from === void 0 && to === void 0;
6316
+ let unresolved = false;
6084
6317
  if (from !== void 0 && to !== void 0) {
6085
6318
  const resolved = this.#gate.resolvedLoss(
6086
6319
  stream.packetId,
@@ -6089,7 +6322,8 @@ var FecReleaseSequencer = class {
6089
6322
  Math.max(from, to),
6090
6323
  from
6091
6324
  );
6092
- if (resolved === null) {
6325
+ unresolved = resolved === null;
6326
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
6093
6327
  const heldMs = performance.now() - head.arrivedAtMs;
6094
6328
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
6095
6329
  this.#recordStat("forcedWindowFlushes");
@@ -6097,22 +6331,69 @@ var FecReleaseSequencer = class {
6097
6331
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
6098
6332
  continue;
6099
6333
  }
6100
- lost = resolved;
6334
+ lost = resolved ?? [];
6101
6335
  }
6102
6336
  stream.buf.shift();
6103
6337
  this.#release(
6104
6338
  stream,
6105
6339
  head,
6106
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
6340
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
6107
6341
  );
6108
6342
  }
6109
6343
  }
6344
+ /**
6345
+ * The head has waited out a gap only a late source can still fill
6346
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
6347
+ * the stream when it has (`wakeAt`), since no packet may come by then.
6348
+ */
6349
+ #unrepairableWaitOver(stream, last, head, from, to) {
6350
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
6351
+ if (waitMs === void 0) return false;
6352
+ const atMs = head.arrivedAtMs + waitMs;
6353
+ if (performance.now() >= atMs) return true;
6354
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
6355
+ return false;
6356
+ }
6357
+ /**
6358
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
6359
+ * source cursor holds it unanchored, and neither does a later frame behind
6360
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
6361
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
6362
+ * like each frame that arrived in front of it since (stale there). The head
6363
+ * then goes, decided as it would be unanchored, once a frame the base path
6364
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
6365
+ * marked one: the base path has passed that one, so a frame still missing
6366
+ * before it can only come from a repair. It also goes while no source frame
6367
+ * has been released, when the direct path shows a recovered frame at once.
6368
+ * And it goes at once while a staged switch decides on when frames arrive
6369
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
6370
+ * sink being replaced: unanchored, it had already reached the sink.
6371
+ * The scan also writes: the `passed` marks it sets stay on the frames,
6372
+ * and push marks a frame it inserts in front of a marked one from them.
6373
+ */
6374
+ #cursorPassed(stream, asUnanchored) {
6375
+ let at = -1;
6376
+ for (let i = 0; i < stream.buf.length; i++) {
6377
+ const frame = stream.buf[i];
6378
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
6379
+ frame.passed = true;
6380
+ if (at < 0) at = i;
6381
+ } else if (frame.passed !== true) break;
6382
+ }
6383
+ if (at < 0) return false;
6384
+ return asUnanchored || !stream.sourced || this.#gate.releaseUnanchored?.(stream.packetId, stream.catalogTrackName) === true || stream.buf.some(({ meta }, i) => i > at && meta.fecSbnFirst === void 0 && (meta.recovered !== true || meta.fecSbn !== void 0));
6385
+ }
6110
6386
  #release(stream, frame, decision) {
6387
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
6388
+ if (stale) this.#recordStat("droppedStale");
6111
6389
  if (decision) frame.meta.gapBefore = decision;
6112
6390
  stream.last = frame;
6113
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
6391
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
6392
+ stream.lastSbn = frame.meta.fecSbn;
6393
+ }
6394
+ if (frame.meta.recovered !== true) stream.sourced = true;
6114
6395
  this.#gate.onReleased?.(frame.data, frame.meta);
6115
- this.#emit(frame.data, frame.meta);
6396
+ if (!stale) this.#emit(frame.data, frame.meta);
6116
6397
  }
6117
6398
  };
6118
6399
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -6153,6 +6434,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
6153
6434
  this.#reclaimedTimingSamples = 0;
6154
6435
  this.#evictedTimingSamples = 0;
6155
6436
  this.#rejectedMovieFragments = 0;
6437
+ this.#recoveredHeadsAwaitingTiming = {
6438
+ held: 0,
6439
+ expired: 0,
6440
+ discarded: 0,
6441
+ superseded: 0
6442
+ };
6156
6443
  this.#sequencers = /* @__PURE__ */ new Map();
6157
6444
  this.#fecGate = null;
6158
6445
  this.#fecSequencer = null;
@@ -6261,6 +6548,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6261
6548
  #reclaimedTimingSamples;
6262
6549
  #evictedTimingSamples;
6263
6550
  #rejectedMovieFragments;
6551
+ #recoveredHeadsAwaitingTiming;
6264
6552
  #sequencers;
6265
6553
  #fecGate;
6266
6554
  #fecSequencer;
@@ -6366,11 +6654,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
6366
6654
  /**
6367
6655
  * Typed view of the ISO-BMFF timing-sample budget.
6368
6656
  *
6369
- * This is the acceptance signal for the budget ratchet: `pending` walking
6370
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
6371
- * and it is observable here rather than only as media silently stopping.
6372
- * Per repo policy this is a producer-owned counter -- never infer budget
6373
- * state by parsing logs.
6657
+ * Each stream admits timing against its own window of `capacity` slots
6658
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
6659
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
6660
+ * timing a stream declared and never delivered shows up there. `pending`
6661
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
6662
+ * a producer-owned counter -- never infer budget state by parsing logs.
6374
6663
  */
6375
6664
  get timingBudgetStats() {
6376
6665
  return {
@@ -6381,6 +6670,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
6381
6670
  rejectedMovieFragments: this.#rejectedMovieFragments
6382
6671
  };
6383
6672
  }
6673
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
6674
+ get recoveredHeadsAwaitingTiming() {
6675
+ let pending = 0;
6676
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
6677
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
6678
+ }
6679
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
6680
+ }
6384
6681
  get reorderStats() {
6385
6682
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
6386
6683
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -6422,6 +6719,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
6422
6719
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
6423
6720
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
6424
6721
  }
6722
+ /** See FecReleaseSequencer.unsource. */
6723
+ unsourceFecRelease(packetId, catalogTrackName) {
6724
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
6725
+ }
6726
+ /** See FecReleaseSequencer.holdsRebuilt. */
6727
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
6728
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
6729
+ }
6425
6730
  /** Re-evaluate held gaps after FEC block state changed. */
6426
6731
  pokeFecRelease(packetId, catalogTrackName) {
6427
6732
  if (!this.#fecSequencer) return;
@@ -6554,7 +6859,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6554
6859
  const now = Date.now();
6555
6860
  for (const { awaitingTiming } of this.#timingStreams.values()) {
6556
6861
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
6557
- awaitingTiming.shift();
6862
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
6558
6863
  }
6559
6864
  }
6560
6865
  }
@@ -6672,11 +6977,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
6672
6977
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
6673
6978
  return this.#drop("fragment-unexpected-fragmentation");
6674
6979
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
6675
- if (!resolver2) return this.#drop("fragment-no-resolver");
6980
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
6676
6981
  const pendingBefore = resolver2.pendingSampleCount;
6677
6982
  const evictedBefore = resolver2.evictedSampleCount;
6678
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
6679
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
6983
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
6984
+ const admitted = resolver2.addMovieFragment(
6985
+ mpu.mpuSequenceNumber,
6986
+ data,
6987
+ remaining,
6988
+ options?.recovered === true
6989
+ );
6680
6990
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
6681
6991
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
6682
6992
  if (!admitted) {
@@ -6696,7 +7006,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6696
7006
  };
6697
7007
  }
6698
7008
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
6699
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
7009
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
6700
7010
  if (!resolver) return this.#drop("mfu-no-resolver");
6701
7011
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
6702
7012
  return this.#drop("mfu-empty-payload");
@@ -6717,6 +7027,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6717
7027
  mpuSequenceNumber: mpu.mpuSequenceNumber,
6718
7028
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
6719
7029
  sampleNumber: mfuDuHeader.sampleNumber,
7030
+ sequenceNumber: info.sequenceNumber,
6720
7031
  arrivedAt: Date.now()
6721
7032
  });
6722
7033
  return this.#drop("mfu-sample-timing-missing");
@@ -6742,7 +7053,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
6742
7053
  info,
6743
7054
  resolver,
6744
7055
  options?.recovered === true,
6745
- options?.fecSbn
7056
+ options?.fecSbn,
7057
+ options?.fecSbnFirst
6746
7058
  );
6747
7059
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
6748
7060
  }
@@ -6835,7 +7147,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
6835
7147
  info,
6836
7148
  resolver,
6837
7149
  options?.recovered === true,
6838
- options?.fecSbn
7150
+ options?.fecSbn,
7151
+ options?.fecSbnFirst
6839
7152
  );
6840
7153
  if (outcome.record !== void 0) return outcome.record;
6841
7154
  return this.#drop(outcome.reason);
@@ -6855,7 +7168,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6855
7168
  * attribution exists to keep readable. Leaving the choice at the call site
6856
7169
  * is what keeps both true.
6857
7170
  */
6858
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
7171
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
6859
7172
  const timing = resolver.sampleTiming(
6860
7173
  combined.mpuSequenceNumber,
6861
7174
  combined.movieFragmentSequenceNumber,
@@ -6872,6 +7185,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6872
7185
  );
6873
7186
  if (!meta) return { reason: "combined-meta-build-failed" };
6874
7187
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
7188
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
6875
7189
  if (!resolver.consumeSample(
6876
7190
  combined.mpuSequenceNumber,
6877
7191
  combined.movieFragmentSequenceNumber,
@@ -7040,6 +7354,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
7040
7354
  }
7041
7355
  this.#emitFrame(data, meta);
7042
7356
  }
7357
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
7358
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
7359
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) != null;
7360
+ }
7043
7361
  /**
7044
7362
  * Claim and return the authored timing for a recovered sample. Recovery does
7045
7363
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -7101,6 +7419,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
7101
7419
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
7102
7420
  this.#sequencers.clear();
7103
7421
  this.#fecSequencer?.discard();
7422
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
7423
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
7424
+ }
7104
7425
  this.#timingStreams.clear();
7105
7426
  this.#pendingTimingSamples = 0;
7106
7427
  this.#reliableMoqStartupGate.clear();
@@ -7119,10 +7440,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
7119
7440
  return resolver;
7120
7441
  }
7121
7442
  #awaitTiming(streamKey, head) {
7122
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
7123
- if (!awaitingTiming) return;
7443
+ const state = this.#timingStreams.get(streamKey);
7444
+ if (!state) return;
7445
+ if (!head.options?.recovered) {
7446
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
7447
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
7448
+ state.awaitingTiming = kept;
7449
+ }
7450
+ const awaitingTiming = state.awaitingTiming;
7124
7451
  awaitingTiming.push(head);
7125
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
7452
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
7453
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
7454
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
7455
+ }
7456
+ }
7457
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
7458
+ #leaveAwaitingTiming(head, outcome) {
7459
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
7126
7460
  }
7127
7461
  /**
7128
7462
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -7150,6 +7484,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
7150
7484
  const state = this.#timingStreams.get(streamKey);
7151
7485
  if (!state) return;
7152
7486
  this.#timingStreams.delete(streamKey);
7487
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
7153
7488
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
7154
7489
  if (this.#pendingTimingSamples < 0) {
7155
7490
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");
@@ -7924,7 +8259,7 @@ function validateCmsfMmtpCatalog(value, _options = {}) {
7924
8259
  }
7925
8260
 
7926
8261
  // src/no-modules.ts
7927
- import { catalogFecInterleaveMs, fecBlockBudgetMs as fecBlockBudgetMs2, fecBlockDeadlineMs } from "@blockcast/mmt-fec";
8262
+ import { catalogFecInterleaveMs as catalogFecInterleaveMs2, fecBlockBudgetMs as fecBlockBudgetMs2, fecBlockDeadlineMs } from "@blockcast/mmt-fec";
7928
8263
 
7929
8264
  // src/fec-state.ts
7930
8265
  var FEC_INACTIVE_REASONS = Object.freeze([
@@ -7970,6 +8305,10 @@ function resolveFecState(evidence) {
7970
8305
  return INACTIVE["reliable-moq"];
7971
8306
  }
7972
8307
 
8308
+ // src/catalog-fec-params.ts
8309
+ import { catalogFecInterleaveMs } from "@blockcast/mmt-fec";
8310
+ var MAX_SAFE_TICKS_PER_HZ = Number.MAX_SAFE_INTEGER / 1e3;
8311
+
7973
8312
  // src/mmtp-fec-session.ts
7974
8313
  import { deriveFecRetentionBlocks, fecBlockBudgetMs } from "@blockcast/mmt-fec";
7975
8314
 
@@ -8071,7 +8410,14 @@ var HeldLayerAdmission = class {
8071
8410
  var PATH_BITS = { moq: 1, multicast: 2 };
8072
8411
  var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8073
8412
  var MmtpFecSession = class {
8413
+ /** P_0 = B_0, the held total every repair packet is checked against. */
8414
+ get repairSymbols() {
8415
+ return this.#repairSymbols;
8416
+ }
8074
8417
  #decoder;
8418
+ #repairSymbols;
8419
+ /** The message entry a catalog-less session was built from; undefined under a catalog. */
8420
+ #message;
8075
8421
  /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
8076
8422
  #blocks = /* @__PURE__ */ new Map();
8077
8423
  /** SS_Starts of settled blocks, so a later repair for one is refused. */
@@ -8109,6 +8455,24 @@ var MmtpFecSession = class {
8109
8455
  * `interleaveDepthMs` or `reorderToleranceMs`. None is defaulted.
8110
8456
  */
8111
8457
  constructor(config) {
8458
+ if (config && "alFecFlow" in config) {
8459
+ const message = alFecRaptorQFlowConfig(config.alFecFlow);
8460
+ if (!message) {
8461
+ throw new Error("MmtpFecSession: the AL-FEC entry is outside draft-ramadan-moq-mmt-02 8.3 (iso-ssbg1-v1)");
8462
+ }
8463
+ this.#message = message;
8464
+ this.blockProfile = parseFecBlockProfile("iso-ssbg1-v1", "alFecFlow");
8465
+ this.algorithm = message.fecCodeId === FEC_CODE_RAPTORQ ? "raptorq" : "reed-solomon";
8466
+ this.sourceSymbols = message.maximumK;
8467
+ this.#repairSymbols = message.maximumP;
8468
+ this.symbolSize = message.repairSymbolSize;
8469
+ this.retentionBlocks = requirePositiveInteger(config.retentionBlocks, "retentionBlocks");
8470
+ this.#repairPacketId = message.repairFlowId;
8471
+ this.#heldLayers = layerZero(message.maximumP);
8472
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
8473
+ this.#decoder = buildDecoder(config.Decoder, this);
8474
+ return;
8475
+ }
8112
8476
  const fec = config?.fec;
8113
8477
  if (!fec || typeof fec !== "object") {
8114
8478
  throw new Error("MmtpFecSession: the catalog fec instance is required");
@@ -8119,7 +8483,7 @@ var MmtpFecSession = class {
8119
8483
  }
8120
8484
  this.algorithm = fec.scheme;
8121
8485
  this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8122
- this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
8486
+ this.#repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
8123
8487
  this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8124
8488
  const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8125
8489
  const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
@@ -8139,17 +8503,30 @@ var MmtpFecSession = class {
8139
8503
  config.heldLayers
8140
8504
  );
8141
8505
  this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols);
8142
- if (typeof config.Decoder !== "function") {
8143
- throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8144
- }
8145
- const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
8146
- try {
8147
- decoder.configure_params(this.sourceSymbols, this.symbolSize);
8148
- } catch (error) {
8149
- decoder.free();
8150
- throw error;
8151
- }
8152
- this.#decoder = decoder;
8506
+ this.#decoder = buildDecoder(config.Decoder, this);
8507
+ }
8508
+ /**
8509
+ * A later version of the AL-FEC message, catalog-less sessions only. A
8510
+ * maximum_p_for_repair_flow above the held total raises it (`raised`): the
8511
+ * anchored check restarts at the new total, so a block generated under the
8512
+ * previous one stays valid before the first block carrying the new total
8513
+ * (fec-core-00 7.3.2, mmt-02 8.3). A field at or below it changes nothing
8514
+ * (`unchanged`): no publisher lowers it, and the check catches a wire that
8515
+ * does. An entry with another asset, repair flow, code point, K or T, or
8516
+ * one outside 8.3, is `refused`: that is a new source encoding, which needs
8517
+ * a new session. A latched fail-closed stays latched either way.
8518
+ */
8519
+ updateAlFecFlow(flow) {
8520
+ const held = this.#message;
8521
+ if (!held) throw new Error("MmtpFecSession: updateAlFecFlow() needs a session built from an AL-FEC entry");
8522
+ const next = alFecRaptorQFlowConfig(flow);
8523
+ if (!next || next.sourcePacketIds[0] !== held.sourcePacketIds[0] || next.repairFlowId !== held.repairFlowId || next.fecCodeId !== held.fecCodeId || next.maximumK !== held.maximumK || next.repairSymbolSize !== held.repairSymbolSize) {
8524
+ return "refused";
8525
+ }
8526
+ if (next.maximumP <= this.#repairSymbols) return "unchanged";
8527
+ this.#repairSymbols = next.maximumP;
8528
+ this.#heldLayers = layerZero(next.maximumP);
8529
+ return "raised";
8153
8530
  }
8154
8531
  /** True once release() ran. */
8155
8532
  get released() {
@@ -8244,7 +8621,7 @@ var MmtpFecSession = class {
8244
8621
  }
8245
8622
  if (admission.reject) {
8246
8623
  const verdict2 = this.#heldLayers.failsClosed(
8247
- repairTrackName,
8624
+ this.#trackFor(repairTrackName),
8248
8625
  frame.ssStart,
8249
8626
  frame.rsbLength,
8250
8627
  this.#anchorHorizon,
@@ -8259,7 +8636,7 @@ var MmtpFecSession = class {
8259
8636
  this.#repairPacketId ??= frame.packetId;
8260
8637
  if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
8261
8638
  const verdict = this.#heldLayers.admit(
8262
- repairTrackName,
8639
+ this.#trackFor(repairTrackName),
8263
8640
  frame.ssStart,
8264
8641
  frame.rsbLength,
8265
8642
  this.#anchorHorizon,
@@ -8318,6 +8695,10 @@ var MmtpFecSession = class {
8318
8695
  decoder.free();
8319
8696
  return true;
8320
8697
  }
8698
+ /** Catalog-less: layer 0 has no own-track clause (mmt-02 8.3), so no track name is judged. */
8699
+ #trackFor(repairTrackName) {
8700
+ return this.#message ? void 0 : repairTrackName;
8701
+ }
8321
8702
  #drop(reason) {
8322
8703
  this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
8323
8704
  return [];
@@ -8439,6 +8820,22 @@ var MmtpFecSession = class {
8439
8820
  }
8440
8821
  }
8441
8822
  };
8823
+ function layerZero(total) {
8824
+ return new HeldLayerAdmission([{ layer: 0, repairTrackName: "", rsIdOffset: 0, repairSymbols: total }]);
8825
+ }
8826
+ function buildDecoder(Decoder, session) {
8827
+ if (typeof Decoder !== "function") {
8828
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8829
+ }
8830
+ const decoder = new Decoder(session.retentionBlocks, session.blockProfile, session.algorithm);
8831
+ try {
8832
+ decoder.configure_params(session.sourceSymbols, session.symbolSize);
8833
+ } catch (error) {
8834
+ decoder.free();
8835
+ throw error;
8836
+ }
8837
+ return decoder;
8838
+ }
8442
8839
  function requirePositiveInteger(value, path) {
8443
8840
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
8444
8841
  throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
@@ -11902,7 +12299,7 @@ export {
11902
12299
  catalogAmtNetworkSource,
11903
12300
  catalogAtsc3NetworkSource,
11904
12301
  catalogDeclaresFec,
11905
- catalogFecInterleaveMs,
12302
+ catalogFecInterleaveMs2 as catalogFecInterleaveMs,
11906
12303
  createWasmMmtpContainerParser,
11907
12304
  datagramMfuReassembly,
11908
12305
  fecBlockBudgetMs2 as fecBlockBudgetMs,
@@ -11912,7 +12309,9 @@ export {
11912
12309
  reliableMoqMfuReassembly,
11913
12310
  resolveFecState,
11914
12311
  resolveGroupDurationMs,
11915
- validateCmsfMmtpCatalog
12312
+ runtimeFecCatalogReport,
12313
+ validateCmsfMmtpCatalog,
12314
+ validateFecCatalog
11916
12315
  };
11917
12316
  /*! Bundled license information:
11918
12317