@blockcast/mmt-container 0.4.0-main.bb90ce9247fa → 0.4.0-main.bbdfdbf39ded

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 (205) hide show
  1. package/README.md +36 -20
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +1721 -705
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +72 -34
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +309 -204
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +15 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +137 -50
  15. package/dist/catalog-fec-params.js.map +4 -4
  16. package/dist/catalog-network-source.d.ts +24 -2
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +24 -1
  19. package/dist/catalog-network-source.js.map +3 -3
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/delivery-catalog.js +100 -230
  25. package/dist/delivery-catalog.js.map +4 -4
  26. package/dist/fec-manager.d.ts +64 -1
  27. package/dist/fec-manager.d.ts.map +1 -1
  28. package/dist/fec-manager.js +275 -62
  29. package/dist/fec-manager.js.map +4 -4
  30. package/dist/fec-state.d.ts +5 -3
  31. package/dist/fec-state.d.ts.map +1 -1
  32. package/dist/fec-state.js +34 -12
  33. package/dist/fec-state.js.map +4 -4
  34. package/dist/fec-worker-setup.d.ts +2 -0
  35. package/dist/fec-worker-setup.d.ts.map +1 -1
  36. package/dist/fec-worker-setup.js +15 -3
  37. package/dist/fec-worker-setup.js.map +3 -3
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +14 -8
  41. package/dist/index.js.map +2 -2
  42. package/dist/iso-block-locator.d.ts +29 -0
  43. package/dist/iso-block-locator.d.ts.map +1 -1
  44. package/dist/iso-block-locator.js +100 -17
  45. package/dist/iso-block-locator.js.map +4 -4
  46. package/dist/manifest-auth-plan.d.ts +26 -25
  47. package/dist/manifest-auth-plan.d.ts.map +1 -1
  48. package/dist/manifest-auth-plan.js +331 -1171
  49. package/dist/manifest-auth-plan.js.map +4 -4
  50. package/dist/mfu-reassembler.js +24 -13
  51. package/dist/mfu-reassembler.js.map +3 -3
  52. package/dist/mmtp-container-parser.d.ts.map +1 -1
  53. package/dist/mmtp-container-parser.js +96 -22
  54. package/dist/mmtp-container-parser.js.map +3 -3
  55. package/dist/mmtp-container-parser.no-modules.js +1138 -325
  56. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  57. package/dist/mmtp-decode-pipeline.js +96 -22
  58. package/dist/mmtp-decode-pipeline.js.map +3 -3
  59. package/dist/mmtp-fec-session.d.ts +159 -0
  60. package/dist/mmtp-fec-session.d.ts.map +1 -0
  61. package/dist/mmtp-fec-session.js +531 -0
  62. package/dist/mmtp-fec-session.js.map +7 -0
  63. package/dist/mmtp-router.d.ts +31 -5
  64. package/dist/mmtp-router.d.ts.map +1 -1
  65. package/dist/mmtp-router.js +168 -22
  66. package/dist/mmtp-router.js.map +3 -3
  67. package/dist/multicast-auth-catalog.d.ts +86 -92
  68. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  69. package/dist/multicast-auth-catalog.js +347 -132
  70. package/dist/multicast-auth-catalog.js.map +4 -4
  71. package/dist/multicast-input.d.ts +28 -6
  72. package/dist/multicast-input.d.ts.map +1 -1
  73. package/dist/multicast-input.js +293 -28
  74. package/dist/multicast-input.js.map +3 -3
  75. package/dist/multicast-manager.d.ts +89 -5
  76. package/dist/multicast-manager.d.ts.map +1 -1
  77. package/dist/multicast-manager.js +730 -356
  78. package/dist/multicast-manager.js.map +4 -4
  79. package/dist/multicast-transport.d.ts +12 -2
  80. package/dist/multicast-transport.d.ts.map +1 -1
  81. package/dist/multicast-transport.js +111 -235
  82. package/dist/multicast-transport.js.map +4 -4
  83. package/dist/multicast-unwrap.js +24 -13
  84. package/dist/multicast-unwrap.js.map +3 -3
  85. package/dist/no-modules.d.ts +4 -1
  86. package/dist/no-modules.d.ts.map +1 -1
  87. package/dist/no-modules.js +1087 -309
  88. package/dist/no-modules.js.map +4 -4
  89. package/dist/phase14-catalog-override.d.ts +1 -1
  90. package/dist/phase14-catalog-override.d.ts.map +1 -1
  91. package/dist/phase14-catalog-override.js +2 -2
  92. package/dist/phase14-catalog-override.js.map +2 -2
  93. package/dist/repair-fetch.d.ts +81 -6
  94. package/dist/repair-fetch.d.ts.map +1 -1
  95. package/dist/repair-fetch.js +159 -31
  96. package/dist/repair-fetch.js.map +3 -3
  97. package/dist/repair-layers.d.ts +2 -0
  98. package/dist/repair-layers.d.ts.map +1 -1
  99. package/dist/repair-layers.js +22 -2
  100. package/dist/repair-layers.js.map +3 -3
  101. package/dist/sample-combiner.d.ts +7 -1
  102. package/dist/sample-combiner.d.ts.map +1 -1
  103. package/dist/sample-combiner.js +14 -2
  104. package/dist/sample-combiner.js.map +2 -2
  105. package/dist/signaling.d.ts +2 -2
  106. package/dist/signaling.d.ts.map +1 -1
  107. package/dist/signaling.js +6 -3
  108. package/dist/signaling.js.map +3 -3
  109. package/dist/source-auth.js +2710 -7
  110. package/dist/source-auth.js.map +4 -4
  111. package/dist/switching-set-alignment.d.ts +1 -1
  112. package/dist/switching-set-alignment.js.map +1 -1
  113. package/dist/timestamp-codec.js +24 -13
  114. package/dist/timestamp-codec.js.map +3 -3
  115. package/dist/wasm-mfu-reassembler.js +3 -0
  116. package/dist/wasm-mfu-reassembler.js.map +3 -3
  117. package/dist/wasm-mmtp-container-parser.js +96 -22
  118. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  119. package/package.json +6 -9
  120. package/schemas/catalog.schema.json +124 -37
  121. package/src/align.ts +52 -21
  122. package/src/carp-catalog.ts +163 -61
  123. package/src/catalog-fec-params.ts +66 -20
  124. package/src/catalog-network-source.ts +45 -2
  125. package/src/catalog-validator.ts +4 -11
  126. package/src/fec-manager.ts +239 -63
  127. package/src/fec-state.ts +14 -12
  128. package/src/fec-worker-setup.ts +20 -2
  129. package/src/index.ts +29 -10
  130. package/src/iso-block-locator.ts +97 -6
  131. package/src/manifest-auth-plan.ts +39 -91
  132. package/src/mmtp-container-parser.ts +75 -7
  133. package/src/mmtp-fec-session.ts +533 -0
  134. package/src/mmtp-router.ts +133 -5
  135. package/src/multicast-auth-catalog.ts +131 -238
  136. package/src/multicast-input.ts +119 -61
  137. package/src/multicast-manager.ts +258 -21
  138. package/src/multicast-transport.ts +17 -3
  139. package/src/no-modules.ts +7 -1
  140. package/src/phase14-catalog-override.ts +3 -3
  141. package/src/repair-fetch.ts +283 -39
  142. package/src/repair-layers.ts +22 -2
  143. package/src/sample-combiner.ts +15 -2
  144. package/src/signaling.ts +2 -2
  145. package/src/switching-set-alignment.ts +1 -1
  146. package/test-vectors/align.json +108 -32
  147. package/test-vectors/bc-provenance-v2.json +1526 -0
  148. package/test-vectors/catalog/README.md +65 -4
  149. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  150. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  151. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  152. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  153. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  154. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  156. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  157. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  158. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  159. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  160. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  161. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  162. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  163. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  164. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  165. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  166. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  167. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  168. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  169. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  170. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  171. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  172. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  174. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  175. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  177. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  178. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  179. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  180. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  181. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  182. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  183. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  184. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  185. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  186. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  187. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  188. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  189. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +2 -2
  190. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  191. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  192. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  193. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  194. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  195. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  196. package/test-vectors/catalog/section-codes.json +30 -1
  197. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  198. package/test-vectors/catalog-validation.json +101 -5
  199. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  200. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  201. package/dist/fec-codec.d.ts +0 -32
  202. package/dist/fec-codec.d.ts.map +0 -1
  203. package/dist/fec-codec.js +0 -47
  204. package/dist/fec-codec.js.map +0 -7
  205. package/src/fec-codec.ts +0 -61
@@ -150,26 +150,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
150
150
  const authLength = view2.getUint16(2, false);
151
151
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
152
152
  }
153
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
153
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
154
154
  if (declaredEnd > payload.length)
155
155
  return null;
156
156
  if (options?.skipFecId) {
157
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
157
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
158
158
  }
159
+ const overlay = options?.overlayDeclared === true && rapFlag;
159
160
  if (fecType === 1) {
160
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
161
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
161
162
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
162
163
  return null;
163
164
  }
164
- return { hasFecId: true };
165
+ return { hasFecId: true, hasOverlayFecId: overlay };
165
166
  }
166
- if (fecType !== 0)
167
+ if (fecType !== 0 || overlay)
167
168
  return null;
168
169
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
169
- return { hasFecId: false };
170
+ return { hasFecId: false, hasOverlayFecId: false };
170
171
  }
171
172
  return null;
172
173
  }
174
+ function sourceFecTrailerSize(overlay) {
175
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
176
+ }
173
177
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
174
178
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
175
179
  return {
@@ -222,15 +226,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
222
226
  if ("rejection" in layoutResult)
223
227
  return layoutResult;
224
228
  const { layout } = layoutResult;
225
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
229
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
226
230
  if (!trailerLayout) {
227
231
  if (!options?.skipFecId && header.fecType === 1) {
228
232
  const observed = payload.length - layout.dataEnd;
229
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
233
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
234
+ if (observed !== expected) {
230
235
  return {
231
236
  rejection: {
232
237
  gate: "source-fec-payload-id-width-mismatch",
233
- detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
238
+ detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${expected} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
234
239
  }
235
240
  };
236
241
  }
@@ -257,10 +262,13 @@ function extractPlannedMfu(mmtpPacket, result) {
257
262
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
258
263
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
259
264
  const data = payload.subarray(mfuOffset, dataEnd);
260
- const fecPayloadId = trailerLayout.hasFecId ? {
261
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
262
- } : null;
263
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
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 };
264
272
  }
265
273
  function sourceFecPayloadIdOf(mmtpPacket, header) {
266
274
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -281,12 +289,86 @@ function sourceFecPayloadIdOf(mmtpPacket, header) {
281
289
  ssId: (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0
282
290
  };
283
291
  }
292
+ var REPAIR_FEC_PID_SIZE = 13;
293
+ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
294
+ let header;
295
+ if (parsedHeader) {
296
+ header = parsedHeader;
297
+ } else {
298
+ try {
299
+ header = parseMMTPHeader(mmtpPacket);
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
304
+ if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2)
305
+ return null;
306
+ const off = header.headerLength;
307
+ if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE)
308
+ return null;
309
+ const ssStart = (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0;
310
+ const rsbLength = mmtpPacket[off + 4] << 16 | mmtpPacket[off + 5] << 8 | mmtpPacket[off + 6];
311
+ const rsId = mmtpPacket[off + 7] << 16 | mmtpPacket[off + 8] << 8 | mmtpPacket[off + 9];
312
+ const ssbLength = mmtpPacket[off + 10] << 16 | mmtpPacket[off + 11] << 8 | mmtpPacket[off + 12];
313
+ return {
314
+ packetId: header.packetId,
315
+ ssStart,
316
+ rsbLength,
317
+ rsId,
318
+ ssbLength,
319
+ dataOffset: off + REPAIR_FEC_PID_SIZE
320
+ };
321
+ }
322
+ function parseMoqRepairFrameWithHeader(frame, header) {
323
+ return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header));
324
+ }
325
+ function moqRepairFrameFrom(frame, repairId) {
326
+ if (!repairId)
327
+ return null;
328
+ const symbolData = frame.subarray(repairId.dataOffset);
329
+ if (repairId.rsbLength === 0 || repairId.ssbLength === 0 || repairId.rsId >= repairId.rsbLength || symbolData.length === 0)
330
+ return null;
331
+ return {
332
+ packetId: repairId.packetId,
333
+ ssStart: repairId.ssStart,
334
+ rsbLength: repairId.rsbLength,
335
+ rsId: repairId.rsId,
336
+ ssbLength: repairId.ssbLength,
337
+ symbolData
338
+ };
339
+ }
340
+
341
+ // ../mmt-base/dist/net-constants.js
342
+ var DEFAULT_AMT_RELAY_PORT = 2268;
284
343
 
285
344
  // ../mmt-base/dist/ntp-short.js
286
345
  var NTP_SHORT_BITS = 32;
287
346
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
288
347
  var NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1);
289
348
 
349
+ // ../mmt-base/dist/serial-number.js
350
+ var SERIAL32_SPAN = 4294967296;
351
+ var SERIAL32_HALF = 2147483648;
352
+ function assertUint32(value, name) {
353
+ if (!Number.isInteger(value) || value < 0 || value >= SERIAL32_SPAN) {
354
+ throw new RangeError(`${name} must be a uint32 (got ${value})`);
355
+ }
356
+ }
357
+ function serial32Add(s, n) {
358
+ assertUint32(s, "s");
359
+ if (!Number.isInteger(n) || n <= -SERIAL32_HALF || n >= SERIAL32_HALF) {
360
+ throw new RangeError(`serial addend must lie in (-2^31, 2^31) (got ${n})`);
361
+ }
362
+ return (s + n + SERIAL32_SPAN) % SERIAL32_SPAN;
363
+ }
364
+ function serial32Distance(from, to) {
365
+ return to - from >>> 0;
366
+ }
367
+ function serial32Precedes(a, b) {
368
+ const distance = serial32Distance(a, b);
369
+ return distance !== 0 && distance < SERIAL32_HALF;
370
+ }
371
+
290
372
  // ../mmt-base/dist/fec-block-profile.js
291
373
  var FEC_BLOCK_PROFILES = Object.freeze([
292
374
  "iso-ssbg1-v1"
@@ -302,6 +384,311 @@ function parseFecBlockProfile(value, where) {
302
384
  }
303
385
  throw new Error(`${where} must be "iso-ssbg1-v1" (got ${JSON.stringify(value)})`);
304
386
  }
387
+ var SSBG1_LENGTH_FIELD_BYTES = 2;
388
+ function ssbg1MaxPacketLength(symbolSize) {
389
+ return symbolSize - SSBG1_LENGTH_FIELD_BYTES;
390
+ }
391
+ function ssbg1FitsSymbol(packetLength, symbolSize) {
392
+ return Number.isSafeInteger(packetLength) && packetLength >= 0 && packetLength <= ssbg1MaxPacketLength(symbolSize) && packetLength <= 65535;
393
+ }
394
+ function trimSsbg1SourceSymbol(symbol) {
395
+ if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES)
396
+ return null;
397
+ const length = symbol[0] << 8 | symbol[1];
398
+ const end = SSBG1_LENGTH_FIELD_BYTES + length;
399
+ if (end > symbol.byteLength)
400
+ return null;
401
+ for (let i = end; i < symbol.byteLength; i++) {
402
+ if (symbol[i] !== 0)
403
+ return null;
404
+ }
405
+ return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end);
406
+ }
407
+ function isoBlockContains(ssStart, ssbLength, ssId) {
408
+ return serial32Distance(ssStart, ssId) < ssbLength;
409
+ }
410
+ function isoBlocksBehindLowerBound(a, b, kMax) {
411
+ if (!Number.isSafeInteger(kMax) || kMax <= 0) {
412
+ throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`);
413
+ }
414
+ return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
415
+ }
416
+
417
+ // ../mmt-base/dist/catalog-fec-source.js
418
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
419
+ function recordOf(value) {
420
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
421
+ }
422
+ function isoBlockSpanUsable(fec) {
423
+ const block = recordOf(fec);
424
+ if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1")
425
+ return true;
426
+ const ms = block["interleaveDepthMs"];
427
+ return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
428
+ }
429
+ function fecAlgorithmUnimplemented(algorithm) {
430
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
431
+ }
432
+ function isPositiveSafeInteger(value) {
433
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
434
+ }
435
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
436
+ function catalogFecDeclaresUnconfigurableInstance(fec) {
437
+ const block = recordOf(fec);
438
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"]))
439
+ return false;
440
+ if (!(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"])))
441
+ return true;
442
+ return block["blockProfile"] === "iso-ssbg1-v1" && block["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE;
443
+ }
444
+
445
+ // ../mmt-base/dist/multicast-catalog.js
446
+ var ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
447
+ var UINT32_MAX = 4294967295;
448
+ var AUTH_MEMBERS = /* @__PURE__ */ new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
449
+ var KEY_MEMBERS = /* @__PURE__ */ new Set(["kid", "publicKey", "firstEpoch"]);
450
+ var ENDPOINT_AUTH_MEMBERS = /* @__PURE__ */ new Set([
451
+ "manifestPort",
452
+ "streamId",
453
+ "senderAddress",
454
+ "maxAuthDelayMs",
455
+ "manifestTimerMs",
456
+ "manifestTrack"
457
+ ]);
458
+ function isObject(value) {
459
+ return typeof value === "object" && value !== null && !Array.isArray(value);
460
+ }
461
+ function isNonEmptyString(value) {
462
+ return typeof value === "string" && value.trim().length > 0;
463
+ }
464
+ function isIntegerIn(value, min, max) {
465
+ return Number.isSafeInteger(value) && value >= min && value <= max;
466
+ }
467
+ function multicastEndpointSource(endpoint) {
468
+ if (!isObject(endpoint))
469
+ return void 0;
470
+ const sourceAddress = endpoint["sourceAddress"];
471
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress))
472
+ return void 0;
473
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
474
+ const protocol = endpoint["protocol"];
475
+ if (protocol !== void 0 && protocol !== mode)
476
+ return void 0;
477
+ const auth = endpoint["auth"];
478
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : void 0;
479
+ if (mode === "ssm")
480
+ return senderAddress === void 0 ? { mode, source: sourceAddress } : void 0;
481
+ if (auth === void 0)
482
+ return { mode };
483
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : void 0;
484
+ }
485
+ function authIssues(auth) {
486
+ const base = "$.multicast.auth";
487
+ const issue = (path, message) => [
488
+ { code: "multicast_auth", path: `${base}${path}`, message }
489
+ ];
490
+ if (!isObject(auth))
491
+ return issue("", "auth must be an object");
492
+ const unknown = Object.keys(auth).filter((key) => !AUTH_MEMBERS.has(key));
493
+ if (unknown.length > 0) {
494
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
495
+ }
496
+ if (auth["scheme"] !== "bc-provenance")
497
+ return issue(".scheme", 'scheme must be "bc-provenance"');
498
+ if (auth["version"] !== 2)
499
+ return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
500
+ if (auth["sig"] !== "ed25519")
501
+ return issue(".sig", 'sig must be "ed25519"');
502
+ const keys = auth["keys"];
503
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
504
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
505
+ }
506
+ const kids = /* @__PURE__ */ new Set();
507
+ const firstEpochs = /* @__PURE__ */ new Set();
508
+ for (let index = 0; index < keys.length; index++) {
509
+ const key = keys[index];
510
+ const at = `.keys[${index}]`;
511
+ if (!isObject(key) || Object.keys(key).some((member) => !KEY_MEMBERS.has(member))) {
512
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
513
+ }
514
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX))
515
+ return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
516
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
517
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
518
+ }
519
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
520
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
521
+ }
522
+ if (kids.has(key["kid"]))
523
+ return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
524
+ if (firstEpochs.has(key["firstEpoch"])) {
525
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
526
+ }
527
+ kids.add(key["kid"]);
528
+ firstEpochs.add(key["firstEpoch"]);
529
+ }
530
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
531
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
532
+ }
533
+ return [];
534
+ }
535
+ function endpointAuthIssue(endpoint, mode, at) {
536
+ const auth = endpoint["auth"];
537
+ if (!isObject(auth))
538
+ return { path: `${at}.auth`, message: "auth must be an object" };
539
+ const unknown = Object.keys(auth).filter((key) => !ENDPOINT_AUTH_MEMBERS.has(key));
540
+ if (unknown.length > 0)
541
+ return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
542
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
543
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
544
+ }
545
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
546
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
547
+ }
548
+ if (mode === "ssm" && auth["senderAddress"] !== void 0) {
549
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
550
+ }
551
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
552
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
553
+ }
554
+ if (auth["maxAuthDelayMs"] !== void 0 && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1e3)) {
555
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
556
+ }
557
+ if (auth["manifestTimerMs"] !== void 0 && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
558
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
559
+ }
560
+ if (auth["manifestTrack"] !== void 0 && !isNonEmptyString(auth["manifestTrack"])) {
561
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
562
+ }
563
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
564
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
565
+ }
566
+ return void 0;
567
+ }
568
+ var CATALOG_NAMESPACE = /* @__PURE__ */ Symbol.for("@blockcast/mmt-base/catalogNamespace");
569
+ function multicastCatalogIssues(catalog, options = {}) {
570
+ if (!isObject(catalog))
571
+ return [];
572
+ const issues = [];
573
+ if ("multicast.auth" in catalog) {
574
+ issues.push({
575
+ code: "multicast_auth",
576
+ path: '$["multicast.auth"]',
577
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)'
578
+ });
579
+ }
580
+ const multicast = catalog["multicast"];
581
+ if (!isObject(multicast))
582
+ return issues;
583
+ const protectedCatalog = multicast["auth"] !== void 0;
584
+ if (protectedCatalog)
585
+ issues.push(...authIssues(multicast["auth"]));
586
+ const endpoints = multicast["endpoints"];
587
+ if (!Array.isArray(endpoints))
588
+ return issues;
589
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
590
+ const namespaceOf = /* @__PURE__ */ new Map();
591
+ for (const track of tracks) {
592
+ if (isObject(track) && typeof track["name"] === "string")
593
+ namespaceOf.set(track["name"], track["namespace"]);
594
+ }
595
+ const tagged = catalog[CATALOG_NAMESPACE];
596
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
597
+ const sources = [];
598
+ for (let index = 0; index < endpoints.length; index++) {
599
+ const endpoint = endpoints[index];
600
+ const at = `$.multicast.endpoints[${index}]`;
601
+ const fail = (code, path, message) => {
602
+ issues.push({ code, path, message, endpointIndex: index });
603
+ };
604
+ sources.push(void 0);
605
+ if (!isObject(endpoint)) {
606
+ fail("multicast_endpoint", at, "endpoint must be an object");
607
+ continue;
608
+ }
609
+ const protocol = endpoint["protocol"];
610
+ if (protocol !== void 0 && protocol !== "ssm" && protocol !== "asm") {
611
+ fail("multicast_endpoint", `${at}.protocol`, `protocol must be "ssm" or "asm"; a bearer such as ${JSON.stringify(protocol)} is a networkSource entry (draft -01 4.2)`);
612
+ continue;
613
+ }
614
+ const hasAuth = endpoint["auth"] !== void 0;
615
+ if (protectedCatalog !== hasAuth) {
616
+ fail("multicast_endpoint_auth", `${at}.auth`, protectedCatalog ? "every endpoint requires auth when multicast carries auth; a receiver ignores this endpoint" : "auth names no key without multicast.auth; a receiver ignores this endpoint");
617
+ continue;
618
+ }
619
+ const sourceAddress = endpoint["sourceAddress"];
620
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress)) {
621
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
622
+ continue;
623
+ }
624
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
625
+ if (protocol !== void 0 && protocol !== mode) {
626
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
627
+ continue;
628
+ }
629
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
630
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
631
+ continue;
632
+ }
633
+ if (hasAuth) {
634
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
635
+ if (authIssue) {
636
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
637
+ continue;
638
+ }
639
+ }
640
+ sources[index] = multicastEndpointSource(endpoint);
641
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
642
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
643
+ const ref = refs[refIndex];
644
+ const name = isObject(ref) ? ref["name"] : ref;
645
+ if (typeof name !== "string")
646
+ continue;
647
+ const namespace = namespaceOf.get(name);
648
+ if (typeof namespace !== "string")
649
+ continue;
650
+ referenceNamespace ??= namespace;
651
+ if (namespace !== referenceNamespace) {
652
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
653
+ }
654
+ }
655
+ }
656
+ const tupleOf = (index) => {
657
+ const endpoint = endpoints[index];
658
+ const auth = endpoint["auth"];
659
+ return {
660
+ sg: JSON.stringify([sources[index].source ?? null, endpoint["groupAddress"]]),
661
+ port: endpoint["port"],
662
+ manifestPort: isObject(auth) ? auth["manifestPort"] : void 0
663
+ };
664
+ };
665
+ for (let index = 0; index < endpoints.length; index++) {
666
+ if (!sources[index])
667
+ continue;
668
+ const own = tupleOf(index);
669
+ const at = `$.multicast.endpoints[${index}]`;
670
+ if (own.manifestPort !== void 0 && own.manifestPort === own.port) {
671
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
672
+ continue;
673
+ }
674
+ for (let other = 0; other < endpoints.length; other++) {
675
+ if (other === index || !sources[other])
676
+ continue;
677
+ const peer = tupleOf(other);
678
+ if (peer.sg !== own.sg)
679
+ continue;
680
+ if (peer.port === own.port) {
681
+ issues.push({ code: "multicast_endpoint", path: `${at}.port`, message: `(S, G, port) is shared with endpoint ${other}; one endpoint object per multicast tuple`, endpointIndex: index });
682
+ break;
683
+ }
684
+ if (own.manifestPort !== void 0 && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
685
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: `manifestPort is a port or manifestPort of endpoint ${other} on the same (S, G)`, endpointIndex: index });
686
+ break;
687
+ }
688
+ }
689
+ }
690
+ return issues;
691
+ }
305
692
 
306
693
  // src/mfu-reassembler.ts
307
694
  function fragmentProvenance(fragment) {
@@ -3148,8 +3535,14 @@ var SampleCombiner = class {
3148
3535
  /**
3149
3536
  * Add one reassembled data unit. Returns the combined sample once every
3150
3537
  * constituent data unit has arrived and totals the authored size.
3538
+ *
3539
+ * `sampleSize` is the authored size the host resolves for the sample as the
3540
+ * data unit completes. It stands in only when no size was registered, which
3541
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
3542
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
3543
+ * fragments, or one decoded before its source copy arrived.
3151
3544
  */
3152
- addMfu(mfu) {
3545
+ addMfu(mfu, sampleSize) {
3153
3546
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3154
3547
  this.#stats.passthroughSamples++;
3155
3548
  return fromPassthrough(mfu);
@@ -3165,7 +3558,7 @@ var SampleCombiner = class {
3165
3558
  return null;
3166
3559
  }
3167
3560
  const dataLen = mfu.data.byteLength;
3168
- const authoredSize = this.#authoredSizes.get(key);
3561
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
3169
3562
  if (offset === 0 && !this.#pending.has(key)) {
3170
3563
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
3171
3564
  if (passesThrough) {
@@ -3459,6 +3852,12 @@ if (void 0) {
3459
3852
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
3460
3853
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
3461
3854
  });
3855
+ test("a size handed with the data unit completes a sample no head registered", () => {
3856
+ const c = combiner({ requireAuthoredSize: true });
3857
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
3858
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
3859
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
3860
+ });
3462
3861
  test("duplicate offset is rejected", () => {
3463
3862
  const c = combiner();
3464
3863
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -5426,6 +5825,7 @@ function isFmp4Box(data) {
5426
5825
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
5427
5826
  return FMPU_BOX_TYPES.has(type);
5428
5827
  }
5828
+ var MAX_AWAITING_TIMING_HEADS = 8;
5429
5829
  var MmtpContainerParser = class _MmtpContainerParser {
5430
5830
  constructor(config) {
5431
5831
  this.#tracks = /* @__PURE__ */ new Map();
@@ -5484,6 +5884,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5484
5884
  * reordering into the parser. */
5485
5885
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
5486
5886
  this.#disposed = false;
5887
+ this.#replayingAwaitingTiming = false;
5487
5888
  this.#fedObjects = 0;
5488
5889
  this.#reassemblerFragmentsFed = 0;
5489
5890
  this.#reassemblerDataUnitsReturned = 0;
@@ -5576,6 +5977,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5576
5977
  #reorderStats;
5577
5978
  #reliableMoqStartupGate;
5578
5979
  #disposed;
5980
+ #replayingAwaitingTiming;
5579
5981
  #fedObjects;
5580
5982
  #reassemblerFragmentsFed;
5581
5983
  #reassemblerDataUnitsReturned;
@@ -5825,7 +6227,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
5825
6227
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
5826
6228
  */
5827
6229
  #drop(reason) {
5828
- this.#countOutcome(`drop:${reason}`);
6230
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
6231
+ else this.#countOutcome(`drop:${reason}`);
5829
6232
  return null;
5830
6233
  }
5831
6234
  get reorderDiagnostics() {
@@ -5848,6 +6251,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
5848
6251
  for (const combiner of this.#sampleCombiners.values()) {
5849
6252
  combiner.cleanupTimeouts(timeoutMs);
5850
6253
  }
6254
+ const now = Date.now();
6255
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
6256
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
6257
+ awaitingTiming.shift();
6258
+ }
6259
+ }
5851
6260
  }
5852
6261
  /**
5853
6262
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -5928,7 +6337,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5928
6337
  byteLength: packet.byteLength
5929
6338
  };
5930
6339
  }
5931
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
6340
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
5932
6341
  const rawSymbol = packet.subarray(0, packet.length - 4);
5933
6342
  try {
5934
6343
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -5976,6 +6385,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5976
6385
  }
5977
6386
  return this.#drop("fragment-timing-refused");
5978
6387
  }
6388
+ this.#replayAwaitingTiming(streamKey, resolver2);
5979
6389
  return {
5980
6390
  kind: "fragment",
5981
6391
  packet: info,
@@ -5999,7 +6409,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
5999
6409
  mfuDuHeader.movieFragmentSequenceNumber,
6000
6410
  mfuDuHeader.sampleNumber
6001
6411
  );
6002
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
6412
+ if (!headTiming) {
6413
+ this.#awaitTiming(streamKey, {
6414
+ packet,
6415
+ options,
6416
+ parsed,
6417
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
6418
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
6419
+ sampleNumber: mfuDuHeader.sampleNumber,
6420
+ arrivedAt: Date.now()
6421
+ });
6422
+ return this.#drop("mfu-sample-timing-missing");
6423
+ }
6003
6424
  const offset = mfuDuHeader.offset;
6004
6425
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
6005
6426
  return this.#drop("mfu-offset-out-of-range");
@@ -6075,16 +6496,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
6075
6496
  const sampleNumber = assembled.sampleNumber;
6076
6497
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
6077
6498
  return this.#drop("assembled-identity-missing");
6078
- if (!resolver.sampleTiming(
6499
+ const assembledTiming = resolver.sampleTiming(
6079
6500
  assembled.mpuSequenceNumber,
6080
6501
  movieFragmentSequenceNumber,
6081
6502
  sampleNumber
6082
- )) return this.#drop("assembled-timing-missing");
6503
+ );
6504
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
6083
6505
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
6084
6506
  return this.#drop("assembled-mpu-mismatch");
6085
6507
  let combined;
6086
6508
  try {
6087
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
6509
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
6088
6510
  } catch (error) {
6089
6511
  if (!(error instanceof SampleCombineError)) throw error;
6090
6512
  console.warn(
@@ -6393,9 +6815,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
6393
6815
  if (existing) return existing.resolver;
6394
6816
  if (!create) return null;
6395
6817
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
6396
- this.#timingStreams.set(streamKey, { packetId, resolver });
6818
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
6397
6819
  return resolver;
6398
6820
  }
6821
+ #awaitTiming(streamKey, head) {
6822
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
6823
+ if (!awaitingTiming) return;
6824
+ awaitingTiming.push(head);
6825
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
6826
+ }
6827
+ /**
6828
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
6829
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
6830
+ * FEC path routes a source symbol that already arrived a second time.
6831
+ */
6832
+ #replayAwaitingTiming(streamKey, resolver) {
6833
+ const state = this.#timingStreams.get(streamKey);
6834
+ if (!state || state.awaitingTiming.length === 0) return;
6835
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
6836
+ head.mpuSequenceNumber,
6837
+ head.movieFragmentSequenceNumber,
6838
+ head.sampleNumber
6839
+ ));
6840
+ if (ready.length === 0) return;
6841
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
6842
+ this.#replayingAwaitingTiming = true;
6843
+ try {
6844
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
6845
+ } finally {
6846
+ this.#replayingAwaitingTiming = false;
6847
+ }
6848
+ }
6399
6849
  #dropTimingStream(streamKey) {
6400
6850
  const state = this.#timingStreams.get(streamKey);
6401
6851
  if (!state) return;
@@ -6885,197 +7335,6 @@ function createWasmMmtpContainerParser(config) {
6885
7335
  });
6886
7336
  }
6887
7337
 
6888
- // src/multicast-auth-catalog.ts
6889
- var RAW_ED25519_KEY_LENGTH = 32;
6890
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
6891
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6892
- function encodeBase64Url(bytes) {
6893
- let output = "";
6894
- for (let i = 0; i < bytes.length; i += 3) {
6895
- const b0 = bytes[i];
6896
- const b1 = bytes[i + 1];
6897
- const b2 = bytes[i + 2];
6898
- output += BASE64URL_ALPHABET[b0 >> 2];
6899
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
6900
- if (b1 === void 0) break;
6901
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
6902
- if (b2 === void 0) break;
6903
- output += BASE64URL_ALPHABET[b2 & 63];
6904
- }
6905
- return output;
6906
- }
6907
- var BASE64URL_DECODE_TABLE = (() => {
6908
- const table = new Int8Array(128).fill(-1);
6909
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
6910
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
6911
- }
6912
- return table;
6913
- })();
6914
- function decodeBase64Url(text) {
6915
- if (text.length % 4 === 1) {
6916
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
6917
- }
6918
- const bytes = [];
6919
- let buffer = 0;
6920
- let bits = 0;
6921
- for (let i = 0; i < text.length; i++) {
6922
- const code = text.charCodeAt(i);
6923
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
6924
- if (value === void 0 || value < 0) {
6925
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
6926
- }
6927
- buffer = buffer << 6 | value;
6928
- bits += 6;
6929
- if (bits >= 8) {
6930
- bits -= 8;
6931
- bytes.push(buffer >> bits & 255);
6932
- }
6933
- }
6934
- const decoded = Uint8Array.from(bytes);
6935
- if (encodeBase64Url(decoded) !== text) {
6936
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
6937
- }
6938
- return decoded;
6939
- }
6940
- function decodeAuthScope(authScope) {
6941
- const bytes = decodeBase64Url(authScope);
6942
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
6943
- throw new Error(
6944
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
6945
- );
6946
- }
6947
- return bytes;
6948
- }
6949
- function decodeEd25519PublicKey(publicKey) {
6950
- const bytes = decodeBase64Url(publicKey);
6951
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
6952
- throw new Error(
6953
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
6954
- );
6955
- }
6956
- return bytes;
6957
- }
6958
- function isNonEmptyString(value) {
6959
- return typeof value === "string" && value.length > 0;
6960
- }
6961
- function isValidAuthScopeField(value) {
6962
- if (!isNonEmptyString(value)) return false;
6963
- try {
6964
- decodeAuthScope(value);
6965
- return true;
6966
- } catch {
6967
- return false;
6968
- }
6969
- }
6970
- function isValidPublicKeyField(value) {
6971
- if (!isNonEmptyString(value)) return false;
6972
- try {
6973
- decodeEd25519PublicKey(value);
6974
- return true;
6975
- } catch {
6976
- return false;
6977
- }
6978
- }
6979
- function hasOnlyKeys(object, allowed) {
6980
- const allowedKeys = new Set(allowed);
6981
- return Object.keys(object).every((key) => allowedKeys.has(key));
6982
- }
6983
- function isMulticastAuthTrackConfig(obj) {
6984
- if (typeof obj !== "object" || obj === null) return false;
6985
- const o = obj;
6986
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
6987
- }
6988
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
6989
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
6990
- function hasUniqueMulticastAuthTrackBindings(tracks) {
6991
- const bindings = tracks.flatMap((track) => {
6992
- if (typeof track !== "object" || track === null) return [];
6993
- const value = track;
6994
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
6995
- return [];
6996
- }
6997
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
6998
- });
6999
- return new Set(bindings).size === bindings.length;
7000
- }
7001
- function isMulticastAuthConfig(obj) {
7002
- if (typeof obj !== "object" || obj === null) return false;
7003
- const o = obj;
7004
- if (o["scheme"] !== "bc-provenance") return false;
7005
- if (o["hash"] !== "blake3") return false;
7006
- if (o["sig"] !== "ed25519") return false;
7007
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
7008
- if (!isValidPublicKeyField(o["publicKey"])) return false;
7009
- if (!isNonEmptyString(o["keyId"])) return false;
7010
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
7011
- if (o["previousKey"] === o["publicKey"]) return false;
7012
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
7013
- if (o["enforcement"] !== void 0) {
7014
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
7015
- }
7016
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
7017
- const tracks = o["tracks"];
7018
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
7019
- const typedTracks = tracks;
7020
- const scopes = typedTracks.map((t) => t.authScope);
7021
- if (new Set(scopes).size !== scopes.length) return false;
7022
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
7023
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
7024
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
7025
- return true;
7026
- }
7027
- function resolveMulticastAuthMode(playerMode, auth) {
7028
- if (playerMode !== void 0) return playerMode;
7029
- if (auth === void 0) return "off";
7030
- return auth.enforcement ?? "shadow";
7031
- }
7032
- function resolveMulticastAuthCatalog(catalog, playerMode) {
7033
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
7034
- throw new Error("[multicast-auth-catalog] catalog must be an object");
7035
- }
7036
- const root = catalog;
7037
- const rawAuth = root["multicast.auth"];
7038
- if (rawAuth === void 0) {
7039
- if (playerMode === "enforce") {
7040
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
7041
- }
7042
- return void 0;
7043
- }
7044
- if (!isMulticastAuthConfig(rawAuth)) {
7045
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
7046
- }
7047
- const rawTracks = root["tracks"];
7048
- if (!Array.isArray(rawTracks)) {
7049
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
7050
- }
7051
- const catalogTrackNames = new Set(
7052
- rawTracks.flatMap(
7053
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
7054
- )
7055
- );
7056
- for (const track of rawAuth.tracks) {
7057
- if (!catalogTrackNames.has(track.mediaTrack)) {
7058
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
7059
- }
7060
- if (!catalogTrackNames.has(track.manifestTrack)) {
7061
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
7062
- }
7063
- }
7064
- return {
7065
- keyId: rawAuth.keyId,
7066
- acceptedPublicKeys: [
7067
- decodeEd25519PublicKey(rawAuth.publicKey),
7068
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
7069
- ],
7070
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
7071
- compaction: rawAuth.compaction,
7072
- tracks: rawAuth.tracks.map((track) => ({
7073
- ...track,
7074
- authScope: decodeAuthScope(track.authScope)
7075
- }))
7076
- };
7077
- }
7078
-
7079
7338
  // src/repair-layers.ts
7080
7339
  var REPAIR_PRIORITY_MIN = 192;
7081
7340
  var REPAIR_PRIORITY_MAX = 255;
@@ -7083,6 +7342,7 @@ var DEFAULT_REPAIR_PRIORITY = 240;
7083
7342
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
7084
7343
  var MAX_REPAIR_SYMBOLS = 16777215;
7085
7344
  var MAX_ENCODING_SYMBOL_ID = 16777215;
7345
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
7086
7346
  var RepairContractError = class extends Error {
7087
7347
  constructor(code, path, message) {
7088
7348
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -7265,11 +7525,12 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7265
7525
  if (layered && !positiveInteger(source.sourceSymbols)) {
7266
7526
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
7267
7527
  }
7268
- if (layered && source.algorithm !== "raptorq") {
7528
+ const reedSolomon = source.algorithm === "reed-solomon";
7529
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
7269
7530
  fail(
7270
7531
  "track_fec",
7271
7532
  `${source.path}.algorithm`,
7272
- "repair layers and overlays are defined only for raptorq: a block code fixes its codeword length, so symbols of a larger P are not symbols of the code a receiver holding fewer layers decodes"
7533
+ "repair layers and overlays are defined only for raptorq and reed-solomon (draft-ramadan-moq-fec-01 6.3.4 rule 7)"
7273
7534
  );
7274
7535
  }
7275
7536
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -7328,6 +7589,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7328
7589
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7329
7590
  );
7330
7591
  }
7592
+ if (reedSolomon && sourceSymbols + repairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
7593
+ fail(
7594
+ "track_fec_bounds",
7595
+ `${d.path}.repairSymbols`,
7596
+ `reed-solomon overlay sourceSymbols + repairSymbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
7597
+ );
7598
+ }
7331
7599
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
7332
7600
  }
7333
7601
  let offset = layerZeroSymbols;
@@ -7372,6 +7640,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7372
7640
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7373
7641
  );
7374
7642
  }
7643
+ if (reedSolomon && k + totalBaseRepairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
7644
+ fail(
7645
+ "track_fec_bounds",
7646
+ `${source.path}.sourceSymbols`,
7647
+ `reed-solomon sourceSymbols + total base repair symbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
7648
+ );
7649
+ }
7375
7650
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
7376
7651
  }
7377
7652
 
@@ -7459,7 +7734,7 @@ var CmsfCatalogValidationError = class extends Error {
7459
7734
  function catalogError(code, path, message) {
7460
7735
  throw new CmsfCatalogValidationError(code, path, message);
7461
7736
  }
7462
- function validateCmsfMmtpCatalog(value) {
7737
+ function validateCmsfMmtpCatalog(value, options = {}) {
7463
7738
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
7464
7739
  catalogError("catalog_object", "$", "catalog must be an object");
7465
7740
  }
@@ -7480,6 +7755,22 @@ function validateCmsfMmtpCatalog(value) {
7480
7755
  "commonTrackFields is retired; every track carries its own fields"
7481
7756
  );
7482
7757
  }
7758
+ const initDataList = catalog["initDataList"];
7759
+ if (initDataList !== void 0) {
7760
+ if (!Array.isArray(initDataList)) {
7761
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
7762
+ }
7763
+ initDataList.forEach((entry, i) => {
7764
+ const e = entry;
7765
+ const entryPath = `$.initDataList[${i}]`;
7766
+ if (typeof e !== "object" || e === null || Array.isArray(e) || typeof e["id"] !== "string" || e["id"].length === 0 || typeof e["type"] !== "string" || e["type"].length === 0) {
7767
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
7768
+ }
7769
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
7770
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
7771
+ }
7772
+ });
7773
+ }
7483
7774
  const tracks = catalog["tracks"];
7484
7775
  const trackRecords = [];
7485
7776
  const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -7531,6 +7822,14 @@ function validateCmsfMmtpCatalog(value) {
7531
7822
  if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
7532
7823
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
7533
7824
  }
7825
+ const anchor = track["presentationAnchorTicks"];
7826
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
7827
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
7828
+ }
7829
+ const initRef = track["initRef"];
7830
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
7831
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7832
+ }
7534
7833
  if (packaging === "fec-repair") {
7535
7834
  rejectRepairTrackGeometry(path, track, catalogError);
7536
7835
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -7538,9 +7837,8 @@ function validateCmsfMmtpCatalog(value) {
7538
7837
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
7539
7838
  }
7540
7839
  if (packaging === "mmtp") {
7541
- const mmtpMode = track["mmtpMode"];
7542
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
7543
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
7840
+ if (track["mmtpMode"] !== "mfu") {
7841
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7544
7842
  }
7545
7843
  if (!positiveInteger2(timescale)) {
7546
7844
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -7563,8 +7861,8 @@ function validateCmsfMmtpCatalog(value) {
7563
7861
  }
7564
7862
  const config = fec;
7565
7863
  const algorithm = config["algorithm"];
7566
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
7567
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
7864
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
7865
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
7568
7866
  }
7569
7867
  if ("interleaveDepth" in config || "interleaveMs" in config) {
7570
7868
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -7593,6 +7891,9 @@ function validateCmsfMmtpCatalog(value) {
7593
7891
  }
7594
7892
  }
7595
7893
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
7894
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
7895
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
7896
+ }
7596
7897
  }
7597
7898
  }
7598
7899
  const repairDescriptors = trackRecords.flatMap(
@@ -7642,11 +7943,21 @@ function validateCmsfMmtpCatalog(value) {
7642
7943
  const timescale = BigInt(track["timescale"]);
7643
7944
  const durationTicks = track["groupDurationTicks"];
7644
7945
  const ticks = durationTicks !== void 0 ? BigInt(durationTicks) : BigInt(track["groupDurationMs"]) * timescale / 1000n;
7645
- const anchor = switchingSets.get(altGroup);
7646
- if (anchor && ticks * anchor.timescale !== anchor.ticks * timescale) {
7647
- catalogError("track_switching_set", `$.tracks[${index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
7946
+ const framerate = track["framerate"];
7947
+ const intraOnly = positiveNumber(framerate) && Math.abs(Number(ticks) * framerate - Number(timescale)) <= Number(timescale) * 1e-3;
7948
+ const members = switchingSets.get(altGroup) ?? [];
7949
+ members.push({ index, name: track["name"], ticks, timescale, intraOnly });
7950
+ switchingSets.set(altGroup, members);
7951
+ }
7952
+ for (const [altGroup, members] of switchingSets) {
7953
+ const anchor = members.find((member) => !member.intraOnly) ?? members[0];
7954
+ for (const member of members) {
7955
+ if (member === anchor || member.ticks * anchor.timescale === anchor.ticks * member.timescale) continue;
7956
+ const nests = member.intraOnly && !anchor.intraOnly && anchor.ticks * member.timescale % (member.ticks * anchor.timescale) === 0n;
7957
+ if (!nests) {
7958
+ catalogError("track_switching_set", `$.tracks[${member.index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
7959
+ }
7648
7960
  }
7649
- if (!anchor) switchingSets.set(altGroup, { name: track["name"], ticks, timescale });
7650
7961
  }
7651
7962
  const multicast = catalog["multicast"];
7652
7963
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
@@ -7694,21 +8005,14 @@ function validateCmsfMmtpCatalog(value) {
7694
8005
  }
7695
8006
  }
7696
8007
  }
7697
- try {
7698
- resolveMulticastAuthCatalog(catalog);
7699
- } catch (error) {
7700
- catalogError(
7701
- "multicast_auth",
7702
- "$.multicast.auth",
7703
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
7704
- );
7705
- }
8008
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
8009
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
7706
8010
  validateArchive(catalog);
7707
8011
  return catalog;
7708
8012
  }
7709
8013
 
7710
8014
  // src/no-modules.ts
7711
- import { catalogFecInterleaveMs, computeFecTimeout } from "@blockcast/mmt-fec";
8015
+ import { catalogFecInterleaveMs, fecBlockBudgetMs as fecBlockBudgetMs2, fecBlockDeadlineMs } from "@blockcast/mmt-fec";
7712
8016
 
7713
8017
  // src/fec-state.ts
7714
8018
  var FEC_INACTIVE_REASONS = Object.freeze([
@@ -7722,22 +8026,16 @@ var INACTIVE = Object.freeze({
7722
8026
  "reliable-moq": Object.freeze({ state: "inactive", reason: "reliable-moq" }),
7723
8027
  "no-multicast-bridge": Object.freeze({ state: "inactive", reason: "no-multicast-bridge" })
7724
8028
  });
7725
- function recordOf(value) {
8029
+ function recordOf2(value) {
7726
8030
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7727
8031
  }
7728
- function isPositiveSafeInteger(value) {
8032
+ function isPositiveSafeInteger2(value) {
7729
8033
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
7730
8034
  }
7731
8035
  function catalogDeclaresFec(fec) {
7732
- const block = recordOf(fec);
7733
- if (block === void 0 || block["algorithm"] === "none") return false;
7734
- return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
7735
- }
7736
- function isoBlockSpanUsable(fec) {
7737
- const block = recordOf(fec);
7738
- if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1") return true;
7739
- const ms = block["interleaveDepthMs"];
7740
- return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
8036
+ const block = recordOf2(fec);
8037
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
8038
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
7741
8039
  }
7742
8040
  function requireBoolean(value, field) {
7743
8041
  if (typeof value !== "boolean") {
@@ -7753,7 +8051,7 @@ function resolveFecState(evidence) {
7753
8051
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
7754
8052
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
7755
8053
  }
7756
- if (stats !== null && stats !== void 0 && recordOf(stats) === void 0) {
8054
+ if (stats !== null && stats !== void 0 && recordOf2(stats) === void 0) {
7757
8055
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
7758
8056
  }
7759
8057
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
@@ -7765,6 +8063,385 @@ function resolveFecState(evidence) {
7765
8063
  return INACTIVE["reliable-moq"];
7766
8064
  }
7767
8065
 
8066
+ // src/mmtp-fec-session.ts
8067
+ import { deriveFecRetentionBlocks, fecBlockBudgetMs } from "@blockcast/mmt-fec";
8068
+ var PATH_BITS = { moq: 1, multicast: 2 };
8069
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8070
+ var MmtpFecSession = class {
8071
+ #decoder;
8072
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
8073
+ #blocks = /* @__PURE__ */ new Map();
8074
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
8075
+ #settled = /* @__PURE__ */ new Set();
8076
+ /**
8077
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
8078
+ * received on, or 0 for one the session recovered.
8079
+ */
8080
+ #have = /* @__PURE__ */ new Map();
8081
+ #newest;
8082
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
8083
+ #prunedAt;
8084
+ #repairPacketId;
8085
+ #stats = {
8086
+ sourceSymbols: 0,
8087
+ repairSymbols: 0,
8088
+ blocksClean: 0,
8089
+ blocksRecovered: 0,
8090
+ blocksFailed: 0,
8091
+ blocksReleased: 0,
8092
+ packetsRecovered: 0,
8093
+ packetsLost: 0,
8094
+ dropped: {},
8095
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
8096
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
8097
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
8098
+ };
8099
+ /**
8100
+ * @throws when the catalog block lacks or misstates a field the session
8101
+ * needs: the block profile, K, T, `interleaveDepthMs` or
8102
+ * `reorderToleranceMs`. None is defaulted.
8103
+ */
8104
+ constructor(config) {
8105
+ const fec = config?.fec;
8106
+ if (!fec || typeof fec !== "object") {
8107
+ throw new Error("MmtpFecSession: the catalog fec block is required");
8108
+ }
8109
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
8110
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
8111
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
8112
+ }
8113
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
8114
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8115
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8116
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8117
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
8118
+ this.retentionBlocks = deriveFecRetentionBlocks(
8119
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
8120
+ interleaveDepthMs
8121
+ );
8122
+ if (typeof config.Decoder !== "function") {
8123
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8124
+ }
8125
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
8126
+ try {
8127
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
8128
+ } catch (error) {
8129
+ decoder.free();
8130
+ throw error;
8131
+ }
8132
+ this.#decoder = decoder;
8133
+ }
8134
+ /** True once release() ran. */
8135
+ get released() {
8136
+ return this.#decoder === null;
8137
+ }
8138
+ get stats() {
8139
+ return {
8140
+ ...this.#stats,
8141
+ dropped: { ...this.#stats.dropped },
8142
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
8143
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
8144
+ mixedPath: { ...this.#stats.mixedPath }
8145
+ };
8146
+ }
8147
+ /**
8148
+ * Feeds one received source packet: the MMTP packet without its four-byte
8149
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
8150
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
8151
+ * was received; a caller that only subscribes over MoQT can leave it out.
8152
+ *
8153
+ * @returns the protected packets of this packet's block that it recovered,
8154
+ * in SS_ID order, for the caller to feed to its parser with
8155
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
8156
+ */
8157
+ addSource(ssId, packet, path = "moq") {
8158
+ const decoder = this.#decoder;
8159
+ if (!decoder) return this.#drop("source:released");
8160
+ const pathBit = PATH_BITS[path];
8161
+ if (!pathBit) return this.#drop("source:unknown-path");
8162
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
8163
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
8164
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
8165
+ this.#have.set(ssId, pathBit);
8166
+ this.#stats.sourceSymbols++;
8167
+ this.#stats.sourceSymbolsByPath[path]++;
8168
+ this.#noteNewest(ssId);
8169
+ const start = this.#blockStartOf(ssId);
8170
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
8171
+ if (block) {
8172
+ block.received++;
8173
+ block.paths |= pathBit;
8174
+ }
8175
+ let output;
8176
+ try {
8177
+ output = decoder.add_source(ssId, packet, 0);
8178
+ } catch {
8179
+ this.#drop("source:decoder-refused");
8180
+ output = void 0;
8181
+ }
8182
+ const recovered = [];
8183
+ if (start !== void 0 && block) {
8184
+ if (output) {
8185
+ recovered.push(...this.#settleDecoded(start, block, output));
8186
+ } else if (block.received >= block.ssbLength) {
8187
+ this.#settleClean(start);
8188
+ }
8189
+ }
8190
+ this.#retireBehindHorizon();
8191
+ return recovered;
8192
+ }
8193
+ /**
8194
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
8195
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
8196
+ * repair packet fixes its packet ID and a packet of any other is refused.
8197
+ * `path` is where it was received, as for addSource().
8198
+ *
8199
+ * @returns the protected packets this repair symbol recovered, as for
8200
+ * addSource().
8201
+ */
8202
+ addRepair(packet, path = "moq") {
8203
+ const decoder = this.#decoder;
8204
+ if (!decoder) return this.#drop("repair:released");
8205
+ const pathBit = PATH_BITS[path];
8206
+ if (!pathBit) return this.#drop("repair:unknown-path");
8207
+ let header;
8208
+ try {
8209
+ header = parseMMTPHeader(packet);
8210
+ } catch {
8211
+ return this.#drop("repair:malformed");
8212
+ }
8213
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
8214
+ if (!frame) return this.#drop("repair:malformed");
8215
+ if (this.#repairPacketId === void 0) {
8216
+ this.#repairPacketId = frame.packetId;
8217
+ } else if (frame.packetId !== this.#repairPacketId) {
8218
+ return this.#drop("repair:foreign-packet-id");
8219
+ }
8220
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
8221
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
8222
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
8223
+ return this.#drop("repair:rs-block-length");
8224
+ }
8225
+ const start = frame.ssStart;
8226
+ let block = this.#blocks.get(start);
8227
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
8228
+ if (block?.rsIds.has(frame.rsId)) return this.#drop("repair:duplicate");
8229
+ if (!block) {
8230
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
8231
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
8232
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
8233
+ this.#countHeld(start, block);
8234
+ this.#blocks.set(start, block);
8235
+ }
8236
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
8237
+ if (block.received >= block.ssbLength) {
8238
+ this.#settleClean(start);
8239
+ this.#retireBehindHorizon();
8240
+ return [];
8241
+ }
8242
+ let output;
8243
+ try {
8244
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
8245
+ } catch {
8246
+ return this.#drop("repair:decoder-refused");
8247
+ }
8248
+ block.rsIds.add(frame.rsId);
8249
+ this.#stats.repairSymbols++;
8250
+ this.#stats.repairSymbolsByPath[path]++;
8251
+ block.paths |= pathBit;
8252
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
8253
+ this.#retireBehindHorizon();
8254
+ return recovered;
8255
+ }
8256
+ /**
8257
+ * Frees the decoder and every block. Blocks still unsettled are counted as
8258
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
8259
+ * returns whether this call released anything.
8260
+ */
8261
+ release() {
8262
+ const decoder = this.#decoder;
8263
+ if (!decoder) return false;
8264
+ this.#decoder = null;
8265
+ this.#stats.blocksReleased += this.#blocks.size;
8266
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
8267
+ this.#blocks.clear();
8268
+ this.#settled.clear();
8269
+ this.#have.clear();
8270
+ decoder.free();
8271
+ return true;
8272
+ }
8273
+ #drop(reason) {
8274
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
8275
+ return [];
8276
+ }
8277
+ #noteNewest(ssId) {
8278
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
8279
+ }
8280
+ #blockStartOf(ssId) {
8281
+ for (const [start, block] of this.#blocks) {
8282
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
8283
+ }
8284
+ return void 0;
8285
+ }
8286
+ /** Counts the sources of a new block the parser already has, and their paths. */
8287
+ #countHeld(start, block) {
8288
+ for (let i = 0; i < block.ssbLength; i++) {
8289
+ const pathBit = this.#have.get(serial32Add(start, i));
8290
+ if (pathBit === void 0) continue;
8291
+ block.received++;
8292
+ block.paths |= pathBit;
8293
+ }
8294
+ }
8295
+ #noteMixed(block, outcome) {
8296
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
8297
+ }
8298
+ /** The decoder's own rule: more than its retention behind, counted from below. */
8299
+ #behindHorizon(start) {
8300
+ const newest = this.#newest;
8301
+ if (newest === void 0) return false;
8302
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
8303
+ }
8304
+ #settle(start) {
8305
+ this.#blocks.delete(start);
8306
+ this.#settled.add(start);
8307
+ }
8308
+ #settleClean(start) {
8309
+ const block = this.#blocks.get(start);
8310
+ if (!block) return;
8311
+ this.#settle(start);
8312
+ this.#stats.blocksClean++;
8313
+ this.#noteMixed(block, "clean");
8314
+ try {
8315
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
8316
+ } catch {
8317
+ }
8318
+ }
8319
+ /**
8320
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
8321
+ * concatenated: split by T, trim by each symbol's length field, and hand
8322
+ * back the packets the parser does not have yet.
8323
+ */
8324
+ #settleDecoded(start, block, output) {
8325
+ this.#settle(start);
8326
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
8327
+ this.#stats.blocksFailed++;
8328
+ this.#stats.packetsLost += block.ssbLength - block.received;
8329
+ this.#noteMixed(block, "failed");
8330
+ this.#drop("block:decoded-length");
8331
+ return [];
8332
+ }
8333
+ const recovered = [];
8334
+ let refused = 0;
8335
+ for (let i = 0; i < block.ssbLength; i++) {
8336
+ const ssId = serial32Add(start, i);
8337
+ if (this.#have.has(ssId)) continue;
8338
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
8339
+ const packet = trimSsbg1SourceSymbol(symbol);
8340
+ if (!packet) {
8341
+ refused++;
8342
+ continue;
8343
+ }
8344
+ this.#have.set(ssId, 0);
8345
+ recovered.push(packet.slice());
8346
+ }
8347
+ if (refused > 0) {
8348
+ this.#stats.blocksFailed++;
8349
+ this.#stats.packetsLost += refused;
8350
+ this.#noteMixed(block, "failed");
8351
+ this.#drop("block:bad-ssbg1-symbol");
8352
+ } else if (recovered.length === 0) {
8353
+ this.#stats.blocksClean++;
8354
+ this.#noteMixed(block, "clean");
8355
+ } else {
8356
+ this.#stats.blocksRecovered++;
8357
+ this.#noteMixed(block, "recovered");
8358
+ }
8359
+ this.#stats.packetsRecovered += recovered.length;
8360
+ return recovered;
8361
+ }
8362
+ /**
8363
+ * Retires every block, and every SS_ID the session remembers, that the
8364
+ * newest SS_ID has moved past the retention. An unsettled block retired
8365
+ * here is a failure: more of its sources were lost than its repair could
8366
+ * restore, or its repair never arrived.
8367
+ */
8368
+ #retireBehindHorizon() {
8369
+ const decoder = this.#decoder;
8370
+ const newest = this.#newest;
8371
+ if (!decoder || newest === void 0) return;
8372
+ try {
8373
+ decoder.cleanup_by_ss_start(newest);
8374
+ } catch {
8375
+ }
8376
+ for (const [start, block] of this.#blocks) {
8377
+ if (!this.#behindHorizon(start)) continue;
8378
+ this.#settle(start);
8379
+ this.#stats.blocksFailed++;
8380
+ this.#stats.packetsLost += block.ssbLength - block.received;
8381
+ this.#noteMixed(block, "failed");
8382
+ }
8383
+ const prunedAt = this.#prunedAt;
8384
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
8385
+ this.#prunedAt = newest;
8386
+ for (const ssId of this.#have.keys()) {
8387
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
8388
+ }
8389
+ for (const start of this.#settled) {
8390
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
8391
+ }
8392
+ }
8393
+ };
8394
+ function requirePositiveInteger(value, path) {
8395
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
8396
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
8397
+ }
8398
+ return value;
8399
+ }
8400
+ function requireNumber(value, path) {
8401
+ if (typeof value !== "number") {
8402
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
8403
+ }
8404
+ return value;
8405
+ }
8406
+
8407
+ // src/catalog-network-source.ts
8408
+ function normalizePort(value) {
8409
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
8410
+ return Number.isInteger(n) && n > 0 && n <= 65535 ? n : void 0;
8411
+ }
8412
+ function catalogAmtNetworkSource(networkSource) {
8413
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8414
+ for (const raw of entries) {
8415
+ if (!raw || typeof raw !== "object") continue;
8416
+ const ns = raw;
8417
+ if (ns.type !== "amt") continue;
8418
+ if (ns.discovery === "driad") continue;
8419
+ const relay = typeof ns.relay === "string" ? ns.relay.trim() : "";
8420
+ if (!relay) continue;
8421
+ return { relay, port: normalizePort(ns.port) ?? DEFAULT_AMT_RELAY_PORT };
8422
+ }
8423
+ return void 0;
8424
+ }
8425
+ function intIn(value, min, max) {
8426
+ return Number.isInteger(value) && value >= min && value <= max;
8427
+ }
8428
+ function catalogAtsc3NetworkSource(networkSource) {
8429
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8430
+ for (const raw of entries) {
8431
+ if (!raw || typeof raw !== "object") continue;
8432
+ const ns = raw;
8433
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
8434
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
8435
+ return {
8436
+ frequency: ns.frequency,
8437
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
8438
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
8439
+ ...slsUri ? { slsUri } : {}
8440
+ };
8441
+ }
8442
+ return void 0;
8443
+ }
8444
+
7768
8445
  // src/mmtp-to-cmaf.ts
7769
8446
  function box(type, ...children2) {
7770
8447
  let size = 8;
@@ -7807,8 +8484,8 @@ function u32(v) {
7807
8484
  }
7808
8485
  var KEYFRAME_FLAGS = 33554432;
7809
8486
  var DELTA_FLAGS = 16842752;
7810
- var UINT32_MAX = 4294967295;
7811
- var MAX_TRACK_ID = UINT32_MAX - 1;
8487
+ var UINT32_MAX2 = 4294967295;
8488
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
7812
8489
  var INT32_MIN = -2147483648;
7813
8490
  var INT32_MAX = 2147483647;
7814
8491
  function assertTrackId(trackId, label) {
@@ -7817,8 +8494,8 @@ function assertTrackId(trackId, label) {
7817
8494
  }
7818
8495
  }
7819
8496
  function assertTimescale(timescale, label) {
7820
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
7821
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
8497
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
8498
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
7822
8499
  }
7823
8500
  }
7824
8501
  function assertCompositionTimeOffsets(samples) {
@@ -8864,7 +9541,7 @@ var SOURCE_AUTH_OBJECT_ENTRY_LENGTH = 52;
8864
9541
  var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
8865
9542
  var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
8866
9543
  var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
8867
- var SOURCE_AUTH_SCOPE_LENGTH2 = 32;
9544
+ var SOURCE_AUTH_SCOPE_LENGTH = 32;
8868
9545
  var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
8869
9546
  function requireBytes(name, value, length) {
8870
9547
  if (value.byteLength !== length) {
@@ -8941,7 +9618,7 @@ function sourceAuthSignaturePreimage(authScope, groupId, objectCount, root) {
8941
9618
  throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
8942
9619
  }
8943
9620
  requireU64("groupId", groupId);
8944
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH2);
9621
+ requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
8945
9622
  requireBytes("root", root, 32);
8946
9623
  const preimage = new Uint8Array(100);
8947
9624
  const view2 = new DataView(preimage.buffer);
@@ -8992,6 +9669,20 @@ function decodeSourceAuthManifestFrame(frame) {
8992
9669
  }
8993
9670
 
8994
9671
  // ../mmt-manifest-verify/dist/verifier.js
9672
+ function manifestKeyFor(keys, epoch, kid) {
9673
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length)
9674
+ return void 0;
9675
+ if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
9676
+ return void 0;
9677
+ let signer;
9678
+ for (const key of keys) {
9679
+ if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
9680
+ signer = key;
9681
+ }
9682
+ if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
9683
+ return void 0;
9684
+ return signer.publicKey;
9685
+ }
8995
9686
  function manifestBindingId(trackName, sourceSymbolFormat) {
8996
9687
  return JSON.stringify([trackName, sourceSymbolFormat]);
8997
9688
  }
@@ -9068,11 +9759,12 @@ var ManifestVerifier = class {
9068
9759
  }
9069
9760
  if (context.authScope.byteLength !== 32)
9070
9761
  throw new Error("manifest authScope must be 32 bytes");
9071
- if (context.publicKey.byteLength !== 32)
9072
- throw new Error("manifest publicKey must be 32 bytes");
9073
- for (const key of context.acceptedPublicKeys ?? []) {
9074
- if (key.byteLength !== 32)
9075
- throw new Error("manifest acceptedPublicKeys must contain 32-byte keys");
9762
+ for (const key of context.keys) {
9763
+ if (key.publicKey.byteLength !== 32)
9764
+ throw new Error("manifest keys must carry 32-byte public keys");
9765
+ }
9766
+ if (manifestKeyFor(context.keys, context.keyEpoch) === void 0) {
9767
+ throw new Error(`manifest keys hold no key set signing keyEpoch ${context.keyEpoch}`);
9076
9768
  }
9077
9769
  for (const [name, value] of Object.entries({
9078
9770
  broadcastNamespaceId: context.broadcastNamespaceId,
@@ -9317,7 +10009,7 @@ var ManifestVerifier = class {
9317
10009
  }
9318
10010
  }
9319
10011
  #verifyAcceptedSignature(track, message, signature) {
9320
- const keys = track.context.acceptedPublicKeys ?? [track.context.publicKey];
10012
+ const keys = [manifestKeyFor(track.context.keys, track.context.keyEpoch)];
9321
10013
  const pending = [];
9322
10014
  let hadSynchronousError = false;
9323
10015
  for (const key of keys) {
@@ -9452,59 +10144,140 @@ var ManifestVerifier = class {
9452
10144
  }
9453
10145
  };
9454
10146
 
9455
- // src/manifest-auth-plan.ts
9456
- function createManifestAuthPlan(catalog, options) {
9457
- const resolved = resolveMulticastAuthCatalog(catalog, options.playerMode);
9458
- if (!resolved || resolved.mode === "off") return void 0;
9459
- const verifier = new ManifestVerifier({
9460
- manifestAuth: {
9461
- mode: resolved.mode,
9462
- onMissingManifest: options.onMissingManifest ?? (resolved.mode === "enforce" ? "stall" : "fallback-shadow")
9463
- },
9464
- verifySignature: options.verifySignature,
9465
- ...options.onFailure === void 0 ? {} : { onFailure: options.onFailure }
9466
- });
9467
- const byManifestTrack = /* @__PURE__ */ new Map();
9468
- const bindings = resolved.tracks.map((binding) => {
9469
- const bindingId = manifestBindingId(binding.mediaTrack, binding.sourceSymbolFormat);
9470
- const planned = {
9471
- bindingId,
9472
- mediaTrack: binding.mediaTrack,
9473
- manifestTrack: binding.manifestTrack,
9474
- sourceSymbolFormat: binding.sourceSymbolFormat
9475
- };
9476
- verifier.registerTrack({
9477
- ...options.contextFor(binding, resolved),
9478
- bindingId,
9479
- trackName: binding.mediaTrack,
9480
- sourceSymbolFormat: binding.sourceSymbolFormat,
9481
- authScope: binding.authScope,
9482
- publicKey: resolved.acceptedPublicKeys[0],
9483
- acceptedPublicKeys: resolved.acceptedPublicKeys
10147
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10148
+ var BCPV2_HEADER_LENGTH = 68;
10149
+ var BCPV2_SIGNATURE_LENGTH = 64;
10150
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10151
+ var text = new TextEncoder();
10152
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10153
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10154
+
10155
+ // src/multicast-auth-catalog.ts
10156
+ var RAW_ED25519_KEY_LENGTH = 32;
10157
+ var DEFAULT_MAX_AUTH_DELAY_MS = 200;
10158
+ var DEFAULT_MANIFEST_TIMER_MS = 20;
10159
+ var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10160
+ function encodeBase64Url(bytes) {
10161
+ let output = "";
10162
+ for (let i = 0; i < bytes.length; i += 3) {
10163
+ const b0 = bytes[i];
10164
+ const b1 = bytes[i + 1];
10165
+ const b2 = bytes[i + 2];
10166
+ output += BASE64URL_ALPHABET[b0 >> 2];
10167
+ output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
10168
+ if (b1 === void 0) break;
10169
+ output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
10170
+ if (b2 === void 0) break;
10171
+ output += BASE64URL_ALPHABET[b2 & 63];
10172
+ }
10173
+ return output;
10174
+ }
10175
+ var BASE64URL_DECODE_TABLE = (() => {
10176
+ const table = new Int8Array(128).fill(-1);
10177
+ for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
10178
+ table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
10179
+ }
10180
+ return table;
10181
+ })();
10182
+ function decodeBase64Url(text2) {
10183
+ if (text2.length % 4 === 1) {
10184
+ throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
10185
+ }
10186
+ const bytes = [];
10187
+ let buffer = 0;
10188
+ let bits = 0;
10189
+ for (let i = 0; i < text2.length; i++) {
10190
+ const code = text2.charCodeAt(i);
10191
+ const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
10192
+ if (value === void 0 || value < 0) {
10193
+ throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
10194
+ }
10195
+ buffer = buffer << 6 | value;
10196
+ bits += 6;
10197
+ if (bits >= 8) {
10198
+ bits -= 8;
10199
+ bytes.push(buffer >> bits & 255);
10200
+ }
10201
+ }
10202
+ const decoded = Uint8Array.from(bytes);
10203
+ if (encodeBase64Url(decoded) !== text2) {
10204
+ throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
10205
+ }
10206
+ return decoded;
10207
+ }
10208
+ function decodeEd25519PublicKey(publicKey) {
10209
+ const bytes = decodeBase64Url(publicKey);
10210
+ if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
10211
+ throw new Error(
10212
+ `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
10213
+ );
10214
+ }
10215
+ return bytes;
10216
+ }
10217
+ function resolveMulticastAuthCatalog(catalog, options = {}) {
10218
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
10219
+ throw new Error("[multicast-auth-catalog] catalog must be an object");
10220
+ }
10221
+ const issues = multicastCatalogIssues(catalog, options);
10222
+ const fatal = issues.find((issue) => issue.endpointIndex === void 0);
10223
+ if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
10224
+ const multicast = catalog["multicast"];
10225
+ const auth = multicast?.["auth"];
10226
+ if (auth === void 0) {
10227
+ if (options.requireAuth) {
10228
+ throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
10229
+ }
10230
+ return void 0;
10231
+ }
10232
+ const ignored = new Set(issues.map((issue) => issue.endpointIndex));
10233
+ const endpoints = multicast["endpoints"] ?? [];
10234
+ const flows = [];
10235
+ endpoints.forEach((endpoint, endpointIndex) => {
10236
+ if (ignored.has(endpointIndex)) return;
10237
+ const flowAuth = endpoint["auth"];
10238
+ flows.push({
10239
+ endpointIndex,
10240
+ source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
10241
+ groupAddress: endpoint["groupAddress"],
10242
+ port: endpoint["port"],
10243
+ bandwidth: endpoint["bandwidth"],
10244
+ manifestPort: flowAuth.manifestPort,
10245
+ streamId: flowAuth.streamId,
10246
+ maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
10247
+ manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
10248
+ ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
10249
+ tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
10250
+ name,
10251
+ packetId
10252
+ }))
9484
10253
  });
9485
- byManifestTrack.set(binding.manifestTrack, planned);
9486
- return planned;
9487
10254
  });
9488
- let disposed = false;
9489
10255
  return {
9490
- verifier,
9491
- mode: resolved.mode,
9492
- bindings,
10256
+ keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
10257
+ minEpoch: auth.minEpoch,
10258
+ flows
10259
+ };
10260
+ }
10261
+ function multicastAuthKeyFor(resolved, kid, epoch) {
10262
+ return manifestKeyFor(resolved.keys, epoch, kid);
10263
+ }
10264
+
10265
+ // src/manifest-auth-plan.ts
10266
+ function createManifestAuthPlan(catalog, options = {}) {
10267
+ const resolved = resolveMulticastAuthCatalog(catalog, options);
10268
+ if (!resolved) return void 0;
10269
+ const byManifestTrack = /* @__PURE__ */ new Map();
10270
+ for (const flow of resolved.flows) {
10271
+ if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
10272
+ }
10273
+ return {
10274
+ keys: resolved.keys,
10275
+ minEpoch: resolved.minEpoch,
10276
+ flows: resolved.flows,
9493
10277
  manifestTracks: [...byManifestTrack.keys()],
9494
- bindingIdFor(mediaTrack, sourceSymbolFormat) {
9495
- const bindingId = manifestBindingId(mediaTrack, sourceSymbolFormat);
9496
- return bindings.some((binding) => binding.bindingId === bindingId) ? bindingId : void 0;
9497
- },
9498
- ingestManifestPayload(manifestTrack, payload) {
9499
- const binding = byManifestTrack.get(manifestTrack);
9500
- if (!binding) throw new Error(`unknown manifest subscription track ${manifestTrack}`);
9501
- verifier.ingestManifestFrame(binding.bindingId, payload);
9502
- },
9503
- dispose() {
9504
- if (disposed) return;
9505
- disposed = true;
9506
- verifier.dispose();
9507
- }
10278
+ keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
10279
+ flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
10280
+ flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
9508
10281
  };
9509
10282
  }
9510
10283
  export {
@@ -9512,14 +10285,19 @@ export {
9512
10285
  FEC_INACTIVE_REASONS,
9513
10286
  ManifestVerifier,
9514
10287
  MmtpContainerParser,
10288
+ MmtpFecSession,
9515
10289
  MmtpToCmaf,
10290
+ catalogAmtNetworkSource,
10291
+ catalogAtsc3NetworkSource,
9516
10292
  catalogDeclaresFec,
9517
10293
  catalogFecInterleaveMs,
9518
- computeFecTimeout,
9519
10294
  createManifestAuthPlan,
9520
10295
  createWasmMmtpContainerParser,
9521
10296
  createWebCryptoEd25519Verifier,
9522
10297
  datagramMfuReassembly,
10298
+ fecBlockBudgetMs2 as fecBlockBudgetMs,
10299
+ fecBlockDeadlineMs,
10300
+ isFmp4InitSegment,
9523
10301
  manifestBindingId,
9524
10302
  mmtpFrameReorderWindowFrames,
9525
10303
  reliableMoqMfuReassembly,