@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
@@ -41,14 +41,19 @@ var BlockcastMmt = (() => {
41
41
  FEC_INACTIVE_REASONS: () => FEC_INACTIVE_REASONS,
42
42
  ManifestVerifier: () => ManifestVerifier,
43
43
  MmtpContainerParser: () => MmtpContainerParser,
44
+ MmtpFecSession: () => MmtpFecSession,
44
45
  MmtpToCmaf: () => MmtpToCmaf,
46
+ catalogAmtNetworkSource: () => catalogAmtNetworkSource,
47
+ catalogAtsc3NetworkSource: () => catalogAtsc3NetworkSource,
45
48
  catalogDeclaresFec: () => catalogDeclaresFec,
46
49
  catalogFecInterleaveMs: () => catalogFecInterleaveMs,
47
- computeFecTimeout: () => computeFecTimeout,
48
50
  createManifestAuthPlan: () => createManifestAuthPlan,
49
51
  createWasmMmtpContainerParser: () => createWasmMmtpContainerParser,
50
52
  createWebCryptoEd25519Verifier: () => createWebCryptoEd25519Verifier,
51
53
  datagramMfuReassembly: () => datagramMfuReassembly,
54
+ fecBlockBudgetMs: () => fecBlockBudgetMs,
55
+ fecBlockDeadlineMs: () => fecBlockDeadlineMs,
56
+ isFmp4InitSegment: () => isFmp4InitSegment,
52
57
  manifestBindingId: () => manifestBindingId,
53
58
  mmtpFrameReorderWindowFrames: () => mmtpFrameReorderWindowFrames,
54
59
  reliableMoqMfuReassembly: () => reliableMoqMfuReassembly,
@@ -209,26 +214,30 @@ var BlockcastMmt = (() => {
209
214
  const authLength = view2.getUint16(2, false);
210
215
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
211
216
  }
212
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
217
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
213
218
  if (declaredEnd > payload.length)
214
219
  return null;
215
220
  if (options?.skipFecId) {
216
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
221
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
217
222
  }
223
+ const overlay = options?.overlayDeclared === true && rapFlag;
218
224
  if (fecType === 1) {
219
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
225
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
220
226
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
221
227
  return null;
222
228
  }
223
- return { hasFecId: true };
229
+ return { hasFecId: true, hasOverlayFecId: overlay };
224
230
  }
225
- if (fecType !== 0)
231
+ if (fecType !== 0 || overlay)
226
232
  return null;
227
233
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
228
- return { hasFecId: false };
234
+ return { hasFecId: false, hasOverlayFecId: false };
229
235
  }
230
236
  return null;
231
237
  }
238
+ function sourceFecTrailerSize(overlay) {
239
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
240
+ }
232
241
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
233
242
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
234
243
  return {
@@ -281,15 +290,16 @@ var BlockcastMmt = (() => {
281
290
  if ("rejection" in layoutResult)
282
291
  return layoutResult;
283
292
  const { layout } = layoutResult;
284
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
293
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
285
294
  if (!trailerLayout) {
286
295
  if (!options?.skipFecId && header.fecType === 1) {
287
296
  const observed = payload.length - layout.dataEnd;
288
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
297
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
298
+ if (observed !== expected) {
289
299
  return {
290
300
  rejection: {
291
301
  gate: "source-fec-payload-id-width-mismatch",
292
- 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})`
302
+ 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})`
293
303
  }
294
304
  };
295
305
  }
@@ -316,10 +326,13 @@ var BlockcastMmt = (() => {
316
326
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
317
327
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
318
328
  const data = payload.subarray(mfuOffset, dataEnd);
319
- const fecPayloadId = trailerLayout.hasFecId ? {
320
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
321
- } : null;
322
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
329
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
330
+ const ssIdAt = (offset) => ({
331
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
332
+ });
333
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
334
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
335
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
323
336
  }
324
337
  function sourceFecPayloadIdOf(mmtpPacket, header) {
325
338
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -340,6 +353,57 @@ var BlockcastMmt = (() => {
340
353
  ssId: (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0
341
354
  };
342
355
  }
356
+ var REPAIR_FEC_PID_SIZE = 13;
357
+ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
358
+ let header;
359
+ if (parsedHeader) {
360
+ header = parsedHeader;
361
+ } else {
362
+ try {
363
+ header = parseMMTPHeader(mmtpPacket);
364
+ } catch {
365
+ return null;
366
+ }
367
+ }
368
+ if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2)
369
+ return null;
370
+ const off = header.headerLength;
371
+ if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE)
372
+ return null;
373
+ const ssStart = (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0;
374
+ const rsbLength = mmtpPacket[off + 4] << 16 | mmtpPacket[off + 5] << 8 | mmtpPacket[off + 6];
375
+ const rsId = mmtpPacket[off + 7] << 16 | mmtpPacket[off + 8] << 8 | mmtpPacket[off + 9];
376
+ const ssbLength = mmtpPacket[off + 10] << 16 | mmtpPacket[off + 11] << 8 | mmtpPacket[off + 12];
377
+ return {
378
+ packetId: header.packetId,
379
+ ssStart,
380
+ rsbLength,
381
+ rsId,
382
+ ssbLength,
383
+ dataOffset: off + REPAIR_FEC_PID_SIZE
384
+ };
385
+ }
386
+ function parseMoqRepairFrameWithHeader(frame, header) {
387
+ return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header));
388
+ }
389
+ function moqRepairFrameFrom(frame, repairId) {
390
+ if (!repairId)
391
+ return null;
392
+ const symbolData = frame.subarray(repairId.dataOffset);
393
+ if (repairId.rsbLength === 0 || repairId.ssbLength === 0 || repairId.rsId >= repairId.rsbLength || symbolData.length === 0)
394
+ return null;
395
+ return {
396
+ packetId: repairId.packetId,
397
+ ssStart: repairId.ssStart,
398
+ rsbLength: repairId.rsbLength,
399
+ rsId: repairId.rsId,
400
+ ssbLength: repairId.ssbLength,
401
+ symbolData
402
+ };
403
+ }
404
+
405
+ // ../mmt-base/dist/net-constants.js
406
+ var DEFAULT_AMT_RELAY_PORT = 2268;
343
407
 
344
408
  // ../mmt-base/dist/ntp-short.js
345
409
  var NTP_SHORT_BITS = 32;
@@ -348,6 +412,26 @@ var BlockcastMmt = (() => {
348
412
 
349
413
  // ../mmt-base/dist/serial-number.js
350
414
  var SERIAL32_SPAN = 4294967296;
415
+ var SERIAL32_HALF = 2147483648;
416
+ function assertUint32(value, name) {
417
+ if (!Number.isInteger(value) || value < 0 || value >= SERIAL32_SPAN) {
418
+ throw new RangeError(`${name} must be a uint32 (got ${value})`);
419
+ }
420
+ }
421
+ function serial32Add(s, n) {
422
+ assertUint32(s, "s");
423
+ if (!Number.isInteger(n) || n <= -SERIAL32_HALF || n >= SERIAL32_HALF) {
424
+ throw new RangeError(`serial addend must lie in (-2^31, 2^31) (got ${n})`);
425
+ }
426
+ return (s + n + SERIAL32_SPAN) % SERIAL32_SPAN;
427
+ }
428
+ function serial32Distance(from, to) {
429
+ return to - from >>> 0;
430
+ }
431
+ function serial32Precedes(a, b) {
432
+ const distance = serial32Distance(a, b);
433
+ return distance !== 0 && distance < SERIAL32_HALF;
434
+ }
351
435
 
352
436
  // ../mmt-base/dist/fec-block-profile.js
353
437
  var FEC_BLOCK_PROFILES = Object.freeze([
@@ -364,6 +448,311 @@ var BlockcastMmt = (() => {
364
448
  }
365
449
  throw new Error(`${where} must be "iso-ssbg1-v1" (got ${JSON.stringify(value)})`);
366
450
  }
451
+ var SSBG1_LENGTH_FIELD_BYTES = 2;
452
+ function ssbg1MaxPacketLength(symbolSize) {
453
+ return symbolSize - SSBG1_LENGTH_FIELD_BYTES;
454
+ }
455
+ function ssbg1FitsSymbol(packetLength, symbolSize) {
456
+ return Number.isSafeInteger(packetLength) && packetLength >= 0 && packetLength <= ssbg1MaxPacketLength(symbolSize) && packetLength <= 65535;
457
+ }
458
+ function trimSsbg1SourceSymbol(symbol) {
459
+ if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES)
460
+ return null;
461
+ const length = symbol[0] << 8 | symbol[1];
462
+ const end = SSBG1_LENGTH_FIELD_BYTES + length;
463
+ if (end > symbol.byteLength)
464
+ return null;
465
+ for (let i = end; i < symbol.byteLength; i++) {
466
+ if (symbol[i] !== 0)
467
+ return null;
468
+ }
469
+ return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end);
470
+ }
471
+ function isoBlockContains(ssStart, ssbLength, ssId) {
472
+ return serial32Distance(ssStart, ssId) < ssbLength;
473
+ }
474
+ function isoBlocksBehindLowerBound(a, b, kMax) {
475
+ if (!Number.isSafeInteger(kMax) || kMax <= 0) {
476
+ throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`);
477
+ }
478
+ return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
479
+ }
480
+
481
+ // ../mmt-base/dist/catalog-fec-source.js
482
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
483
+ function recordOf(value) {
484
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
485
+ }
486
+ function isoBlockSpanUsable(fec) {
487
+ const block = recordOf(fec);
488
+ if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1")
489
+ return true;
490
+ const ms = block["interleaveDepthMs"];
491
+ return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
492
+ }
493
+ function fecAlgorithmUnimplemented(algorithm) {
494
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
495
+ }
496
+ function isPositiveSafeInteger(value) {
497
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
498
+ }
499
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
500
+ function catalogFecDeclaresUnconfigurableInstance(fec) {
501
+ const block = recordOf(fec);
502
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"]))
503
+ return false;
504
+ if (!(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"])))
505
+ return true;
506
+ return block["blockProfile"] === "iso-ssbg1-v1" && block["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE;
507
+ }
508
+
509
+ // ../mmt-base/dist/multicast-catalog.js
510
+ var ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
511
+ var UINT32_MAX = 4294967295;
512
+ var AUTH_MEMBERS = /* @__PURE__ */ new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
513
+ var KEY_MEMBERS = /* @__PURE__ */ new Set(["kid", "publicKey", "firstEpoch"]);
514
+ var ENDPOINT_AUTH_MEMBERS = /* @__PURE__ */ new Set([
515
+ "manifestPort",
516
+ "streamId",
517
+ "senderAddress",
518
+ "maxAuthDelayMs",
519
+ "manifestTimerMs",
520
+ "manifestTrack"
521
+ ]);
522
+ function isObject(value) {
523
+ return typeof value === "object" && value !== null && !Array.isArray(value);
524
+ }
525
+ function isNonEmptyString(value) {
526
+ return typeof value === "string" && value.trim().length > 0;
527
+ }
528
+ function isIntegerIn(value, min, max) {
529
+ return Number.isSafeInteger(value) && value >= min && value <= max;
530
+ }
531
+ function multicastEndpointSource(endpoint) {
532
+ if (!isObject(endpoint))
533
+ return void 0;
534
+ const sourceAddress = endpoint["sourceAddress"];
535
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress))
536
+ return void 0;
537
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
538
+ const protocol = endpoint["protocol"];
539
+ if (protocol !== void 0 && protocol !== mode)
540
+ return void 0;
541
+ const auth = endpoint["auth"];
542
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : void 0;
543
+ if (mode === "ssm")
544
+ return senderAddress === void 0 ? { mode, source: sourceAddress } : void 0;
545
+ if (auth === void 0)
546
+ return { mode };
547
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : void 0;
548
+ }
549
+ function authIssues(auth) {
550
+ const base = "$.multicast.auth";
551
+ const issue = (path, message) => [
552
+ { code: "multicast_auth", path: `${base}${path}`, message }
553
+ ];
554
+ if (!isObject(auth))
555
+ return issue("", "auth must be an object");
556
+ const unknown = Object.keys(auth).filter((key) => !AUTH_MEMBERS.has(key));
557
+ if (unknown.length > 0) {
558
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
559
+ }
560
+ if (auth["scheme"] !== "bc-provenance")
561
+ return issue(".scheme", 'scheme must be "bc-provenance"');
562
+ if (auth["version"] !== 2)
563
+ return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
564
+ if (auth["sig"] !== "ed25519")
565
+ return issue(".sig", 'sig must be "ed25519"');
566
+ const keys = auth["keys"];
567
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
568
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
569
+ }
570
+ const kids = /* @__PURE__ */ new Set();
571
+ const firstEpochs = /* @__PURE__ */ new Set();
572
+ for (let index = 0; index < keys.length; index++) {
573
+ const key = keys[index];
574
+ const at = `.keys[${index}]`;
575
+ if (!isObject(key) || Object.keys(key).some((member) => !KEY_MEMBERS.has(member))) {
576
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
577
+ }
578
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX))
579
+ return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
580
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
581
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
582
+ }
583
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
584
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
585
+ }
586
+ if (kids.has(key["kid"]))
587
+ return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
588
+ if (firstEpochs.has(key["firstEpoch"])) {
589
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
590
+ }
591
+ kids.add(key["kid"]);
592
+ firstEpochs.add(key["firstEpoch"]);
593
+ }
594
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
595
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
596
+ }
597
+ return [];
598
+ }
599
+ function endpointAuthIssue(endpoint, mode, at) {
600
+ const auth = endpoint["auth"];
601
+ if (!isObject(auth))
602
+ return { path: `${at}.auth`, message: "auth must be an object" };
603
+ const unknown = Object.keys(auth).filter((key) => !ENDPOINT_AUTH_MEMBERS.has(key));
604
+ if (unknown.length > 0)
605
+ return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
606
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
607
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
608
+ }
609
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
610
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
611
+ }
612
+ if (mode === "ssm" && auth["senderAddress"] !== void 0) {
613
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
614
+ }
615
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
616
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
617
+ }
618
+ if (auth["maxAuthDelayMs"] !== void 0 && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1e3)) {
619
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
620
+ }
621
+ if (auth["manifestTimerMs"] !== void 0 && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
622
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
623
+ }
624
+ if (auth["manifestTrack"] !== void 0 && !isNonEmptyString(auth["manifestTrack"])) {
625
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
626
+ }
627
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
628
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
629
+ }
630
+ return void 0;
631
+ }
632
+ var CATALOG_NAMESPACE = /* @__PURE__ */ Symbol.for("@blockcast/mmt-base/catalogNamespace");
633
+ function multicastCatalogIssues(catalog, options = {}) {
634
+ if (!isObject(catalog))
635
+ return [];
636
+ const issues = [];
637
+ if ("multicast.auth" in catalog) {
638
+ issues.push({
639
+ code: "multicast_auth",
640
+ path: '$["multicast.auth"]',
641
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)'
642
+ });
643
+ }
644
+ const multicast = catalog["multicast"];
645
+ if (!isObject(multicast))
646
+ return issues;
647
+ const protectedCatalog = multicast["auth"] !== void 0;
648
+ if (protectedCatalog)
649
+ issues.push(...authIssues(multicast["auth"]));
650
+ const endpoints = multicast["endpoints"];
651
+ if (!Array.isArray(endpoints))
652
+ return issues;
653
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
654
+ const namespaceOf = /* @__PURE__ */ new Map();
655
+ for (const track of tracks) {
656
+ if (isObject(track) && typeof track["name"] === "string")
657
+ namespaceOf.set(track["name"], track["namespace"]);
658
+ }
659
+ const tagged = catalog[CATALOG_NAMESPACE];
660
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
661
+ const sources = [];
662
+ for (let index = 0; index < endpoints.length; index++) {
663
+ const endpoint = endpoints[index];
664
+ const at = `$.multicast.endpoints[${index}]`;
665
+ const fail = (code, path, message) => {
666
+ issues.push({ code, path, message, endpointIndex: index });
667
+ };
668
+ sources.push(void 0);
669
+ if (!isObject(endpoint)) {
670
+ fail("multicast_endpoint", at, "endpoint must be an object");
671
+ continue;
672
+ }
673
+ const protocol = endpoint["protocol"];
674
+ if (protocol !== void 0 && protocol !== "ssm" && protocol !== "asm") {
675
+ 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)`);
676
+ continue;
677
+ }
678
+ const hasAuth = endpoint["auth"] !== void 0;
679
+ if (protectedCatalog !== hasAuth) {
680
+ 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");
681
+ continue;
682
+ }
683
+ const sourceAddress = endpoint["sourceAddress"];
684
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress)) {
685
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
686
+ continue;
687
+ }
688
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
689
+ if (protocol !== void 0 && protocol !== mode) {
690
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
691
+ continue;
692
+ }
693
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
694
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
695
+ continue;
696
+ }
697
+ if (hasAuth) {
698
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
699
+ if (authIssue) {
700
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
701
+ continue;
702
+ }
703
+ }
704
+ sources[index] = multicastEndpointSource(endpoint);
705
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
706
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
707
+ const ref = refs[refIndex];
708
+ const name = isObject(ref) ? ref["name"] : ref;
709
+ if (typeof name !== "string")
710
+ continue;
711
+ const namespace = namespaceOf.get(name);
712
+ if (typeof namespace !== "string")
713
+ continue;
714
+ referenceNamespace ?? (referenceNamespace = namespace);
715
+ if (namespace !== referenceNamespace) {
716
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
717
+ }
718
+ }
719
+ }
720
+ const tupleOf = (index) => {
721
+ const endpoint = endpoints[index];
722
+ const auth = endpoint["auth"];
723
+ return {
724
+ sg: JSON.stringify([sources[index].source ?? null, endpoint["groupAddress"]]),
725
+ port: endpoint["port"],
726
+ manifestPort: isObject(auth) ? auth["manifestPort"] : void 0
727
+ };
728
+ };
729
+ for (let index = 0; index < endpoints.length; index++) {
730
+ if (!sources[index])
731
+ continue;
732
+ const own = tupleOf(index);
733
+ const at = `$.multicast.endpoints[${index}]`;
734
+ if (own.manifestPort !== void 0 && own.manifestPort === own.port) {
735
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
736
+ continue;
737
+ }
738
+ for (let other = 0; other < endpoints.length; other++) {
739
+ if (other === index || !sources[other])
740
+ continue;
741
+ const peer = tupleOf(other);
742
+ if (peer.sg !== own.sg)
743
+ continue;
744
+ if (peer.port === own.port) {
745
+ 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 });
746
+ break;
747
+ }
748
+ if (own.manifestPort !== void 0 && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
749
+ 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 });
750
+ break;
751
+ }
752
+ }
753
+ }
754
+ return issues;
755
+ }
367
756
 
368
757
  // src/mfu-reassembler.ts
369
758
  function fragmentProvenance(fragment) {
@@ -3207,8 +3596,14 @@ var BlockcastMmt = (() => {
3207
3596
  /**
3208
3597
  * Add one reassembled data unit. Returns the combined sample once every
3209
3598
  * constituent data unit has arrived and totals the authored size.
3599
+ *
3600
+ * `sampleSize` is the authored size the host resolves for the sample as the
3601
+ * data unit completes. It stands in only when no size was registered, which
3602
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
3603
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
3604
+ * fragments, or one decoded before its source copy arrived.
3210
3605
  */
3211
- addMfu(mfu) {
3606
+ addMfu(mfu, sampleSize) {
3212
3607
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3213
3608
  __privateGet(this, _stats).passthroughSamples++;
3214
3609
  return fromPassthrough(mfu);
@@ -3224,7 +3619,7 @@ var BlockcastMmt = (() => {
3224
3619
  return null;
3225
3620
  }
3226
3621
  const dataLen = mfu.data.byteLength;
3227
- const authoredSize = __privateGet(this, _authoredSizes).get(key);
3622
+ const authoredSize = __privateGet(this, _authoredSizes).get(key) ?? sampleSize;
3228
3623
  if (offset === 0 && !__privateGet(this, _pending).has(key)) {
3229
3624
  const passesThrough = authoredSize === void 0 ? !__privateGet(this, _requireAuthoredSize) : dataLen === authoredSize;
3230
3625
  if (passesThrough) {
@@ -3532,6 +3927,12 @@ var BlockcastMmt = (() => {
3532
3927
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
3533
3928
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
3534
3929
  });
3930
+ test("a size handed with the data unit completes a sample no head registered", () => {
3931
+ const c = combiner({ requireAuthoredSize: true });
3932
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
3933
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
3934
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
3935
+ });
3535
3936
  test("duplicate offset is rejected", () => {
3536
3937
  const c = combiner();
3537
3938
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -5519,7 +5920,8 @@ var BlockcastMmt = (() => {
5519
5920
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
5520
5921
  return FMPU_BOX_TYPES.has(type);
5521
5922
  }
5522
- var _tracks, _defaultTrack, _reassembler, _sampleCombiners, _sampleCombinerOptions, _retiredSampleCombinerStats, _timingStreams, _maxPendingTimingSamples, _pendingTimingSamples, _reclaimedTimingSamples, _evictedTimingSamples, _rejectedMovieFragments, _sequencers, _fecGate, _fecSequencer, _reorderWindow, _reassemblyPolicy, _frameCb, _initCb, _sourceSymbolCb, _trackFrameCbs, _reorderStats, _reliableMoqStartupGate, _disposed, _fedObjects, _reassemblerFragmentsFed, _reassemblerDataUnitsReturned, _feedOutcomes, _deferredFeedOutcomes, _lastOutcome, _lastOutcomeCount, _MmtpContainerParser_instances, streamKey_fn, sampleCombinerFor_fn, releaseTimingSlot_fn, dropSampleCombiner_fn, countOutcome_fn, countDeferredOutcome_fn, drop_fn, feedCounted_fn, feed_fn, emitCombinedSample_fn, passReliableMoqStartupGate_fn, timingResolver_fn, dropTimingStream_fn, validateReassemblyPolicy_fn, buildFrameMeta_fn, sequencerFor_fn, flushSequencers_fn, emitFrame_fn2, _MmtpContainerParser_static, scanForKeyframe_fn, scanLengthPrefixedHevcForKeyframe_fn, scanAnnexBForKeyframe_fn;
5923
+ var MAX_AWAITING_TIMING_HEADS = 8;
5924
+ var _tracks, _defaultTrack, _reassembler, _sampleCombiners, _sampleCombinerOptions, _retiredSampleCombinerStats, _timingStreams, _maxPendingTimingSamples, _pendingTimingSamples, _reclaimedTimingSamples, _evictedTimingSamples, _rejectedMovieFragments, _sequencers, _fecGate, _fecSequencer, _reorderWindow, _reassemblyPolicy, _frameCb, _initCb, _sourceSymbolCb, _trackFrameCbs, _reorderStats, _reliableMoqStartupGate, _disposed, _replayingAwaitingTiming, _fedObjects, _reassemblerFragmentsFed, _reassemblerDataUnitsReturned, _feedOutcomes, _deferredFeedOutcomes, _lastOutcome, _lastOutcomeCount, _MmtpContainerParser_instances, streamKey_fn, sampleCombinerFor_fn, releaseTimingSlot_fn, dropSampleCombiner_fn, countOutcome_fn, countDeferredOutcome_fn, drop_fn, feedCounted_fn, feed_fn, emitCombinedSample_fn, passReliableMoqStartupGate_fn, timingResolver_fn, awaitTiming_fn, replayAwaitingTiming_fn, dropTimingStream_fn, validateReassemblyPolicy_fn, buildFrameMeta_fn, sequencerFor_fn, flushSequencers_fn, emitFrame_fn2, _MmtpContainerParser_static, scanForKeyframe_fn, scanLengthPrefixedHevcForKeyframe_fn, scanAnnexBForKeyframe_fn;
5523
5925
  var _MmtpContainerParser = class _MmtpContainerParser {
5524
5926
  constructor(config) {
5525
5927
  __privateAdd(this, _MmtpContainerParser_instances);
@@ -5582,6 +5984,7 @@ var BlockcastMmt = (() => {
5582
5984
  * reordering into the parser. */
5583
5985
  __privateAdd(this, _reliableMoqStartupGate, /* @__PURE__ */ new Map());
5584
5986
  __privateAdd(this, _disposed, false);
5987
+ __privateAdd(this, _replayingAwaitingTiming, false);
5585
5988
  __privateAdd(this, _fedObjects, 0);
5586
5989
  __privateAdd(this, _reassemblerFragmentsFed, 0);
5587
5990
  __privateAdd(this, _reassemblerDataUnitsReturned, 0);
@@ -5840,6 +6243,12 @@ var BlockcastMmt = (() => {
5840
6243
  for (const combiner of __privateGet(this, _sampleCombiners).values()) {
5841
6244
  combiner.cleanupTimeouts(timeoutMs);
5842
6245
  }
6246
+ const now = Date.now();
6247
+ for (const { awaitingTiming } of __privateGet(this, _timingStreams).values()) {
6248
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
6249
+ awaitingTiming.shift();
6250
+ }
6251
+ }
5843
6252
  }
5844
6253
  /**
5845
6254
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -6126,6 +6535,7 @@ var BlockcastMmt = (() => {
6126
6535
  _reorderStats = new WeakMap();
6127
6536
  _reliableMoqStartupGate = new WeakMap();
6128
6537
  _disposed = new WeakMap();
6538
+ _replayingAwaitingTiming = new WeakMap();
6129
6539
  _fedObjects = new WeakMap();
6130
6540
  _reassemblerFragmentsFed = new WeakMap();
6131
6541
  _reassemblerDataUnitsReturned = new WeakMap();
@@ -6206,7 +6616,8 @@ var BlockcastMmt = (() => {
6206
6616
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
6207
6617
  */
6208
6618
  drop_fn = function(reason) {
6209
- __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, `drop:${reason}`);
6619
+ if (__privateGet(this, _replayingAwaitingTiming)) __privateMethod(this, _MmtpContainerParser_instances, countDeferredOutcome_fn).call(this, reason);
6620
+ else __privateMethod(this, _MmtpContainerParser_instances, countOutcome_fn).call(this, `drop:${reason}`);
6210
6621
  return null;
6211
6622
  };
6212
6623
  feedCounted_fn = function(packet, options, parsed) {
@@ -6235,7 +6646,7 @@ var BlockcastMmt = (() => {
6235
6646
  byteLength: packet.byteLength
6236
6647
  };
6237
6648
  }
6238
- if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb)) {
6649
+ if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb) && !__privateGet(this, _replayingAwaitingTiming)) {
6239
6650
  const rawSymbol = packet.subarray(0, packet.length - 4);
6240
6651
  try {
6241
6652
  __privateGet(this, _sourceSymbolCb).call(this, info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -6283,6 +6694,7 @@ var BlockcastMmt = (() => {
6283
6694
  }
6284
6695
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-timing-refused");
6285
6696
  }
6697
+ __privateMethod(this, _MmtpContainerParser_instances, replayAwaitingTiming_fn).call(this, streamKey, resolver2);
6286
6698
  return {
6287
6699
  kind: "fragment",
6288
6700
  packet: info,
@@ -6306,7 +6718,18 @@ var BlockcastMmt = (() => {
6306
6718
  mfuDuHeader.movieFragmentSequenceNumber,
6307
6719
  mfuDuHeader.sampleNumber
6308
6720
  );
6309
- if (!headTiming) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-sample-timing-missing");
6721
+ if (!headTiming) {
6722
+ __privateMethod(this, _MmtpContainerParser_instances, awaitTiming_fn).call(this, streamKey, {
6723
+ packet,
6724
+ options,
6725
+ parsed,
6726
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
6727
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
6728
+ sampleNumber: mfuDuHeader.sampleNumber,
6729
+ arrivedAt: Date.now()
6730
+ });
6731
+ return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-sample-timing-missing");
6732
+ }
6310
6733
  const offset = mfuDuHeader.offset;
6311
6734
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
6312
6735
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-offset-out-of-range");
@@ -6376,16 +6799,17 @@ var BlockcastMmt = (() => {
6376
6799
  const sampleNumber = assembled.sampleNumber;
6377
6800
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
6378
6801
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-identity-missing");
6379
- if (!resolver.sampleTiming(
6802
+ const assembledTiming = resolver.sampleTiming(
6380
6803
  assembled.mpuSequenceNumber,
6381
6804
  movieFragmentSequenceNumber,
6382
6805
  sampleNumber
6383
- )) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-timing-missing");
6806
+ );
6807
+ if (!assembledTiming) return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-timing-missing");
6384
6808
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
6385
6809
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-mpu-mismatch");
6386
6810
  let combined;
6387
6811
  try {
6388
- combined = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).addMfu(assembled);
6812
+ combined = __privateMethod(this, _MmtpContainerParser_instances, sampleCombinerFor_fn).call(this, streamKey).addMfu(assembled, assembledTiming.size);
6389
6813
  } catch (error) {
6390
6814
  if (!(error instanceof SampleCombineError)) throw error;
6391
6815
  console.warn(
@@ -6479,9 +6903,37 @@ var BlockcastMmt = (() => {
6479
6903
  if (existing) return existing.resolver;
6480
6904
  if (!create) return null;
6481
6905
  const resolver = new IsoBmffTimingResolver(__privateGet(this, _maxPendingTimingSamples));
6482
- __privateGet(this, _timingStreams).set(streamKey, { packetId, resolver });
6906
+ __privateGet(this, _timingStreams).set(streamKey, { packetId, resolver, awaitingTiming: [] });
6483
6907
  return resolver;
6484
6908
  };
6909
+ awaitTiming_fn = function(streamKey, head) {
6910
+ const awaitingTiming = __privateGet(this, _timingStreams).get(streamKey)?.awaitingTiming;
6911
+ if (!awaitingTiming) return;
6912
+ awaitingTiming.push(head);
6913
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
6914
+ };
6915
+ /**
6916
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
6917
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
6918
+ * FEC path routes a source symbol that already arrived a second time.
6919
+ */
6920
+ replayAwaitingTiming_fn = function(streamKey, resolver) {
6921
+ const state = __privateGet(this, _timingStreams).get(streamKey);
6922
+ if (!state || state.awaitingTiming.length === 0) return;
6923
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
6924
+ head.mpuSequenceNumber,
6925
+ head.movieFragmentSequenceNumber,
6926
+ head.sampleNumber
6927
+ ));
6928
+ if (ready.length === 0) return;
6929
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
6930
+ __privateSet(this, _replayingAwaitingTiming, true);
6931
+ try {
6932
+ for (const head of ready) __privateMethod(this, _MmtpContainerParser_instances, feed_fn).call(this, head.packet, head.options, head.parsed);
6933
+ } finally {
6934
+ __privateSet(this, _replayingAwaitingTiming, false);
6935
+ }
6936
+ };
6485
6937
  dropTimingStream_fn = function(streamKey) {
6486
6938
  const state = __privateGet(this, _timingStreams).get(streamKey);
6487
6939
  if (!state) return;
@@ -6983,197 +7435,6 @@ var BlockcastMmt = (() => {
6983
7435
  });
6984
7436
  }
6985
7437
 
6986
- // src/multicast-auth-catalog.ts
6987
- var RAW_ED25519_KEY_LENGTH = 32;
6988
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
6989
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6990
- function encodeBase64Url(bytes) {
6991
- let output = "";
6992
- for (let i = 0; i < bytes.length; i += 3) {
6993
- const b0 = bytes[i];
6994
- const b1 = bytes[i + 1];
6995
- const b2 = bytes[i + 2];
6996
- output += BASE64URL_ALPHABET[b0 >> 2];
6997
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
6998
- if (b1 === void 0) break;
6999
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
7000
- if (b2 === void 0) break;
7001
- output += BASE64URL_ALPHABET[b2 & 63];
7002
- }
7003
- return output;
7004
- }
7005
- var BASE64URL_DECODE_TABLE = (() => {
7006
- const table = new Int8Array(128).fill(-1);
7007
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
7008
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
7009
- }
7010
- return table;
7011
- })();
7012
- function decodeBase64Url(text) {
7013
- if (text.length % 4 === 1) {
7014
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
7015
- }
7016
- const bytes = [];
7017
- let buffer = 0;
7018
- let bits = 0;
7019
- for (let i = 0; i < text.length; i++) {
7020
- const code = text.charCodeAt(i);
7021
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
7022
- if (value === void 0 || value < 0) {
7023
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
7024
- }
7025
- buffer = buffer << 6 | value;
7026
- bits += 6;
7027
- if (bits >= 8) {
7028
- bits -= 8;
7029
- bytes.push(buffer >> bits & 255);
7030
- }
7031
- }
7032
- const decoded = Uint8Array.from(bytes);
7033
- if (encodeBase64Url(decoded) !== text) {
7034
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
7035
- }
7036
- return decoded;
7037
- }
7038
- function decodeAuthScope(authScope) {
7039
- const bytes = decodeBase64Url(authScope);
7040
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
7041
- throw new Error(
7042
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
7043
- );
7044
- }
7045
- return bytes;
7046
- }
7047
- function decodeEd25519PublicKey(publicKey) {
7048
- const bytes = decodeBase64Url(publicKey);
7049
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
7050
- throw new Error(
7051
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
7052
- );
7053
- }
7054
- return bytes;
7055
- }
7056
- function isNonEmptyString(value) {
7057
- return typeof value === "string" && value.length > 0;
7058
- }
7059
- function isValidAuthScopeField(value) {
7060
- if (!isNonEmptyString(value)) return false;
7061
- try {
7062
- decodeAuthScope(value);
7063
- return true;
7064
- } catch {
7065
- return false;
7066
- }
7067
- }
7068
- function isValidPublicKeyField(value) {
7069
- if (!isNonEmptyString(value)) return false;
7070
- try {
7071
- decodeEd25519PublicKey(value);
7072
- return true;
7073
- } catch {
7074
- return false;
7075
- }
7076
- }
7077
- function hasOnlyKeys(object, allowed) {
7078
- const allowedKeys = new Set(allowed);
7079
- return Object.keys(object).every((key) => allowedKeys.has(key));
7080
- }
7081
- function isMulticastAuthTrackConfig(obj) {
7082
- if (typeof obj !== "object" || obj === null) return false;
7083
- const o = obj;
7084
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
7085
- }
7086
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
7087
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
7088
- function hasUniqueMulticastAuthTrackBindings(tracks) {
7089
- const bindings = tracks.flatMap((track) => {
7090
- if (typeof track !== "object" || track === null) return [];
7091
- const value = track;
7092
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
7093
- return [];
7094
- }
7095
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
7096
- });
7097
- return new Set(bindings).size === bindings.length;
7098
- }
7099
- function isMulticastAuthConfig(obj) {
7100
- if (typeof obj !== "object" || obj === null) return false;
7101
- const o = obj;
7102
- if (o["scheme"] !== "bc-provenance") return false;
7103
- if (o["hash"] !== "blake3") return false;
7104
- if (o["sig"] !== "ed25519") return false;
7105
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
7106
- if (!isValidPublicKeyField(o["publicKey"])) return false;
7107
- if (!isNonEmptyString(o["keyId"])) return false;
7108
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
7109
- if (o["previousKey"] === o["publicKey"]) return false;
7110
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
7111
- if (o["enforcement"] !== void 0) {
7112
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
7113
- }
7114
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
7115
- const tracks = o["tracks"];
7116
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
7117
- const typedTracks = tracks;
7118
- const scopes = typedTracks.map((t) => t.authScope);
7119
- if (new Set(scopes).size !== scopes.length) return false;
7120
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
7121
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
7122
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
7123
- return true;
7124
- }
7125
- function resolveMulticastAuthMode(playerMode, auth) {
7126
- if (playerMode !== void 0) return playerMode;
7127
- if (auth === void 0) return "off";
7128
- return auth.enforcement ?? "shadow";
7129
- }
7130
- function resolveMulticastAuthCatalog(catalog, playerMode) {
7131
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
7132
- throw new Error("[multicast-auth-catalog] catalog must be an object");
7133
- }
7134
- const root = catalog;
7135
- const rawAuth = root["multicast.auth"];
7136
- if (rawAuth === void 0) {
7137
- if (playerMode === "enforce") {
7138
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
7139
- }
7140
- return void 0;
7141
- }
7142
- if (!isMulticastAuthConfig(rawAuth)) {
7143
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
7144
- }
7145
- const rawTracks = root["tracks"];
7146
- if (!Array.isArray(rawTracks)) {
7147
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
7148
- }
7149
- const catalogTrackNames = new Set(
7150
- rawTracks.flatMap(
7151
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
7152
- )
7153
- );
7154
- for (const track of rawAuth.tracks) {
7155
- if (!catalogTrackNames.has(track.mediaTrack)) {
7156
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
7157
- }
7158
- if (!catalogTrackNames.has(track.manifestTrack)) {
7159
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
7160
- }
7161
- }
7162
- return {
7163
- keyId: rawAuth.keyId,
7164
- acceptedPublicKeys: [
7165
- decodeEd25519PublicKey(rawAuth.publicKey),
7166
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
7167
- ],
7168
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
7169
- compaction: rawAuth.compaction,
7170
- tracks: rawAuth.tracks.map((track) => ({
7171
- ...track,
7172
- authScope: decodeAuthScope(track.authScope)
7173
- }))
7174
- };
7175
- }
7176
-
7177
7438
  // src/repair-layers.ts
7178
7439
  var REPAIR_PRIORITY_MIN = 192;
7179
7440
  var REPAIR_PRIORITY_MAX = 255;
@@ -7181,6 +7442,7 @@ var BlockcastMmt = (() => {
7181
7442
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
7182
7443
  var MAX_REPAIR_SYMBOLS = 16777215;
7183
7444
  var MAX_ENCODING_SYMBOL_ID = 16777215;
7445
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
7184
7446
  var RepairContractError = class extends Error {
7185
7447
  constructor(code, path, message) {
7186
7448
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -7363,11 +7625,12 @@ var BlockcastMmt = (() => {
7363
7625
  if (layered && !positiveInteger(source.sourceSymbols)) {
7364
7626
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
7365
7627
  }
7366
- if (layered && source.algorithm !== "raptorq") {
7628
+ const reedSolomon = source.algorithm === "reed-solomon";
7629
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
7367
7630
  fail(
7368
7631
  "track_fec",
7369
7632
  `${source.path}.algorithm`,
7370
- "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"
7633
+ "repair layers and overlays are defined only for raptorq and reed-solomon (draft-ramadan-moq-fec-01 6.3.4 rule 7)"
7371
7634
  );
7372
7635
  }
7373
7636
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -7426,6 +7689,13 @@ var BlockcastMmt = (() => {
7426
7689
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7427
7690
  );
7428
7691
  }
7692
+ if (reedSolomon && sourceSymbols + repairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
7693
+ fail(
7694
+ "track_fec_bounds",
7695
+ `${d.path}.repairSymbols`,
7696
+ `reed-solomon overlay sourceSymbols + repairSymbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
7697
+ );
7698
+ }
7429
7699
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
7430
7700
  }
7431
7701
  let offset = layerZeroSymbols;
@@ -7470,6 +7740,13 @@ var BlockcastMmt = (() => {
7470
7740
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7471
7741
  );
7472
7742
  }
7743
+ if (reedSolomon && k + totalBaseRepairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
7744
+ fail(
7745
+ "track_fec_bounds",
7746
+ `${source.path}.sourceSymbols`,
7747
+ `reed-solomon sourceSymbols + total base repair symbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
7748
+ );
7749
+ }
7473
7750
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
7474
7751
  }
7475
7752
 
@@ -7557,7 +7834,7 @@ var BlockcastMmt = (() => {
7557
7834
  function catalogError(code, path, message) {
7558
7835
  throw new CmsfCatalogValidationError(code, path, message);
7559
7836
  }
7560
- function validateCmsfMmtpCatalog(value) {
7837
+ function validateCmsfMmtpCatalog(value, options = {}) {
7561
7838
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
7562
7839
  catalogError("catalog_object", "$", "catalog must be an object");
7563
7840
  }
@@ -7578,6 +7855,22 @@ var BlockcastMmt = (() => {
7578
7855
  "commonTrackFields is retired; every track carries its own fields"
7579
7856
  );
7580
7857
  }
7858
+ const initDataList = catalog["initDataList"];
7859
+ if (initDataList !== void 0) {
7860
+ if (!Array.isArray(initDataList)) {
7861
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
7862
+ }
7863
+ initDataList.forEach((entry, i) => {
7864
+ const e = entry;
7865
+ const entryPath = `$.initDataList[${i}]`;
7866
+ 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) {
7867
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
7868
+ }
7869
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
7870
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
7871
+ }
7872
+ });
7873
+ }
7581
7874
  const tracks = catalog["tracks"];
7582
7875
  const trackRecords = [];
7583
7876
  const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -7629,6 +7922,14 @@ var BlockcastMmt = (() => {
7629
7922
  if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
7630
7923
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
7631
7924
  }
7925
+ const anchor = track["presentationAnchorTicks"];
7926
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
7927
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
7928
+ }
7929
+ const initRef = track["initRef"];
7930
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
7931
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7932
+ }
7632
7933
  if (packaging === "fec-repair") {
7633
7934
  rejectRepairTrackGeometry(path, track, catalogError);
7634
7935
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -7636,9 +7937,8 @@ var BlockcastMmt = (() => {
7636
7937
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
7637
7938
  }
7638
7939
  if (packaging === "mmtp") {
7639
- const mmtpMode = track["mmtpMode"];
7640
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
7641
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
7940
+ if (track["mmtpMode"] !== "mfu") {
7941
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7642
7942
  }
7643
7943
  if (!positiveInteger2(timescale)) {
7644
7944
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -7661,8 +7961,8 @@ var BlockcastMmt = (() => {
7661
7961
  }
7662
7962
  const config = fec;
7663
7963
  const algorithm = config["algorithm"];
7664
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
7665
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
7964
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
7965
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
7666
7966
  }
7667
7967
  if ("interleaveDepth" in config || "interleaveMs" in config) {
7668
7968
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -7691,6 +7991,9 @@ var BlockcastMmt = (() => {
7691
7991
  }
7692
7992
  }
7693
7993
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
7994
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
7995
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
7996
+ }
7694
7997
  }
7695
7998
  }
7696
7999
  const repairDescriptors = trackRecords.flatMap(
@@ -7740,11 +8043,21 @@ var BlockcastMmt = (() => {
7740
8043
  const timescale = BigInt(track["timescale"]);
7741
8044
  const durationTicks = track["groupDurationTicks"];
7742
8045
  const ticks = durationTicks !== void 0 ? BigInt(durationTicks) : BigInt(track["groupDurationMs"]) * timescale / 1000n;
7743
- const anchor = switchingSets.get(altGroup);
7744
- if (anchor && ticks * anchor.timescale !== anchor.ticks * timescale) {
7745
- catalogError("track_switching_set", `$.tracks[${index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
8046
+ const framerate = track["framerate"];
8047
+ const intraOnly = positiveNumber(framerate) && Math.abs(Number(ticks) * framerate - Number(timescale)) <= Number(timescale) * 1e-3;
8048
+ const members = switchingSets.get(altGroup) ?? [];
8049
+ members.push({ index, name: track["name"], ticks, timescale, intraOnly });
8050
+ switchingSets.set(altGroup, members);
8051
+ }
8052
+ for (const [altGroup, members] of switchingSets) {
8053
+ const anchor = members.find((member) => !member.intraOnly) ?? members[0];
8054
+ for (const member of members) {
8055
+ if (member === anchor || member.ticks * anchor.timescale === anchor.ticks * member.timescale) continue;
8056
+ const nests = member.intraOnly && !anchor.intraOnly && anchor.ticks * member.timescale % (member.ticks * anchor.timescale) === 0n;
8057
+ if (!nests) {
8058
+ catalogError("track_switching_set", `$.tracks[${member.index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
8059
+ }
7746
8060
  }
7747
- if (!anchor) switchingSets.set(altGroup, { name: track["name"], ticks, timescale });
7748
8061
  }
7749
8062
  const multicast = catalog["multicast"];
7750
8063
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
@@ -7792,15 +8105,8 @@ var BlockcastMmt = (() => {
7792
8105
  }
7793
8106
  }
7794
8107
  }
7795
- try {
7796
- resolveMulticastAuthCatalog(catalog);
7797
- } catch (error) {
7798
- catalogError(
7799
- "multicast_auth",
7800
- "$.multicast.auth",
7801
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
7802
- );
7803
- }
8108
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
8109
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
7804
8110
  validateArchive(catalog);
7805
8111
  return catalog;
7806
8112
  }
@@ -7810,14 +8116,42 @@ var BlockcastMmt = (() => {
7810
8116
  const ms = fec?.interleaveDepthMs;
7811
8117
  return typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0 ? ms : void 0;
7812
8118
  }
7813
- function computeFecTimeout(interleaveDepthMs, safetyFactor = 3) {
7814
- if (!Number.isFinite(interleaveDepthMs) || interleaveDepthMs <= 0) {
8119
+ function fecBlockDeadlineMs(params) {
8120
+ const { firstAcceptedAtMs, interleaveDepthMs, reorderToleranceMs } = params;
8121
+ if (!Number.isFinite(firstAcceptedAtMs)) {
8122
+ throw new Error(`[FEC] firstAcceptedAtMs must be finite (got ${firstAcceptedAtMs}).`);
8123
+ }
8124
+ return firstAcceptedAtMs + fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs);
8125
+ }
8126
+ function fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs) {
8127
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0)) {
7815
8128
  throw new Error(`[FEC] interleaveDepthMs must be a finite value > 0 (got ${interleaveDepthMs}ms). Fix encoder config.`);
7816
8129
  }
7817
- if (!Number.isFinite(safetyFactor) || safetyFactor <= 0) {
7818
- throw new Error(`[FEC] safetyFactor must be a finite value > 0 (got ${safetyFactor}). Fix encoder config.`);
8130
+ if (!(reorderToleranceMs >= 0) || !Number.isFinite(reorderToleranceMs)) {
8131
+ throw new Error(`[FEC] reorderToleranceMs must be a finite value >= 0 (got ${reorderToleranceMs}ms). It is a catalog value (fec.reorderToleranceMs), not a local default.`);
7819
8132
  }
7820
- return Math.ceil(interleaveDepthMs * safetyFactor);
8133
+ return Math.ceil(interleaveDepthMs + reorderToleranceMs);
8134
+ }
8135
+ function deriveFecRetentionBlocks(deliveryWindowMs, interleaveDepthMs) {
8136
+ const blocks = tryDeriveFecRetentionBlocks(deliveryWindowMs, interleaveDepthMs);
8137
+ if (blocks !== void 0)
8138
+ return blocks;
8139
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0)) {
8140
+ throw new Error(`[FEC] interleaveDepthMs must be a finite value > 0 (got ${interleaveDepthMs}ms). Fix encoder config.`);
8141
+ }
8142
+ if (!Number.isFinite(deliveryWindowMs) || !(deliveryWindowMs > 0)) {
8143
+ throw new Error(`[FEC] deliveryWindowMs must be a finite value > 0 (got ${deliveryWindowMs}ms). It is derived from catalog geometry, not a local default.`);
8144
+ }
8145
+ throw new Error(`[FEC] retention of ${Math.ceil(deliveryWindowMs / interleaveDepthMs) + 1} blocks exceeds the 255 the decoder and the ISO/IEC 23008-1 AL-FEC signaling byte accept (deliveryWindowMs=${deliveryWindowMs}ms over interleaveDepthMs=${interleaveDepthMs}ms). Fix the catalog geometry: a span this short cannot carry a window this wide.`);
8146
+ }
8147
+ var MAX_FEC_RETENTION_BLOCKS = 255;
8148
+ function tryDeriveFecRetentionBlocks(deliveryWindowMs, interleaveDepthMs) {
8149
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0))
8150
+ return void 0;
8151
+ if (!Number.isFinite(deliveryWindowMs) || !(deliveryWindowMs > 0))
8152
+ return void 0;
8153
+ const blocks = Math.ceil(deliveryWindowMs / interleaveDepthMs) + 1;
8154
+ return blocks > MAX_FEC_RETENTION_BLOCKS ? void 0 : blocks;
7821
8155
  }
7822
8156
 
7823
8157
  // ../fec/dist/repair-group.js
@@ -7838,22 +8172,16 @@ var BlockcastMmt = (() => {
7838
8172
  "reliable-moq": Object.freeze({ state: "inactive", reason: "reliable-moq" }),
7839
8173
  "no-multicast-bridge": Object.freeze({ state: "inactive", reason: "no-multicast-bridge" })
7840
8174
  });
7841
- function recordOf(value) {
8175
+ function recordOf2(value) {
7842
8176
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7843
8177
  }
7844
- function isPositiveSafeInteger(value) {
8178
+ function isPositiveSafeInteger2(value) {
7845
8179
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
7846
8180
  }
7847
8181
  function catalogDeclaresFec(fec) {
7848
- const block = recordOf(fec);
7849
- if (block === void 0 || block["algorithm"] === "none") return false;
7850
- return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
7851
- }
7852
- function isoBlockSpanUsable(fec) {
7853
- const block = recordOf(fec);
7854
- if (block === void 0 || block["blockProfile"] !== "iso-ssbg1-v1") return true;
7855
- const ms = block["interleaveDepthMs"];
7856
- return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
8182
+ const block = recordOf2(fec);
8183
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
8184
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
7857
8185
  }
7858
8186
  function requireBoolean(value, field) {
7859
8187
  if (typeof value !== "boolean") {
@@ -7869,7 +8197,7 @@ var BlockcastMmt = (() => {
7869
8197
  if (typeof transportPolicy !== "string" || !TRANSPORT_POLICIES.has(transportPolicy)) {
7870
8198
  throw new TypeError(`resolveFecState: unsupported transportPolicy ${JSON.stringify(transportPolicy)}`);
7871
8199
  }
7872
- if (stats !== null && stats !== void 0 && recordOf(stats) === void 0) {
8200
+ if (stats !== null && stats !== void 0 && recordOf2(stats) === void 0) {
7873
8201
  throw new TypeError("resolveFecState: stats must be a plain object, null or undefined");
7874
8202
  }
7875
8203
  if (!catalogFec) return INACTIVE["no-catalog-fec"];
@@ -7881,6 +8209,395 @@ var BlockcastMmt = (() => {
7881
8209
  return INACTIVE["reliable-moq"];
7882
8210
  }
7883
8211
 
8212
+ // src/mmtp-fec-session.ts
8213
+ var PATH_BITS = { moq: 1, multicast: 2 };
8214
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8215
+ var _decoder, _blocks, _settled, _have, _newest, _prunedAt, _repairPacketId, _stats3, _MmtpFecSession_instances, drop_fn2, noteNewest_fn, blockStartOf_fn, countHeld_fn, noteMixed_fn, behindHorizon_fn, settle_fn, settleClean_fn, settleDecoded_fn, retireBehindHorizon_fn;
8216
+ var MmtpFecSession = class {
8217
+ /**
8218
+ * @throws when the catalog block lacks or misstates a field the session
8219
+ * needs: the block profile, K, T, `interleaveDepthMs` or
8220
+ * `reorderToleranceMs`. None is defaulted.
8221
+ */
8222
+ constructor(config) {
8223
+ __privateAdd(this, _MmtpFecSession_instances);
8224
+ __privateAdd(this, _decoder);
8225
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
8226
+ __privateAdd(this, _blocks, /* @__PURE__ */ new Map());
8227
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
8228
+ __privateAdd(this, _settled, /* @__PURE__ */ new Set());
8229
+ /**
8230
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
8231
+ * received on, or 0 for one the session recovered.
8232
+ */
8233
+ __privateAdd(this, _have, /* @__PURE__ */ new Map());
8234
+ __privateAdd(this, _newest);
8235
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
8236
+ __privateAdd(this, _prunedAt);
8237
+ __privateAdd(this, _repairPacketId);
8238
+ __privateAdd(this, _stats3, {
8239
+ sourceSymbols: 0,
8240
+ repairSymbols: 0,
8241
+ blocksClean: 0,
8242
+ blocksRecovered: 0,
8243
+ blocksFailed: 0,
8244
+ blocksReleased: 0,
8245
+ packetsRecovered: 0,
8246
+ packetsLost: 0,
8247
+ dropped: {},
8248
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
8249
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
8250
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
8251
+ });
8252
+ const fec = config?.fec;
8253
+ if (!fec || typeof fec !== "object") {
8254
+ throw new Error("MmtpFecSession: the catalog fec block is required");
8255
+ }
8256
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
8257
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
8258
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
8259
+ }
8260
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
8261
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8262
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8263
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8264
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
8265
+ this.retentionBlocks = deriveFecRetentionBlocks(
8266
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
8267
+ interleaveDepthMs
8268
+ );
8269
+ if (typeof config.Decoder !== "function") {
8270
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8271
+ }
8272
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
8273
+ try {
8274
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
8275
+ } catch (error) {
8276
+ decoder.free();
8277
+ throw error;
8278
+ }
8279
+ __privateSet(this, _decoder, decoder);
8280
+ }
8281
+ /** True once release() ran. */
8282
+ get released() {
8283
+ return __privateGet(this, _decoder) === null;
8284
+ }
8285
+ get stats() {
8286
+ return {
8287
+ ...__privateGet(this, _stats3),
8288
+ dropped: { ...__privateGet(this, _stats3).dropped },
8289
+ sourceSymbolsByPath: { ...__privateGet(this, _stats3).sourceSymbolsByPath },
8290
+ repairSymbolsByPath: { ...__privateGet(this, _stats3).repairSymbolsByPath },
8291
+ mixedPath: { ...__privateGet(this, _stats3).mixedPath }
8292
+ };
8293
+ }
8294
+ /**
8295
+ * Feeds one received source packet: the MMTP packet without its four-byte
8296
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
8297
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
8298
+ * was received; a caller that only subscribes over MoQT can leave it out.
8299
+ *
8300
+ * @returns the protected packets of this packet's block that it recovered,
8301
+ * in SS_ID order, for the caller to feed to its parser with
8302
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
8303
+ */
8304
+ addSource(ssId, packet, path = "moq") {
8305
+ const decoder = __privateGet(this, _decoder);
8306
+ if (!decoder) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:released");
8307
+ const pathBit = PATH_BITS[path];
8308
+ if (!pathBit) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:unknown-path");
8309
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:bad-ss-id");
8310
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:exceeds-symbol");
8311
+ if (__privateGet(this, _have).has(ssId)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:duplicate");
8312
+ __privateGet(this, _have).set(ssId, pathBit);
8313
+ __privateGet(this, _stats3).sourceSymbols++;
8314
+ __privateGet(this, _stats3).sourceSymbolsByPath[path]++;
8315
+ __privateMethod(this, _MmtpFecSession_instances, noteNewest_fn).call(this, ssId);
8316
+ const start = __privateMethod(this, _MmtpFecSession_instances, blockStartOf_fn).call(this, ssId);
8317
+ const block = start === void 0 ? void 0 : __privateGet(this, _blocks).get(start);
8318
+ if (block) {
8319
+ block.received++;
8320
+ block.paths |= pathBit;
8321
+ }
8322
+ let output;
8323
+ try {
8324
+ output = decoder.add_source(ssId, packet, 0);
8325
+ } catch {
8326
+ __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:decoder-refused");
8327
+ output = void 0;
8328
+ }
8329
+ const recovered = [];
8330
+ if (start !== void 0 && block) {
8331
+ if (output) {
8332
+ recovered.push(...__privateMethod(this, _MmtpFecSession_instances, settleDecoded_fn).call(this, start, block, output));
8333
+ } else if (block.received >= block.ssbLength) {
8334
+ __privateMethod(this, _MmtpFecSession_instances, settleClean_fn).call(this, start);
8335
+ }
8336
+ }
8337
+ __privateMethod(this, _MmtpFecSession_instances, retireBehindHorizon_fn).call(this);
8338
+ return recovered;
8339
+ }
8340
+ /**
8341
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
8342
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
8343
+ * repair packet fixes its packet ID and a packet of any other is refused.
8344
+ * `path` is where it was received, as for addSource().
8345
+ *
8346
+ * @returns the protected packets this repair symbol recovered, as for
8347
+ * addSource().
8348
+ */
8349
+ addRepair(packet, path = "moq") {
8350
+ const decoder = __privateGet(this, _decoder);
8351
+ if (!decoder) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:released");
8352
+ const pathBit = PATH_BITS[path];
8353
+ if (!pathBit) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:unknown-path");
8354
+ let header;
8355
+ try {
8356
+ header = parseMMTPHeader(packet);
8357
+ } catch {
8358
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:malformed");
8359
+ }
8360
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
8361
+ if (!frame) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:malformed");
8362
+ if (__privateGet(this, _repairPacketId) === void 0) {
8363
+ __privateSet(this, _repairPacketId, frame.packetId);
8364
+ } else if (frame.packetId !== __privateGet(this, _repairPacketId)) {
8365
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:foreign-packet-id");
8366
+ }
8367
+ if (frame.symbolData.byteLength !== this.symbolSize) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:symbol-size");
8368
+ if (frame.ssbLength > this.sourceSymbols) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:ssb-length");
8369
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
8370
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:rs-block-length");
8371
+ }
8372
+ const start = frame.ssStart;
8373
+ let block = __privateGet(this, _blocks).get(start);
8374
+ if (block && block.ssbLength !== frame.ssbLength) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:conflicting-ssb-length");
8375
+ if (block?.rsIds.has(frame.rsId)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:duplicate");
8376
+ if (!block) {
8377
+ if (__privateGet(this, _settled).has(start)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:block-settled");
8378
+ if (__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, start)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:behind-horizon");
8379
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
8380
+ __privateMethod(this, _MmtpFecSession_instances, countHeld_fn).call(this, start, block);
8381
+ __privateGet(this, _blocks).set(start, block);
8382
+ }
8383
+ __privateMethod(this, _MmtpFecSession_instances, noteNewest_fn).call(this, serial32Add(start, frame.ssbLength - 1));
8384
+ if (block.received >= block.ssbLength) {
8385
+ __privateMethod(this, _MmtpFecSession_instances, settleClean_fn).call(this, start);
8386
+ __privateMethod(this, _MmtpFecSession_instances, retireBehindHorizon_fn).call(this);
8387
+ return [];
8388
+ }
8389
+ let output;
8390
+ try {
8391
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
8392
+ } catch {
8393
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:decoder-refused");
8394
+ }
8395
+ block.rsIds.add(frame.rsId);
8396
+ __privateGet(this, _stats3).repairSymbols++;
8397
+ __privateGet(this, _stats3).repairSymbolsByPath[path]++;
8398
+ block.paths |= pathBit;
8399
+ const recovered = output ? __privateMethod(this, _MmtpFecSession_instances, settleDecoded_fn).call(this, start, block, output) : [];
8400
+ __privateMethod(this, _MmtpFecSession_instances, retireBehindHorizon_fn).call(this);
8401
+ return recovered;
8402
+ }
8403
+ /**
8404
+ * Frees the decoder and every block. Blocks still unsettled are counted as
8405
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
8406
+ * returns whether this call released anything.
8407
+ */
8408
+ release() {
8409
+ const decoder = __privateGet(this, _decoder);
8410
+ if (!decoder) return false;
8411
+ __privateSet(this, _decoder, null);
8412
+ __privateGet(this, _stats3).blocksReleased += __privateGet(this, _blocks).size;
8413
+ for (const block of __privateGet(this, _blocks).values()) __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "released");
8414
+ __privateGet(this, _blocks).clear();
8415
+ __privateGet(this, _settled).clear();
8416
+ __privateGet(this, _have).clear();
8417
+ decoder.free();
8418
+ return true;
8419
+ }
8420
+ };
8421
+ _decoder = new WeakMap();
8422
+ _blocks = new WeakMap();
8423
+ _settled = new WeakMap();
8424
+ _have = new WeakMap();
8425
+ _newest = new WeakMap();
8426
+ _prunedAt = new WeakMap();
8427
+ _repairPacketId = new WeakMap();
8428
+ _stats3 = new WeakMap();
8429
+ _MmtpFecSession_instances = new WeakSet();
8430
+ drop_fn2 = function(reason) {
8431
+ __privateGet(this, _stats3).dropped[reason] = (__privateGet(this, _stats3).dropped[reason] ?? 0) + 1;
8432
+ return [];
8433
+ };
8434
+ noteNewest_fn = function(ssId) {
8435
+ if (__privateGet(this, _newest) === void 0 || serial32Precedes(__privateGet(this, _newest), ssId)) __privateSet(this, _newest, ssId);
8436
+ };
8437
+ blockStartOf_fn = function(ssId) {
8438
+ for (const [start, block] of __privateGet(this, _blocks)) {
8439
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
8440
+ }
8441
+ return void 0;
8442
+ };
8443
+ /** Counts the sources of a new block the parser already has, and their paths. */
8444
+ countHeld_fn = function(start, block) {
8445
+ for (let i = 0; i < block.ssbLength; i++) {
8446
+ const pathBit = __privateGet(this, _have).get(serial32Add(start, i));
8447
+ if (pathBit === void 0) continue;
8448
+ block.received++;
8449
+ block.paths |= pathBit;
8450
+ }
8451
+ };
8452
+ noteMixed_fn = function(block, outcome) {
8453
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) __privateGet(this, _stats3).mixedPath[outcome]++;
8454
+ };
8455
+ /** The decoder's own rule: more than its retention behind, counted from below. */
8456
+ behindHorizon_fn = function(start) {
8457
+ const newest = __privateGet(this, _newest);
8458
+ if (newest === void 0) return false;
8459
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
8460
+ };
8461
+ settle_fn = function(start) {
8462
+ __privateGet(this, _blocks).delete(start);
8463
+ __privateGet(this, _settled).add(start);
8464
+ };
8465
+ settleClean_fn = function(start) {
8466
+ const block = __privateGet(this, _blocks).get(start);
8467
+ if (!block) return;
8468
+ __privateMethod(this, _MmtpFecSession_instances, settle_fn).call(this, start);
8469
+ __privateGet(this, _stats3).blocksClean++;
8470
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "clean");
8471
+ try {
8472
+ __privateGet(this, _decoder)?.cleanup_blocks_detailed(Uint32Array.of(start));
8473
+ } catch {
8474
+ }
8475
+ };
8476
+ /**
8477
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
8478
+ * concatenated: split by T, trim by each symbol's length field, and hand
8479
+ * back the packets the parser does not have yet.
8480
+ */
8481
+ settleDecoded_fn = function(start, block, output) {
8482
+ __privateMethod(this, _MmtpFecSession_instances, settle_fn).call(this, start);
8483
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
8484
+ __privateGet(this, _stats3).blocksFailed++;
8485
+ __privateGet(this, _stats3).packetsLost += block.ssbLength - block.received;
8486
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "failed");
8487
+ __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "block:decoded-length");
8488
+ return [];
8489
+ }
8490
+ const recovered = [];
8491
+ let refused = 0;
8492
+ for (let i = 0; i < block.ssbLength; i++) {
8493
+ const ssId = serial32Add(start, i);
8494
+ if (__privateGet(this, _have).has(ssId)) continue;
8495
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
8496
+ const packet = trimSsbg1SourceSymbol(symbol);
8497
+ if (!packet) {
8498
+ refused++;
8499
+ continue;
8500
+ }
8501
+ __privateGet(this, _have).set(ssId, 0);
8502
+ recovered.push(packet.slice());
8503
+ }
8504
+ if (refused > 0) {
8505
+ __privateGet(this, _stats3).blocksFailed++;
8506
+ __privateGet(this, _stats3).packetsLost += refused;
8507
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "failed");
8508
+ __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "block:bad-ssbg1-symbol");
8509
+ } else if (recovered.length === 0) {
8510
+ __privateGet(this, _stats3).blocksClean++;
8511
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "clean");
8512
+ } else {
8513
+ __privateGet(this, _stats3).blocksRecovered++;
8514
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "recovered");
8515
+ }
8516
+ __privateGet(this, _stats3).packetsRecovered += recovered.length;
8517
+ return recovered;
8518
+ };
8519
+ /**
8520
+ * Retires every block, and every SS_ID the session remembers, that the
8521
+ * newest SS_ID has moved past the retention. An unsettled block retired
8522
+ * here is a failure: more of its sources were lost than its repair could
8523
+ * restore, or its repair never arrived.
8524
+ */
8525
+ retireBehindHorizon_fn = function() {
8526
+ const decoder = __privateGet(this, _decoder);
8527
+ const newest = __privateGet(this, _newest);
8528
+ if (!decoder || newest === void 0) return;
8529
+ try {
8530
+ decoder.cleanup_by_ss_start(newest);
8531
+ } catch {
8532
+ }
8533
+ for (const [start, block] of __privateGet(this, _blocks)) {
8534
+ if (!__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, start)) continue;
8535
+ __privateMethod(this, _MmtpFecSession_instances, settle_fn).call(this, start);
8536
+ __privateGet(this, _stats3).blocksFailed++;
8537
+ __privateGet(this, _stats3).packetsLost += block.ssbLength - block.received;
8538
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "failed");
8539
+ }
8540
+ const prunedAt = __privateGet(this, _prunedAt);
8541
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
8542
+ __privateSet(this, _prunedAt, newest);
8543
+ for (const ssId of __privateGet(this, _have).keys()) {
8544
+ if (__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, ssId)) __privateGet(this, _have).delete(ssId);
8545
+ }
8546
+ for (const start of __privateGet(this, _settled)) {
8547
+ if (__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, start)) __privateGet(this, _settled).delete(start);
8548
+ }
8549
+ };
8550
+ function requirePositiveInteger(value, path) {
8551
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
8552
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
8553
+ }
8554
+ return value;
8555
+ }
8556
+ function requireNumber(value, path) {
8557
+ if (typeof value !== "number") {
8558
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
8559
+ }
8560
+ return value;
8561
+ }
8562
+
8563
+ // src/catalog-network-source.ts
8564
+ function normalizePort(value) {
8565
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
8566
+ return Number.isInteger(n) && n > 0 && n <= 65535 ? n : void 0;
8567
+ }
8568
+ function catalogAmtNetworkSource(networkSource) {
8569
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8570
+ for (const raw of entries) {
8571
+ if (!raw || typeof raw !== "object") continue;
8572
+ const ns = raw;
8573
+ if (ns.type !== "amt") continue;
8574
+ if (ns.discovery === "driad") continue;
8575
+ const relay = typeof ns.relay === "string" ? ns.relay.trim() : "";
8576
+ if (!relay) continue;
8577
+ return { relay, port: normalizePort(ns.port) ?? DEFAULT_AMT_RELAY_PORT };
8578
+ }
8579
+ return void 0;
8580
+ }
8581
+ function intIn(value, min, max) {
8582
+ return Number.isInteger(value) && value >= min && value <= max;
8583
+ }
8584
+ function catalogAtsc3NetworkSource(networkSource) {
8585
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8586
+ for (const raw of entries) {
8587
+ if (!raw || typeof raw !== "object") continue;
8588
+ const ns = raw;
8589
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
8590
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
8591
+ return {
8592
+ frequency: ns.frequency,
8593
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
8594
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
8595
+ ...slsUri ? { slsUri } : {}
8596
+ };
8597
+ }
8598
+ return void 0;
8599
+ }
8600
+
7884
8601
  // src/mmtp-to-cmaf.ts
7885
8602
  function box(type, ...children2) {
7886
8603
  let size = 8;
@@ -7923,8 +8640,8 @@ var BlockcastMmt = (() => {
7923
8640
  }
7924
8641
  var KEYFRAME_FLAGS = 33554432;
7925
8642
  var DELTA_FLAGS = 16842752;
7926
- var UINT32_MAX = 4294967295;
7927
- var MAX_TRACK_ID = UINT32_MAX - 1;
8643
+ var UINT32_MAX2 = 4294967295;
8644
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
7928
8645
  var INT32_MIN = -2147483648;
7929
8646
  var INT32_MAX = 2147483647;
7930
8647
  function assertTrackId(trackId, label) {
@@ -7933,8 +8650,8 @@ var BlockcastMmt = (() => {
7933
8650
  }
7934
8651
  }
7935
8652
  function assertTimescale(timescale, label) {
7936
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
7937
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
8653
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
8654
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
7938
8655
  }
7939
8656
  }
7940
8657
  function assertCompositionTimeOffsets(samples) {
@@ -8998,7 +9715,7 @@ var BlockcastMmt = (() => {
8998
9715
  var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
8999
9716
  var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
9000
9717
  var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
9001
- var SOURCE_AUTH_SCOPE_LENGTH2 = 32;
9718
+ var SOURCE_AUTH_SCOPE_LENGTH = 32;
9002
9719
  var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
9003
9720
  function requireBytes(name, value, length) {
9004
9721
  if (value.byteLength !== length) {
@@ -9075,7 +9792,7 @@ var BlockcastMmt = (() => {
9075
9792
  throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
9076
9793
  }
9077
9794
  requireU64("groupId", groupId);
9078
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH2);
9795
+ requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
9079
9796
  requireBytes("root", root, 32);
9080
9797
  const preimage = new Uint8Array(100);
9081
9798
  const view2 = new DataView(preimage.buffer);
@@ -9126,6 +9843,20 @@ var BlockcastMmt = (() => {
9126
9843
  }
9127
9844
 
9128
9845
  // ../mmt-manifest-verify/dist/verifier.js
9846
+ function manifestKeyFor(keys, epoch, kid) {
9847
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length)
9848
+ return void 0;
9849
+ if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
9850
+ return void 0;
9851
+ let signer;
9852
+ for (const key of keys) {
9853
+ if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
9854
+ signer = key;
9855
+ }
9856
+ if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
9857
+ return void 0;
9858
+ return signer.publicKey;
9859
+ }
9129
9860
  function manifestBindingId(trackName, sourceSymbolFormat) {
9130
9861
  return JSON.stringify([trackName, sourceSymbolFormat]);
9131
9862
  }
@@ -9154,7 +9885,7 @@ var BlockcastMmt = (() => {
9154
9885
  return diff === 0;
9155
9886
  };
9156
9887
  var isPromiseLike = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
9157
- var _config, _verifySignature, _onFailure, _tracks2, _stats3, _disposed2, _ManifestVerifier_instances, requireTrack_fn, group_fn, validateIdentity_fn, admitAgainstEntry_fn, rejectOrShadow_fn, resolvePending_fn, closeGroup_fn, finishGroupSignature_fn, verifyAcceptedSignature_fn, failGroup_fn, removePending_fn, quarantine_fn, enforceCap_fn, giveUpOnPending_fn, failOpenTrack_fn, failOpenGroup_fn, releaseAllQuarantine_fn, failure_fn;
9888
+ var _config, _verifySignature, _onFailure, _tracks2, _stats4, _disposed2, _ManifestVerifier_instances, requireTrack_fn, group_fn, validateIdentity_fn, admitAgainstEntry_fn, rejectOrShadow_fn, resolvePending_fn, closeGroup_fn, finishGroupSignature_fn, verifyAcceptedSignature_fn, failGroup_fn, removePending_fn, quarantine_fn, enforceCap_fn, giveUpOnPending_fn, failOpenTrack_fn, failOpenGroup_fn, releaseAllQuarantine_fn, failure_fn;
9158
9889
  var ManifestVerifier = class {
9159
9890
  constructor(options) {
9160
9891
  __privateAdd(this, _ManifestVerifier_instances);
@@ -9162,7 +9893,7 @@ var BlockcastMmt = (() => {
9162
9893
  __privateAdd(this, _verifySignature);
9163
9894
  __privateAdd(this, _onFailure);
9164
9895
  __privateAdd(this, _tracks2, /* @__PURE__ */ new Map());
9165
- __privateAdd(this, _stats3, {
9896
+ __privateAdd(this, _stats4, {
9166
9897
  verified: 0,
9167
9898
  failures: Object.fromEntries(FAILURE_REASONS.map((reason) => [reason, 0])),
9168
9899
  quarantinedBytes: 0
@@ -9180,10 +9911,10 @@ var BlockcastMmt = (() => {
9180
9911
  for (const track of __privateGet(this, _tracks2).values())
9181
9912
  quarantined += track.quarantine.length;
9182
9913
  return {
9183
- verified: __privateGet(this, _stats3).verified,
9184
- failures: { ...__privateGet(this, _stats3).failures },
9914
+ verified: __privateGet(this, _stats4).verified,
9915
+ failures: { ...__privateGet(this, _stats4).failures },
9185
9916
  quarantined,
9186
- quarantinedBytes: __privateGet(this, _stats3).quarantinedBytes
9917
+ quarantinedBytes: __privateGet(this, _stats4).quarantinedBytes
9187
9918
  };
9188
9919
  }
9189
9920
  setMode(mode) {
@@ -9204,11 +9935,12 @@ var BlockcastMmt = (() => {
9204
9935
  }
9205
9936
  if (context.authScope.byteLength !== 32)
9206
9937
  throw new Error("manifest authScope must be 32 bytes");
9207
- if (context.publicKey.byteLength !== 32)
9208
- throw new Error("manifest publicKey must be 32 bytes");
9209
- for (const key of context.acceptedPublicKeys ?? []) {
9210
- if (key.byteLength !== 32)
9211
- throw new Error("manifest acceptedPublicKeys must contain 32-byte keys");
9938
+ for (const key of context.keys) {
9939
+ if (key.publicKey.byteLength !== 32)
9940
+ throw new Error("manifest keys must carry 32-byte public keys");
9941
+ }
9942
+ if (manifestKeyFor(context.keys, context.keyEpoch) === void 0) {
9943
+ throw new Error(`manifest keys hold no key set signing keyEpoch ${context.keyEpoch}`);
9212
9944
  }
9213
9945
  for (const [name, value] of Object.entries({
9214
9946
  broadcastNamespaceId: context.broadcastNamespaceId,
@@ -9318,7 +10050,7 @@ var BlockcastMmt = (() => {
9318
10050
  _verifySignature = new WeakMap();
9319
10051
  _onFailure = new WeakMap();
9320
10052
  _tracks2 = new WeakMap();
9321
- _stats3 = new WeakMap();
10053
+ _stats4 = new WeakMap();
9322
10054
  _disposed2 = new WeakMap();
9323
10055
  _ManifestVerifier_instances = new WeakSet();
9324
10056
  requireTrack_fn = function(bindingId) {
@@ -9370,7 +10102,7 @@ var BlockcastMmt = (() => {
9370
10102
  return { action: "stall", verified: false };
9371
10103
  }
9372
10104
  release();
9373
- __privateGet(this, _stats3).verified++;
10105
+ __privateGet(this, _stats4).verified++;
9374
10106
  return { action: "play", verified: true };
9375
10107
  };
9376
10108
  rejectOrShadow_fn = function(identity, release, reason) {
@@ -9461,7 +10193,7 @@ var BlockcastMmt = (() => {
9461
10193
  }
9462
10194
  };
9463
10195
  verifyAcceptedSignature_fn = function(track, message, signature) {
9464
- const keys = track.context.acceptedPublicKeys ?? [track.context.publicKey];
10196
+ const keys = [manifestKeyFor(track.context.keys, track.context.keyEpoch)];
9465
10197
  const pending = [];
9466
10198
  let hadSynchronousError = false;
9467
10199
  for (const key of keys) {
@@ -9510,7 +10242,7 @@ var BlockcastMmt = (() => {
9510
10242
  if (index >= 0)
9511
10243
  track.quarantine.splice(index, 1);
9512
10244
  track.quarantinedBytes -= pending.bytes;
9513
- __privateGet(this, _stats3).quarantinedBytes -= pending.bytes;
10245
+ __privateGet(this, _stats4).quarantinedBytes -= pending.bytes;
9514
10246
  };
9515
10247
  quarantine_fn = function(track, group, pending) {
9516
10248
  if (group.pending.has(pending.identity.objectId))
@@ -9518,7 +10250,7 @@ var BlockcastMmt = (() => {
9518
10250
  group.pending.set(pending.identity.objectId, pending);
9519
10251
  track.quarantine.push(pending);
9520
10252
  track.quarantinedBytes += pending.bytes;
9521
- __privateGet(this, _stats3).quarantinedBytes += pending.bytes;
10253
+ __privateGet(this, _stats4).quarantinedBytes += pending.bytes;
9522
10254
  __privateMethod(this, _ManifestVerifier_instances, enforceCap_fn).call(this, track);
9523
10255
  return true;
9524
10256
  };
@@ -9529,7 +10261,7 @@ var BlockcastMmt = (() => {
9529
10261
  if (group)
9530
10262
  group.pending.delete(pending.identity.objectId);
9531
10263
  track.quarantinedBytes -= pending.bytes;
9532
- __privateGet(this, _stats3).quarantinedBytes -= pending.bytes;
10264
+ __privateGet(this, _stats4).quarantinedBytes -= pending.bytes;
9533
10265
  __privateMethod(this, _ManifestVerifier_instances, giveUpOnPending_fn).call(this, pending);
9534
10266
  __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
9535
10267
  console.warn(`[ManifestVerifier] quarantine cap eviction track=${pending.identity.trackName} group=${pending.identity.groupId} object=${pending.identity.objectId} disposition=${__privateGet(this, _config).mode === "enforce" ? "drop" : "fail-open"}`);
@@ -9586,7 +10318,7 @@ var BlockcastMmt = (() => {
9586
10318
  };
9587
10319
  failure_fn = function(identity, reason) {
9588
10320
  var _a;
9589
- __privateGet(this, _stats3).failures[reason]++;
10321
+ __privateGet(this, _stats4).failures[reason]++;
9590
10322
  (_a = __privateGet(this, _onFailure)) == null ? void 0 : _a.call(this, {
9591
10323
  trackName: identity.trackName,
9592
10324
  ...identity.bindingId === void 0 ? {} : { bindingId: identity.bindingId },
@@ -9596,59 +10328,140 @@ var BlockcastMmt = (() => {
9596
10328
  });
9597
10329
  };
9598
10330
 
9599
- // src/manifest-auth-plan.ts
9600
- function createManifestAuthPlan(catalog, options) {
9601
- const resolved = resolveMulticastAuthCatalog(catalog, options.playerMode);
9602
- if (!resolved || resolved.mode === "off") return void 0;
9603
- const verifier = new ManifestVerifier({
9604
- manifestAuth: {
9605
- mode: resolved.mode,
9606
- onMissingManifest: options.onMissingManifest ?? (resolved.mode === "enforce" ? "stall" : "fallback-shadow")
9607
- },
9608
- verifySignature: options.verifySignature,
9609
- ...options.onFailure === void 0 ? {} : { onFailure: options.onFailure }
9610
- });
9611
- const byManifestTrack = /* @__PURE__ */ new Map();
9612
- const bindings = resolved.tracks.map((binding) => {
9613
- const bindingId = manifestBindingId(binding.mediaTrack, binding.sourceSymbolFormat);
9614
- const planned = {
9615
- bindingId,
9616
- mediaTrack: binding.mediaTrack,
9617
- manifestTrack: binding.manifestTrack,
9618
- sourceSymbolFormat: binding.sourceSymbolFormat
9619
- };
9620
- verifier.registerTrack({
9621
- ...options.contextFor(binding, resolved),
9622
- bindingId,
9623
- trackName: binding.mediaTrack,
9624
- sourceSymbolFormat: binding.sourceSymbolFormat,
9625
- authScope: binding.authScope,
9626
- publicKey: resolved.acceptedPublicKeys[0],
9627
- acceptedPublicKeys: resolved.acceptedPublicKeys
10331
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10332
+ var BCPV2_HEADER_LENGTH = 68;
10333
+ var BCPV2_SIGNATURE_LENGTH = 64;
10334
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10335
+ var text = new TextEncoder();
10336
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10337
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10338
+
10339
+ // src/multicast-auth-catalog.ts
10340
+ var RAW_ED25519_KEY_LENGTH = 32;
10341
+ var DEFAULT_MAX_AUTH_DELAY_MS = 200;
10342
+ var DEFAULT_MANIFEST_TIMER_MS = 20;
10343
+ var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10344
+ function encodeBase64Url(bytes) {
10345
+ let output = "";
10346
+ for (let i = 0; i < bytes.length; i += 3) {
10347
+ const b0 = bytes[i];
10348
+ const b1 = bytes[i + 1];
10349
+ const b2 = bytes[i + 2];
10350
+ output += BASE64URL_ALPHABET[b0 >> 2];
10351
+ output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
10352
+ if (b1 === void 0) break;
10353
+ output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
10354
+ if (b2 === void 0) break;
10355
+ output += BASE64URL_ALPHABET[b2 & 63];
10356
+ }
10357
+ return output;
10358
+ }
10359
+ var BASE64URL_DECODE_TABLE = (() => {
10360
+ const table = new Int8Array(128).fill(-1);
10361
+ for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
10362
+ table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
10363
+ }
10364
+ return table;
10365
+ })();
10366
+ function decodeBase64Url(text2) {
10367
+ if (text2.length % 4 === 1) {
10368
+ throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
10369
+ }
10370
+ const bytes = [];
10371
+ let buffer = 0;
10372
+ let bits = 0;
10373
+ for (let i = 0; i < text2.length; i++) {
10374
+ const code = text2.charCodeAt(i);
10375
+ const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
10376
+ if (value === void 0 || value < 0) {
10377
+ throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
10378
+ }
10379
+ buffer = buffer << 6 | value;
10380
+ bits += 6;
10381
+ if (bits >= 8) {
10382
+ bits -= 8;
10383
+ bytes.push(buffer >> bits & 255);
10384
+ }
10385
+ }
10386
+ const decoded = Uint8Array.from(bytes);
10387
+ if (encodeBase64Url(decoded) !== text2) {
10388
+ throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
10389
+ }
10390
+ return decoded;
10391
+ }
10392
+ function decodeEd25519PublicKey(publicKey) {
10393
+ const bytes = decodeBase64Url(publicKey);
10394
+ if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
10395
+ throw new Error(
10396
+ `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
10397
+ );
10398
+ }
10399
+ return bytes;
10400
+ }
10401
+ function resolveMulticastAuthCatalog(catalog, options = {}) {
10402
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
10403
+ throw new Error("[multicast-auth-catalog] catalog must be an object");
10404
+ }
10405
+ const issues = multicastCatalogIssues(catalog, options);
10406
+ const fatal = issues.find((issue) => issue.endpointIndex === void 0);
10407
+ if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
10408
+ const multicast = catalog["multicast"];
10409
+ const auth = multicast?.["auth"];
10410
+ if (auth === void 0) {
10411
+ if (options.requireAuth) {
10412
+ throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
10413
+ }
10414
+ return void 0;
10415
+ }
10416
+ const ignored = new Set(issues.map((issue) => issue.endpointIndex));
10417
+ const endpoints = multicast["endpoints"] ?? [];
10418
+ const flows = [];
10419
+ endpoints.forEach((endpoint, endpointIndex) => {
10420
+ if (ignored.has(endpointIndex)) return;
10421
+ const flowAuth = endpoint["auth"];
10422
+ flows.push({
10423
+ endpointIndex,
10424
+ source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
10425
+ groupAddress: endpoint["groupAddress"],
10426
+ port: endpoint["port"],
10427
+ bandwidth: endpoint["bandwidth"],
10428
+ manifestPort: flowAuth.manifestPort,
10429
+ streamId: flowAuth.streamId,
10430
+ maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
10431
+ manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
10432
+ ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
10433
+ tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
10434
+ name,
10435
+ packetId
10436
+ }))
9628
10437
  });
9629
- byManifestTrack.set(binding.manifestTrack, planned);
9630
- return planned;
9631
10438
  });
9632
- let disposed = false;
9633
10439
  return {
9634
- verifier,
9635
- mode: resolved.mode,
9636
- bindings,
10440
+ keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
10441
+ minEpoch: auth.minEpoch,
10442
+ flows
10443
+ };
10444
+ }
10445
+ function multicastAuthKeyFor(resolved, kid, epoch) {
10446
+ return manifestKeyFor(resolved.keys, epoch, kid);
10447
+ }
10448
+
10449
+ // src/manifest-auth-plan.ts
10450
+ function createManifestAuthPlan(catalog, options = {}) {
10451
+ const resolved = resolveMulticastAuthCatalog(catalog, options);
10452
+ if (!resolved) return void 0;
10453
+ const byManifestTrack = /* @__PURE__ */ new Map();
10454
+ for (const flow of resolved.flows) {
10455
+ if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
10456
+ }
10457
+ return {
10458
+ keys: resolved.keys,
10459
+ minEpoch: resolved.minEpoch,
10460
+ flows: resolved.flows,
9637
10461
  manifestTracks: [...byManifestTrack.keys()],
9638
- bindingIdFor(mediaTrack, sourceSymbolFormat) {
9639
- const bindingId = manifestBindingId(mediaTrack, sourceSymbolFormat);
9640
- return bindings.some((binding) => binding.bindingId === bindingId) ? bindingId : void 0;
9641
- },
9642
- ingestManifestPayload(manifestTrack, payload) {
9643
- const binding = byManifestTrack.get(manifestTrack);
9644
- if (!binding) throw new Error(`unknown manifest subscription track ${manifestTrack}`);
9645
- verifier.ingestManifestFrame(binding.bindingId, payload);
9646
- },
9647
- dispose() {
9648
- if (disposed) return;
9649
- disposed = true;
9650
- verifier.dispose();
9651
- }
10462
+ keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
10463
+ flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
10464
+ flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
9652
10465
  };
9653
10466
  }
9654
10467
  return __toCommonJS(no_modules_exports);