@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
@@ -148,30 +148,26 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
148
148
  const authLength = view2.getUint16(2, false);
149
149
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
150
150
  }
151
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
151
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
152
152
  if (declaredEnd > payload.length)
153
153
  return null;
154
154
  if (options?.skipFecId) {
155
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
155
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
156
156
  }
157
- const overlay = options?.overlayDeclared === true && rapFlag;
158
157
  if (fecType === 1) {
159
- const fecStart = payload.length - sourceFecTrailerSize(overlay);
158
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
160
159
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
161
160
  return null;
162
161
  }
163
- return { hasFecId: true, hasOverlayFecId: overlay };
162
+ return { hasFecId: true };
164
163
  }
165
- if (fecType !== 0 || overlay)
164
+ if (fecType !== 0)
166
165
  return null;
167
166
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
168
- return { hasFecId: false, hasOverlayFecId: false };
167
+ return { hasFecId: false };
169
168
  }
170
169
  return null;
171
170
  }
172
- function sourceFecTrailerSize(overlay) {
173
- return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
174
- }
175
171
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
176
172
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
177
173
  return {
@@ -224,11 +220,11 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
224
220
  if ("rejection" in layoutResult)
225
221
  return layoutResult;
226
222
  const { layout } = layoutResult;
227
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
223
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
228
224
  if (!trailerLayout) {
229
225
  if (!options?.skipFecId && header.fecType === 1) {
230
226
  const observed = payload.length - layout.dataEnd;
231
- const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
227
+ const expected = SOURCE_FEC_PAYLOAD_ID_SIZE;
232
228
  if (observed !== expected) {
233
229
  return {
234
230
  rejection: {
@@ -260,13 +256,10 @@ function extractPlannedMfu(mmtpPacket, result) {
260
256
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
261
257
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
262
258
  const data = payload.subarray(mfuOffset, dataEnd);
263
- const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
264
- const ssIdAt = (offset) => ({
265
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
266
- });
267
- const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
268
- const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
269
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
259
+ const fecPayloadId = trailerLayout.hasFecId ? {
260
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, 4).getUint32(0, false)
261
+ } : null;
262
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
270
263
  }
271
264
  function sourceFecPayloadIdOf(mmtpPacket, header) {
272
265
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -3882,9 +3875,10 @@ function isH264IntraSlice(nal) {
3882
3875
  const sliceType = readH264SliceType(nal);
3883
3876
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9;
3884
3877
  }
3878
+ var H264_SLICE_TYPE_ESCAPED_BYTES = 32;
3885
3879
  function readH264SliceType(nal) {
3886
3880
  if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
3887
- const rbsp = removeEmulationPrevention(nal.subarray(1));
3881
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES));
3888
3882
  const state = { bitOffset: 0 };
3889
3883
  if (readUnsignedExpGolomb(rbsp, state) === null) return null;
3890
3884
  return readUnsignedExpGolomb(rbsp, state);
@@ -4031,6 +4025,96 @@ if (void 0) {
4031
4025
  ]))).toBe(false);
4032
4026
  });
4033
4027
  });
4028
+ describe("readH264SliceType", () => {
4029
+ const wholeNalSliceType = (nal) => {
4030
+ if (nal.length < 2 || (nal[0] & 31) !== 1) return null;
4031
+ const rbsp = removeEmulationPrevention(nal.subarray(1));
4032
+ const state = { bitOffset: 0 };
4033
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null;
4034
+ return readUnsignedExpGolomb(rbsp, state);
4035
+ };
4036
+ const hex = (text) => Uint8Array.from(text.match(/../g), (byte) => parseInt(byte, 16));
4037
+ const ue = (value) => {
4038
+ const code = (value + 1).toString(2);
4039
+ return "0".repeat(code.length - 1) + code;
4040
+ };
4041
+ const sliceNal = (bits) => {
4042
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, "0").match(/.{8}/g);
4043
+ const nal = [1];
4044
+ let zeros = 0;
4045
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
4046
+ if (zeros >= 2 && byte <= 3) {
4047
+ nal.push(3);
4048
+ zeros = 0;
4049
+ }
4050
+ nal.push(byte);
4051
+ zeros = byte === 0 ? zeros + 1 : 0;
4052
+ }
4053
+ return Uint8Array.from(nal);
4054
+ };
4055
+ const x264Slices = [
4056
+ ["64x48 P", hex("419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176"), 5, false],
4057
+ ["64x48 B", hex("419e414212fffeeade283707cb70f7"), 6, false],
4058
+ ["64x48 non-IDR I", hex(
4059
+ "4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39a527e23eb34c8167fd"
4060
+ ), 7, true],
4061
+ ["1280x720 B, escape at byte 10", hex(
4062
+ "01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e19b75d92170917306190f262fd58268702db2eff86a9651e48"
4063
+ ), 6, false],
4064
+ ["1280x720 P, escape at byte 15", hex(
4065
+ "41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f02c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e85302da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3"
4066
+ ), 5, false],
4067
+ ["1280x720 B, escape at byte 22", hex("01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352"), 6, false],
4068
+ ["7680x4320 IDR, first_mb_in_slice 97440", hex(
4069
+ "650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9"
4070
+ ), null, true],
4071
+ ["7680x4320 P, first_mb_in_slice 32640", hex(
4072
+ "410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020"
4073
+ ), 5, false],
4074
+ ["7680x4320 P, first_mb_in_slice 97440", hex(
4075
+ "410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806"
4076
+ ), 5, false]
4077
+ ];
4078
+ const syntheticSlices = [
4079
+ ["an escape inside first_mb_in_slice", sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
4080
+ ["an escape between the fields", sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
4081
+ ["an escape inside slice_type", sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
4082
+ ["the longest fields, five escapes", sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
4083
+ ["the largest values", sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
4084
+ ["31 leading zeros in first_mb_in_slice", sliceNal(`${"0".repeat(31)}1`), null],
4085
+ ["31 leading zeros in slice_type", sliceNal(`1${"0".repeat(31)}1`), null],
4086
+ ["escapes running past the slice header", sliceNal(ue(0) + ue(5) + "0".repeat(400)), 5]
4087
+ ];
4088
+ test("reads the slice_type of real and synthetic slices", () => {
4089
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
4090
+ expect(readH264SliceType(nal), name).toBe(sliceType);
4091
+ }
4092
+ });
4093
+ test("matches the whole-NAL unescape at every truncation", () => {
4094
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
4095
+ for (let end = 0; end <= nal.length; end++) {
4096
+ const cut = nal.subarray(0, end);
4097
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut));
4098
+ }
4099
+ }
4100
+ });
4101
+ test("matches the whole-NAL unescape on zero-heavy NAL units", () => {
4102
+ const bytes = [0, 0, 0, 3, 1, 2, 128, 255];
4103
+ let seed = 1;
4104
+ const next = () => (seed = Math.imul(seed, 1103515245) + 12345 >>> 0) >>> 16;
4105
+ for (let i = 0; i < 5e3; i++) {
4106
+ const nal = new Uint8Array(2 + next() % 63);
4107
+ nal[0] = 65;
4108
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length];
4109
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal));
4110
+ }
4111
+ });
4112
+ test("classifies the x264 slices as keyframes or not", () => {
4113
+ for (const [name, nal, , keyframe] of x264Slices) {
4114
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe);
4115
+ }
4116
+ });
4117
+ });
4034
4118
  describe("avccToAnnexB", () => {
4035
4119
  test("converts with SPS/PPS on keyframe", () => {
4036
4120
  const avcc = new Uint8Array([0, 0, 0, 3, 101, 170, 187]);
@@ -4858,9 +4942,21 @@ var IsoBmffTimingResolver = class {
4858
4942
  }
4859
4943
  #track = null;
4860
4944
  #fragments = /* @__PURE__ */ new Map();
4945
+ /** First sample of each pending fragment, kept in `#delivered` with its sample count. */
4946
+ #firstSamples = /* @__PURE__ */ new Map();
4947
+ /**
4948
+ * First sample and sample count of the newest fragments whose every slot was
4949
+ * cleared. Abandonment counts: `releaseSample` clears a slot too, which
4950
+ * matches the combiner, since it retires an abandoned sample as well.
4951
+ */
4952
+ #delivered = /* @__PURE__ */ new Map();
4861
4953
  #pendingSamples = 0;
4862
4954
  #evictedSamples = 0;
4863
4955
  #lastMovieFragmentRejection = null;
4956
+ /** True once an FT=0 has bound the track that FT=1 timing is read against. */
4957
+ get initialized() {
4958
+ return this.#track !== null;
4959
+ }
4864
4960
  get pendingSampleCount() {
4865
4961
  return this.#pendingSamples;
4866
4962
  }
@@ -4884,7 +4980,14 @@ var IsoBmffTimingResolver = class {
4884
4980
  this.#track = timing;
4885
4981
  return true;
4886
4982
  }
4887
- addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples) {
4983
+ /**
4984
+ * `recovered` marks an FEC-recovered copy. A recovered block hands back
4985
+ * every FT=1 it holds, the received ones included, so a recovered copy of a
4986
+ * fragment whose samples are all done is a duplicate: admitting it again
4987
+ * would charge stale timing and could displace the live MPU's. A source
4988
+ * copy is still admitted again (a rendition switch re-arms timing that way).
4989
+ */
4990
+ addMovieFragment(mpuSequenceNumber, data, additionalSampleLimit = this.maxPendingSamples, recovered = false) {
4888
4991
  this.#lastMovieFragmentRejection = null;
4889
4992
  if (!Number.isInteger(additionalSampleLimit) || additionalSampleLimit < 0) {
4890
4993
  this.#lastMovieFragmentRejection = "invalid";
@@ -4910,6 +5013,8 @@ var IsoBmffTimingResolver = class {
4910
5013
  (sample, index) => sample !== null && sameSample(sample, parsed.samples[index])
4911
5014
  );
4912
5015
  }
5016
+ const delivered = recovered ? this.#delivered.get(key) : void 0;
5017
+ if (delivered && delivered.sampleCount === parsed.samples.length && sameSample(delivered.first, parsed.samples[0])) return true;
4913
5018
  let freed = 0;
4914
5019
  while (this.#fragments.size > 0 && (this.#pendingSamples + parsed.samples.length > this.maxPendingSamples || parsed.samples.length - freed > additionalSampleLimit)) {
4915
5020
  freed += this.#evictOldestFragment();
@@ -4923,6 +5028,7 @@ var IsoBmffTimingResolver = class {
4923
5028
  return false;
4924
5029
  }
4925
5030
  this.#fragments.set(key, [...parsed.samples]);
5031
+ this.#firstSamples.set(key, parsed.samples[0]);
4926
5032
  this.#pendingSamples += parsed.samples.length;
4927
5033
  return true;
4928
5034
  }
@@ -4980,6 +5086,7 @@ var IsoBmffTimingResolver = class {
4980
5086
  let live = 0;
4981
5087
  for (const sample of samples) if (sample !== null) live++;
4982
5088
  this.#fragments.delete(oldest);
5089
+ this.#firstSamples.delete(oldest);
4983
5090
  this.#pendingSamples -= live;
4984
5091
  this.#evictedSamples += live;
4985
5092
  return live;
@@ -4995,12 +5102,23 @@ var IsoBmffTimingResolver = class {
4995
5102
  if (!samples || !samples[index]) return false;
4996
5103
  samples[index] = null;
4997
5104
  this.#pendingSamples--;
4998
- if (samples.every((value) => value === null)) this.#fragments.delete(key);
5105
+ if (samples.every((value) => value === null)) {
5106
+ this.#fragments.delete(key);
5107
+ const first = this.#firstSamples.get(key);
5108
+ this.#firstSamples.delete(key);
5109
+ this.#delivered.delete(key);
5110
+ this.#delivered.set(key, { first, sampleCount: samples.length });
5111
+ if (this.#delivered.size > this.maxPendingSamples) {
5112
+ this.#delivered.delete(this.#delivered.keys().next().value);
5113
+ }
5114
+ }
4999
5115
  return true;
5000
5116
  }
5001
5117
  reset() {
5002
5118
  this.#track = null;
5003
5119
  this.#fragments.clear();
5120
+ this.#firstSamples.clear();
5121
+ this.#delivered.clear();
5004
5122
  this.#pendingSamples = 0;
5005
5123
  }
5006
5124
  };
@@ -5170,6 +5288,9 @@ function authoredGap(before, after) {
5170
5288
  function ssIdAfter(a, b) {
5171
5289
  return (a - b | 0) > 0;
5172
5290
  }
5291
+ function holdsRebuilt(stream) {
5292
+ return stream.buf.some(({ meta }) => meta.fecSbnFirst !== void 0);
5293
+ }
5173
5294
  var FecReleaseSequencer = class {
5174
5295
  #streams = /* @__PURE__ */ new Map();
5175
5296
  #gate;
@@ -5232,6 +5353,7 @@ var FecReleaseSequencer = class {
5232
5353
  stream.lastSbn = void 0;
5233
5354
  stream.discontinuity = false;
5234
5355
  stream.rapSsId = void 0;
5356
+ stream.sourced = false;
5235
5357
  }
5236
5358
  if (stream.last !== null && compareFrameOrder(frame, stream.last) <= 0) {
5237
5359
  this.#recordStat("droppedStale");
@@ -5258,6 +5380,7 @@ var FecReleaseSequencer = class {
5258
5380
  if (compareFrameOrder(stream.buf[mid], frame) < 0) lo = mid + 1;
5259
5381
  else hi = mid;
5260
5382
  }
5383
+ if (stream.buf[lo]?.passed === true) frame.passed = true;
5261
5384
  stream.buf.splice(lo, 0, frame);
5262
5385
  this.#drainUnlessDeferred(stream);
5263
5386
  }
@@ -5293,6 +5416,41 @@ var FecReleaseSequencer = class {
5293
5416
  }
5294
5417
  return false;
5295
5418
  }
5419
+ /**
5420
+ * These streams' sink is being replaced by one that has seen no source
5421
+ * frame yet. First, from a stream that holds a frame the overlay rebuilt,
5422
+ * release to the sink being replaced the frames the unanchored path had
5423
+ * already released to it (#cursorPassed): there they waited in its queue,
5424
+ * which its replacement flushes. A stream that holds none is not drained:
5425
+ * it holds nothing the anchor kept back, and a drain would still force out
5426
+ * a frame held past the hold limit, which before the anchor waited for the
5427
+ * next push. Then treat the streams as unsourced until a source frame is
5428
+ * released.
5429
+ */
5430
+ unsource(packetId, catalogTrackName) {
5431
+ for (const stream of this.#streams.values()) {
5432
+ if (stream.packetId === packetId && (catalogTrackName === void 0 || stream.catalogTrackName === catalogTrackName)) {
5433
+ if (stream.draining === 0 && holdsRebuilt(stream)) {
5434
+ if (this.#deferDepth > 0) this.#deferredStreams.add(stream);
5435
+ else this.#drain(stream, true);
5436
+ }
5437
+ stream.sourced = false;
5438
+ }
5439
+ }
5440
+ }
5441
+ /**
5442
+ * Whether a stream of `packetId` holds a frame the keyframe overlay rebuilt
5443
+ * (FrameMeta.fecSbnFirst). Without `catalogTrackName`, every stream of the
5444
+ * packetId.
5445
+ */
5446
+ holdsRebuilt(packetId, catalogTrackName) {
5447
+ for (const stream of this.#streams.values()) {
5448
+ if (stream.packetId !== packetId) continue;
5449
+ if (catalogTrackName !== void 0 && stream.catalogTrackName !== catalogTrackName) continue;
5450
+ if (holdsRebuilt(stream)) return true;
5451
+ }
5452
+ return false;
5453
+ }
5296
5454
  /** Re-evaluate held gaps after FEC state changed. */
5297
5455
  poke(streamKey) {
5298
5456
  if (streamKey !== void 0) {
@@ -5384,16 +5542,32 @@ var FecReleaseSequencer = class {
5384
5542
  last: null,
5385
5543
  lastSbn: void 0,
5386
5544
  discontinuity: false,
5387
- rapSsId: void 0
5545
+ rapSsId: void 0,
5546
+ sourced: false,
5547
+ draining: 0
5388
5548
  };
5389
5549
  this.#streams.set(streamKey, stream);
5390
5550
  }
5391
5551
  return stream;
5392
5552
  }
5393
- #drain(stream) {
5553
+ /** `asUnanchored`: release overlay-rebuilt frames when unanchored did (#cursorPassed). */
5554
+ #drain(stream, asUnanchored = false) {
5555
+ stream.draining++;
5556
+ try {
5557
+ this.#drainLoop(stream, asUnanchored);
5558
+ } finally {
5559
+ stream.draining--;
5560
+ }
5561
+ }
5562
+ #drainLoop(stream, asUnanchored) {
5394
5563
  while (stream.buf.length > 0 && stream.last !== null) {
5395
5564
  const head = stream.buf[0];
5396
5565
  const last = stream.last;
5566
+ if (compareFrameOrder(head, last) <= 0) {
5567
+ stream.buf.shift();
5568
+ this.#release(stream, head, void 0);
5569
+ continue;
5570
+ }
5397
5571
  if (stream.discontinuity) {
5398
5572
  stream.discontinuity = false;
5399
5573
  stream.buf.shift();
@@ -5407,9 +5581,10 @@ var FecReleaseSequencer = class {
5407
5581
  }
5408
5582
  const headSbn = head.meta.fecSbn;
5409
5583
  const from = stream.lastSbn ?? headSbn;
5410
- const to = headSbn ?? stream.lastSbn;
5584
+ const to = head.meta.fecSbnFirst ?? headSbn ?? stream.lastSbn;
5411
5585
  let lost = [];
5412
5586
  const unanchored = from === void 0 && to === void 0;
5587
+ let unresolved = false;
5413
5588
  if (from !== void 0 && to !== void 0) {
5414
5589
  const resolved = this.#gate.resolvedLoss(
5415
5590
  stream.packetId,
@@ -5418,7 +5593,8 @@ var FecReleaseSequencer = class {
5418
5593
  Math.max(from, to),
5419
5594
  from
5420
5595
  );
5421
- if (resolved === null) {
5596
+ unresolved = resolved === null;
5597
+ if (unresolved && !this.#cursorPassed(stream, asUnanchored) && !this.#unrepairableWaitOver(stream, last, head, from, to)) {
5422
5598
  const heldMs = performance.now() - head.arrivedAtMs;
5423
5599
  if (heldMs <= this.#gate.holdLimitMs(stream.packetId, stream.catalogTrackName)) return;
5424
5600
  this.#recordStat("forcedWindowFlushes");
@@ -5426,22 +5602,69 @@ var FecReleaseSequencer = class {
5426
5602
  this.#release(stream, head, this.#gate.decide(last, head, [], true));
5427
5603
  continue;
5428
5604
  }
5429
- lost = resolved;
5605
+ lost = resolved ?? [];
5430
5606
  }
5431
5607
  stream.buf.shift();
5432
5608
  this.#release(
5433
5609
  stream,
5434
5610
  head,
5435
- lost.length > 0 || unanchored || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
5611
+ lost.length > 0 || unanchored || unresolved || authoredGap(last.meta, head.meta) ? this.#gate.decide(last, head, lost, false) : void 0
5436
5612
  );
5437
5613
  }
5438
5614
  }
5615
+ /**
5616
+ * The head has waited out a gap only a late source can still fill
5617
+ * (FecReleaseGate.unrepairableWaitMs). Not yet: the gate is asked to poke
5618
+ * the stream when it has (`wakeAt`), since no packet may come by then.
5619
+ */
5620
+ #unrepairableWaitOver(stream, last, head, from, to) {
5621
+ const waitMs = this.#gate.unrepairableWaitMs?.(last, head, from, to);
5622
+ if (waitMs === void 0) return false;
5623
+ const atMs = head.arrivedAtMs + waitMs;
5624
+ if (performance.now() >= atMs) return true;
5625
+ this.#gate.wakeAt?.(stream.packetId, stream.catalogTrackName, atMs);
5626
+ return false;
5627
+ }
5628
+ /**
5629
+ * An overlay-rebuilt frame (fecSbnFirst) waits no longer than the BLO-53342
5630
+ * source cursor holds it unanchored, and neither does a later frame behind
5631
+ * it. Unanchored, a frame that waits on no block (fecSbnFirst set, or no
5632
+ * fecSbn) left the gate once every frame ahead of it had: mark it `passed`,
5633
+ * like each frame that arrived in front of it since (stale there). The head
5634
+ * then goes, decided as it would be unanchored, once a frame the base path
5635
+ * delivered (a source frame, or one base FEC recovered) is buffered after a
5636
+ * marked one: the base path has passed that one, so a frame still missing
5637
+ * before it can only come from a repair. It also goes while no source frame
5638
+ * has been released, when the direct path shows a recovered frame at once.
5639
+ * And it goes at once while a staged switch decides on when frames arrive
5640
+ * (FecReleaseGate.releaseUnanchored), and when unsource releases into a
5641
+ * sink being replaced: unanchored, it had already reached the sink.
5642
+ * The scan also writes: the `passed` marks it sets stay on the frames,
5643
+ * and push marks a frame it inserts in front of a marked one from them.
5644
+ */
5645
+ #cursorPassed(stream, asUnanchored) {
5646
+ let at = -1;
5647
+ for (let i = 0; i < stream.buf.length; i++) {
5648
+ const frame = stream.buf[i];
5649
+ if (frame.meta.fecSbnFirst !== void 0 || frame.meta.fecSbn === void 0) {
5650
+ frame.passed = true;
5651
+ if (at < 0) at = i;
5652
+ } else if (frame.passed !== true) break;
5653
+ }
5654
+ if (at < 0) return false;
5655
+ 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));
5656
+ }
5439
5657
  #release(stream, frame, decision) {
5658
+ const stale = stream.last !== null && compareFrameOrder(frame, stream.last) <= 0;
5659
+ if (stale) this.#recordStat("droppedStale");
5440
5660
  if (decision) frame.meta.gapBefore = decision;
5441
5661
  stream.last = frame;
5442
- if (frame.meta.fecSbn !== void 0) stream.lastSbn = frame.meta.fecSbn;
5662
+ if (frame.meta.fecSbn !== void 0 && (frame.meta.fecSbnFirst === void 0 || stream.lastSbn !== void 0)) {
5663
+ stream.lastSbn = frame.meta.fecSbn;
5664
+ }
5665
+ if (frame.meta.recovered !== true) stream.sourced = true;
5443
5666
  this.#gate.onReleased?.(frame.data, frame.meta);
5444
- this.#emit(frame.data, frame.meta);
5667
+ if (!stale) this.#emit(frame.data, frame.meta);
5445
5668
  }
5446
5669
  };
5447
5670
  var FMPU_BOX_TYPES = /* @__PURE__ */ new Set(["ftyp", "moov", "moof"]);
@@ -5482,6 +5705,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
5482
5705
  this.#reclaimedTimingSamples = 0;
5483
5706
  this.#evictedTimingSamples = 0;
5484
5707
  this.#rejectedMovieFragments = 0;
5708
+ this.#recoveredHeadsAwaitingTiming = {
5709
+ held: 0,
5710
+ expired: 0,
5711
+ discarded: 0,
5712
+ superseded: 0
5713
+ };
5485
5714
  this.#sequencers = /* @__PURE__ */ new Map();
5486
5715
  this.#fecGate = null;
5487
5716
  this.#fecSequencer = null;
@@ -5590,6 +5819,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5590
5819
  #reclaimedTimingSamples;
5591
5820
  #evictedTimingSamples;
5592
5821
  #rejectedMovieFragments;
5822
+ #recoveredHeadsAwaitingTiming;
5593
5823
  #sequencers;
5594
5824
  #fecGate;
5595
5825
  #fecSequencer;
@@ -5695,11 +5925,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
5695
5925
  /**
5696
5926
  * Typed view of the ISO-BMFF timing-sample budget.
5697
5927
  *
5698
- * This is the acceptance signal for the budget ratchet: `pending` walking
5699
- * to `capacity` while `rejectedMovieFragments` climbs is the stream wedging,
5700
- * and it is observable here rather than only as media silently stopping.
5701
- * Per repo policy this is a producer-owned counter -- never infer budget
5702
- * state by parsing logs.
5928
+ * Each stream admits timing against its own window of `capacity` slots
5929
+ * (BLO-52085). A stream at capacity displaces its own oldest timing to
5930
+ * admit the moof in hand, and `evicted` counts the slots so displaced:
5931
+ * timing a stream declared and never delivered shows up there. `pending`
5932
+ * sums every stream, so it can exceed `capacity`. Per repo policy this is
5933
+ * a producer-owned counter -- never infer budget state by parsing logs.
5703
5934
  */
5704
5935
  get timingBudgetStats() {
5705
5936
  return {
@@ -5710,6 +5941,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
5710
5941
  rejectedMovieFragments: this.#rejectedMovieFragments
5711
5942
  };
5712
5943
  }
5944
+ /** Recovered heads parked for FT=1 timing (BLO-53369). Survives dispose(). */
5945
+ get recoveredHeadsAwaitingTiming() {
5946
+ let pending = 0;
5947
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
5948
+ for (const head of awaitingTiming) if (head.options?.recovered) pending++;
5949
+ }
5950
+ return { ...this.#recoveredHeadsAwaitingTiming, pending };
5951
+ }
5713
5952
  get reorderStats() {
5714
5953
  let bufferedFrames = this.#fecSequencer?.buffered ?? 0;
5715
5954
  for (const { sequencer } of this.#sequencers.values()) bufferedFrames += sequencer.buffered;
@@ -5751,6 +5990,14 @@ var MmtpContainerParser = class _MmtpContainerParser {
5751
5990
  fecReleaseRapAbove(packetId, catalogTrackName, ssId) {
5752
5991
  return this.#fecSequencer?.rapAbove(packetId, catalogTrackName, ssId) ?? false;
5753
5992
  }
5993
+ /** See FecReleaseSequencer.unsource. */
5994
+ unsourceFecRelease(packetId, catalogTrackName) {
5995
+ this.#fecSequencer?.unsource(packetId, catalogTrackName);
5996
+ }
5997
+ /** See FecReleaseSequencer.holdsRebuilt. */
5998
+ fecReleaseHoldsRebuilt(packetId, catalogTrackName) {
5999
+ return this.#fecSequencer?.holdsRebuilt(packetId, catalogTrackName) ?? false;
6000
+ }
5754
6001
  /** Re-evaluate held gaps after FEC block state changed. */
5755
6002
  pokeFecRelease(packetId, catalogTrackName) {
5756
6003
  if (!this.#fecSequencer) return;
@@ -5883,7 +6130,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5883
6130
  const now = Date.now();
5884
6131
  for (const { awaitingTiming } of this.#timingStreams.values()) {
5885
6132
  while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
5886
- awaitingTiming.shift();
6133
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
5887
6134
  }
5888
6135
  }
5889
6136
  }
@@ -6001,11 +6248,16 @@ var MmtpContainerParser = class _MmtpContainerParser {
6001
6248
  if (mpu.fragmentationIndicator !== 0 || mpu.fragmentCounter !== 0)
6002
6249
  return this.#drop("fragment-unexpected-fragmentation");
6003
6250
  const resolver2 = this.#timingResolver(streamKey, info.packetId, false);
6004
- if (!resolver2) return this.#drop("fragment-no-resolver");
6251
+ if (!resolver2?.initialized) return this.#drop("fragment-no-resolver");
6005
6252
  const pendingBefore = resolver2.pendingSampleCount;
6006
6253
  const evictedBefore = resolver2.evictedSampleCount;
6007
- const remaining = this.#maxPendingTimingSamples - this.#pendingTimingSamples;
6008
- const admitted = resolver2.addMovieFragment(mpu.mpuSequenceNumber, data, remaining);
6254
+ const remaining = this.#maxPendingTimingSamples - resolver2.pendingSampleCount;
6255
+ const admitted = resolver2.addMovieFragment(
6256
+ mpu.mpuSequenceNumber,
6257
+ data,
6258
+ remaining,
6259
+ options?.recovered === true
6260
+ );
6009
6261
  this.#pendingTimingSamples += resolver2.pendingSampleCount - pendingBefore;
6010
6262
  this.#evictedTimingSamples += resolver2.evictedSampleCount - evictedBefore;
6011
6263
  if (!admitted) {
@@ -6025,7 +6277,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6025
6277
  };
6026
6278
  }
6027
6279
  if (fragmentType !== 2) return this.#drop("unknown-fragment-type");
6028
- const resolver = this.#timingResolver(streamKey, info.packetId, false);
6280
+ const resolver = this.#timingResolver(streamKey, info.packetId, true);
6029
6281
  if (!resolver) return this.#drop("mfu-no-resolver");
6030
6282
  if (!Number.isSafeInteger(data.byteLength) || data.byteLength <= 0)
6031
6283
  return this.#drop("mfu-empty-payload");
@@ -6046,6 +6298,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6046
6298
  mpuSequenceNumber: mpu.mpuSequenceNumber,
6047
6299
  movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
6048
6300
  sampleNumber: mfuDuHeader.sampleNumber,
6301
+ sequenceNumber: info.sequenceNumber,
6049
6302
  arrivedAt: Date.now()
6050
6303
  });
6051
6304
  return this.#drop("mfu-sample-timing-missing");
@@ -6071,7 +6324,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
6071
6324
  info,
6072
6325
  resolver,
6073
6326
  options?.recovered === true,
6074
- options?.fecSbn
6327
+ options?.fecSbn,
6328
+ options?.fecSbnFirst
6075
6329
  );
6076
6330
  if (deferred.record === void 0) this.#countDeferredOutcome(deferred.reason);
6077
6331
  }
@@ -6164,7 +6418,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
6164
6418
  info,
6165
6419
  resolver,
6166
6420
  options?.recovered === true,
6167
- options?.fecSbn
6421
+ options?.fecSbn,
6422
+ options?.fecSbnFirst
6168
6423
  );
6169
6424
  if (outcome.record !== void 0) return outcome.record;
6170
6425
  return this.#drop(outcome.reason);
@@ -6184,7 +6439,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6184
6439
  * attribution exists to keep readable. Leaving the choice at the call site
6185
6440
  * is what keeps both true.
6186
6441
  */
6187
- #emitCombinedSample(combined, info, resolver, recovered, fecSbn) {
6442
+ #emitCombinedSample(combined, info, resolver, recovered, fecSbn, fecSbnFirst) {
6188
6443
  const timing = resolver.sampleTiming(
6189
6444
  combined.mpuSequenceNumber,
6190
6445
  combined.movieFragmentSequenceNumber,
@@ -6201,6 +6456,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6201
6456
  );
6202
6457
  if (!meta) return { reason: "combined-meta-build-failed" };
6203
6458
  if (fecSbn !== void 0) meta.fecSbn = fecSbn;
6459
+ if (fecSbnFirst !== void 0) meta.fecSbnFirst = fecSbnFirst;
6204
6460
  if (!resolver.consumeSample(
6205
6461
  combined.mpuSequenceNumber,
6206
6462
  combined.movieFragmentSequenceNumber,
@@ -6369,6 +6625,10 @@ var MmtpContainerParser = class _MmtpContainerParser {
6369
6625
  }
6370
6626
  this.#emitFrame(data, meta);
6371
6627
  }
6628
+ /** Whether FT=1 metadata already names this sample, without claiming it. */
6629
+ hasAuthoredTimingFor(packetId, mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber, catalogTrackName) {
6630
+ return this.#timingResolver(this.#streamKey(packetId, catalogTrackName), packetId, false)?.sampleTiming(mpuSequenceNumber, movieFragmentSequenceNumber, sampleNumber) != null;
6631
+ }
6372
6632
  /**
6373
6633
  * Claim and return the authored timing for a recovered sample. Recovery does
6374
6634
  * not pass through the ordinary `feed()` completion path, so it must retire
@@ -6430,6 +6690,9 @@ var MmtpContainerParser = class _MmtpContainerParser {
6430
6690
  for (const { sequencer } of this.#sequencers.values()) sequencer.discard();
6431
6691
  this.#sequencers.clear();
6432
6692
  this.#fecSequencer?.discard();
6693
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
6694
+ for (const head of awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
6695
+ }
6433
6696
  this.#timingStreams.clear();
6434
6697
  this.#pendingTimingSamples = 0;
6435
6698
  this.#reliableMoqStartupGate.clear();
@@ -6448,10 +6711,23 @@ var MmtpContainerParser = class _MmtpContainerParser {
6448
6711
  return resolver;
6449
6712
  }
6450
6713
  #awaitTiming(streamKey, head) {
6451
- const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
6452
- if (!awaitingTiming) return;
6714
+ const state = this.#timingStreams.get(streamKey);
6715
+ if (!state) return;
6716
+ if (!head.options?.recovered) {
6717
+ const kept = state.awaitingTiming.filter((queued) => !queued.options?.recovered || queued.sequenceNumber !== head.sequenceNumber);
6718
+ this.#recoveredHeadsAwaitingTiming.superseded += state.awaitingTiming.length - kept.length;
6719
+ state.awaitingTiming = kept;
6720
+ }
6721
+ const awaitingTiming = state.awaitingTiming;
6453
6722
  awaitingTiming.push(head);
6454
- if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
6723
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming.held++;
6724
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) {
6725
+ this.#leaveAwaitingTiming(awaitingTiming.shift(), "expired");
6726
+ }
6727
+ }
6728
+ /** Count a recovered head leaving the queue other than by replay or its source copy. */
6729
+ #leaveAwaitingTiming(head, outcome) {
6730
+ if (head.options?.recovered) this.#recoveredHeadsAwaitingTiming[outcome]++;
6455
6731
  }
6456
6732
  /**
6457
6733
  * Feed again the heads whose timing the FT=1 just admitted declares. That
@@ -6479,6 +6755,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
6479
6755
  const state = this.#timingStreams.get(streamKey);
6480
6756
  if (!state) return;
6481
6757
  this.#timingStreams.delete(streamKey);
6758
+ for (const head of state.awaitingTiming) this.#leaveAwaitingTiming(head, "discarded");
6482
6759
  this.#pendingTimingSamples -= state.resolver.pendingSampleCount;
6483
6760
  if (this.#pendingTimingSamples < 0) {
6484
6761
  throw new Error("[MmtpContainerParser] pending timing sample accounting underflow");