@blockcast/mmt-container 0.4.0 → 0.4.1-main.30f0611c24e8

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 (215) 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 +1904 -692
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +76 -39
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +321 -205
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +12 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +40 -17
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.d.ts +28 -7
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +21 -1
  19. package/dist/catalog-network-source.js.map +2 -2
  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/cmcd-producer.d.ts +8 -0
  25. package/dist/cmcd-producer.d.ts.map +1 -1
  26. package/dist/cmcd-producer.js +14 -0
  27. package/dist/cmcd-producer.js.map +2 -2
  28. package/dist/delivery-catalog.js +98 -234
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +108 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +452 -66
  33. package/dist/fec-manager.js.map +4 -4
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/held-layer-admission.d.ts +58 -0
  43. package/dist/held-layer-admission.d.ts.map +1 -0
  44. package/dist/held-layer-admission.js +105 -0
  45. package/dist/held-layer-admission.js.map +7 -0
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +8 -8
  49. package/dist/index.js.map +2 -2
  50. package/dist/iso-block-locator.d.ts +39 -1
  51. package/dist/iso-block-locator.d.ts.map +1 -1
  52. package/dist/iso-block-locator.js +109 -17
  53. package/dist/iso-block-locator.js.map +3 -3
  54. package/dist/manifest-auth-plan.d.ts +26 -25
  55. package/dist/manifest-auth-plan.d.ts.map +1 -1
  56. package/dist/manifest-auth-plan.js +331 -1171
  57. package/dist/manifest-auth-plan.js.map +4 -4
  58. package/dist/mfu-reassembler.js +21 -13
  59. package/dist/mfu-reassembler.js.map +2 -2
  60. package/dist/mmtp-container-parser.d.ts.map +1 -1
  61. package/dist/mmtp-container-parser.js +93 -22
  62. package/dist/mmtp-container-parser.js.map +2 -2
  63. package/dist/mmtp-container-parser.no-modules.js +1250 -317
  64. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  65. package/dist/mmtp-decode-pipeline.js +93 -22
  66. package/dist/mmtp-decode-pipeline.js.map +2 -2
  67. package/dist/mmtp-fec-session.d.ts +192 -0
  68. package/dist/mmtp-fec-session.d.ts.map +1 -0
  69. package/dist/mmtp-fec-session.js +640 -0
  70. package/dist/mmtp-fec-session.js.map +7 -0
  71. package/dist/mmtp-router.d.ts +39 -6
  72. package/dist/mmtp-router.d.ts.map +1 -1
  73. package/dist/mmtp-router.js +184 -27
  74. package/dist/mmtp-router.js.map +2 -2
  75. package/dist/multicast-auth-catalog.d.ts +86 -92
  76. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  77. package/dist/multicast-auth-catalog.js +347 -132
  78. package/dist/multicast-auth-catalog.js.map +4 -4
  79. package/dist/multicast-input.d.ts +31 -8
  80. package/dist/multicast-input.d.ts.map +1 -1
  81. package/dist/multicast-input.js +299 -35
  82. package/dist/multicast-input.js.map +3 -3
  83. package/dist/multicast-manager.d.ts +94 -5
  84. package/dist/multicast-manager.d.ts.map +1 -1
  85. package/dist/multicast-manager.js +908 -357
  86. package/dist/multicast-manager.js.map +4 -4
  87. package/dist/multicast-transport.d.ts +12 -2
  88. package/dist/multicast-transport.d.ts.map +1 -1
  89. package/dist/multicast-transport.js +108 -238
  90. package/dist/multicast-transport.js.map +4 -4
  91. package/dist/multicast-unwrap.js +21 -13
  92. package/dist/multicast-unwrap.js.map +2 -2
  93. package/dist/no-modules.d.ts +4 -1
  94. package/dist/no-modules.d.ts.map +1 -1
  95. package/dist/no-modules.js +1195 -301
  96. package/dist/no-modules.js.map +4 -4
  97. package/dist/phase14-catalog-override.d.ts +1 -1
  98. package/dist/phase14-catalog-override.d.ts.map +1 -1
  99. package/dist/phase14-catalog-override.js +2 -2
  100. package/dist/phase14-catalog-override.js.map +2 -2
  101. package/dist/repair-fetch.d.ts +81 -6
  102. package/dist/repair-fetch.d.ts.map +1 -1
  103. package/dist/repair-fetch.js +156 -31
  104. package/dist/repair-fetch.js.map +3 -3
  105. package/dist/repair-layers.d.ts +2 -0
  106. package/dist/repair-layers.d.ts.map +1 -1
  107. package/dist/repair-layers.js +19 -2
  108. package/dist/repair-layers.js.map +2 -2
  109. package/dist/sample-combiner.d.ts +7 -1
  110. package/dist/sample-combiner.d.ts.map +1 -1
  111. package/dist/sample-combiner.js +14 -2
  112. package/dist/sample-combiner.js.map +2 -2
  113. package/dist/signaling.d.ts +2 -2
  114. package/dist/signaling.d.ts.map +1 -1
  115. package/dist/signaling.js +3 -3
  116. package/dist/signaling.js.map +2 -2
  117. package/dist/source-auth.js +2710 -7
  118. package/dist/source-auth.js.map +4 -4
  119. package/dist/switching-set-alignment.d.ts +1 -1
  120. package/dist/switching-set-alignment.js.map +1 -1
  121. package/dist/timestamp-codec.js +21 -13
  122. package/dist/timestamp-codec.js.map +2 -2
  123. package/dist/wasm-mfu-reassembler.js.map +1 -1
  124. package/dist/wasm-mmtp-container-parser.js +93 -22
  125. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  126. package/package.json +6 -9
  127. package/schemas/catalog.schema.json +133 -38
  128. package/src/align.ts +52 -21
  129. package/src/carp-catalog.ts +188 -68
  130. package/src/catalog-fec-params.ts +28 -3
  131. package/src/catalog-network-source.ts +49 -7
  132. package/src/catalog-validator.ts +4 -11
  133. package/src/cmcd-producer.ts +17 -0
  134. package/src/fec-manager.ts +366 -63
  135. package/src/fec-state.ts +11 -4
  136. package/src/fec-worker-setup.ts +30 -2
  137. package/src/held-layer-admission.ts +161 -0
  138. package/src/index.ts +27 -10
  139. package/src/iso-block-locator.ts +110 -7
  140. package/src/manifest-auth-plan.ts +39 -91
  141. package/src/mmtp-container-parser.ts +75 -7
  142. package/src/mmtp-fec-session.ts +606 -0
  143. package/src/mmtp-router.ts +166 -7
  144. package/src/multicast-auth-catalog.ts +131 -238
  145. package/src/multicast-input.ts +148 -124
  146. package/src/multicast-manager.ts +267 -21
  147. package/src/multicast-transport.ts +17 -3
  148. package/src/no-modules.ts +7 -1
  149. package/src/phase14-catalog-override.ts +3 -3
  150. package/src/repair-fetch.ts +283 -39
  151. package/src/repair-layers.ts +22 -2
  152. package/src/sample-combiner.ts +15 -2
  153. package/src/signaling.ts +2 -2
  154. package/src/switching-set-alignment.ts +1 -1
  155. package/test-vectors/align.json +108 -32
  156. package/test-vectors/bc-provenance-v2.json +1526 -0
  157. package/test-vectors/catalog/README.md +71 -4
  158. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  159. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  160. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  161. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  162. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  163. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  164. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  165. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  166. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  167. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  168. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  169. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  170. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  171. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  172. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  173. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  174. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  177. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  178. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  179. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  181. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  182. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  183. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  184. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  185. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  186. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  187. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  188. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  189. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  190. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  191. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  192. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  193. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  194. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  195. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  196. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  197. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  198. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  199. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  200. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  201. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  202. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  203. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  204. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  205. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  206. package/test-vectors/catalog/section-codes.json +31 -1
  207. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  208. package/test-vectors/catalog-validation.json +101 -5
  209. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  210. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  211. package/dist/fec-codec.d.ts +0 -32
  212. package/dist/fec-codec.d.ts.map +0 -1
  213. package/dist/fec-codec.js +0 -47
  214. package/dist/fec-codec.js.map +0 -7
  215. 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,35 @@ 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
+ }
367
480
 
368
481
  // ../mmt-base/dist/catalog-fec-source.js
369
482
  var ALL_ROLES = Object.freeze(["video", "audio"]);
@@ -377,6 +490,269 @@ var BlockcastMmt = (() => {
377
490
  const ms = block["interleaveDepthMs"];
378
491
  return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
379
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
+ }
380
756
 
381
757
  // src/mfu-reassembler.ts
382
758
  function fragmentProvenance(fragment) {
@@ -3220,8 +3596,14 @@ var BlockcastMmt = (() => {
3220
3596
  /**
3221
3597
  * Add one reassembled data unit. Returns the combined sample once every
3222
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.
3223
3605
  */
3224
- addMfu(mfu) {
3606
+ addMfu(mfu, sampleSize) {
3225
3607
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3226
3608
  __privateGet(this, _stats).passthroughSamples++;
3227
3609
  return fromPassthrough(mfu);
@@ -3237,7 +3619,7 @@ var BlockcastMmt = (() => {
3237
3619
  return null;
3238
3620
  }
3239
3621
  const dataLen = mfu.data.byteLength;
3240
- const authoredSize = __privateGet(this, _authoredSizes).get(key);
3622
+ const authoredSize = __privateGet(this, _authoredSizes).get(key) ?? sampleSize;
3241
3623
  if (offset === 0 && !__privateGet(this, _pending).has(key)) {
3242
3624
  const passesThrough = authoredSize === void 0 ? !__privateGet(this, _requireAuthoredSize) : dataLen === authoredSize;
3243
3625
  if (passesThrough) {
@@ -3545,6 +3927,12 @@ var BlockcastMmt = (() => {
3545
3927
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
3546
3928
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
3547
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
+ });
3548
3936
  test("duplicate offset is rejected", () => {
3549
3937
  const c = combiner();
3550
3938
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -5532,7 +5920,8 @@ var BlockcastMmt = (() => {
5532
5920
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
5533
5921
  return FMPU_BOX_TYPES.has(type);
5534
5922
  }
5535
- 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;
5536
5925
  var _MmtpContainerParser = class _MmtpContainerParser {
5537
5926
  constructor(config) {
5538
5927
  __privateAdd(this, _MmtpContainerParser_instances);
@@ -5595,6 +5984,7 @@ var BlockcastMmt = (() => {
5595
5984
  * reordering into the parser. */
5596
5985
  __privateAdd(this, _reliableMoqStartupGate, /* @__PURE__ */ new Map());
5597
5986
  __privateAdd(this, _disposed, false);
5987
+ __privateAdd(this, _replayingAwaitingTiming, false);
5598
5988
  __privateAdd(this, _fedObjects, 0);
5599
5989
  __privateAdd(this, _reassemblerFragmentsFed, 0);
5600
5990
  __privateAdd(this, _reassemblerDataUnitsReturned, 0);
@@ -5853,6 +6243,12 @@ var BlockcastMmt = (() => {
5853
6243
  for (const combiner of __privateGet(this, _sampleCombiners).values()) {
5854
6244
  combiner.cleanupTimeouts(timeoutMs);
5855
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
+ }
5856
6252
  }
5857
6253
  /**
5858
6254
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -6139,6 +6535,7 @@ var BlockcastMmt = (() => {
6139
6535
  _reorderStats = new WeakMap();
6140
6536
  _reliableMoqStartupGate = new WeakMap();
6141
6537
  _disposed = new WeakMap();
6538
+ _replayingAwaitingTiming = new WeakMap();
6142
6539
  _fedObjects = new WeakMap();
6143
6540
  _reassemblerFragmentsFed = new WeakMap();
6144
6541
  _reassemblerDataUnitsReturned = new WeakMap();
@@ -6219,7 +6616,8 @@ var BlockcastMmt = (() => {
6219
6616
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
6220
6617
  */
6221
6618
  drop_fn = function(reason) {
6222
- __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}`);
6223
6621
  return null;
6224
6622
  };
6225
6623
  feedCounted_fn = function(packet, options, parsed) {
@@ -6248,7 +6646,7 @@ var BlockcastMmt = (() => {
6248
6646
  byteLength: packet.byteLength
6249
6647
  };
6250
6648
  }
6251
- if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb)) {
6649
+ if (info.fecPayloadId !== null && __privateGet(this, _sourceSymbolCb) && !__privateGet(this, _replayingAwaitingTiming)) {
6252
6650
  const rawSymbol = packet.subarray(0, packet.length - 4);
6253
6651
  try {
6254
6652
  __privateGet(this, _sourceSymbolCb).call(this, info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -6296,6 +6694,7 @@ var BlockcastMmt = (() => {
6296
6694
  }
6297
6695
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "fragment-timing-refused");
6298
6696
  }
6697
+ __privateMethod(this, _MmtpContainerParser_instances, replayAwaitingTiming_fn).call(this, streamKey, resolver2);
6299
6698
  return {
6300
6699
  kind: "fragment",
6301
6700
  packet: info,
@@ -6319,7 +6718,18 @@ var BlockcastMmt = (() => {
6319
6718
  mfuDuHeader.movieFragmentSequenceNumber,
6320
6719
  mfuDuHeader.sampleNumber
6321
6720
  );
6322
- 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
+ }
6323
6733
  const offset = mfuDuHeader.offset;
6324
6734
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
6325
6735
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "mfu-offset-out-of-range");
@@ -6389,16 +6799,17 @@ var BlockcastMmt = (() => {
6389
6799
  const sampleNumber = assembled.sampleNumber;
6390
6800
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
6391
6801
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-identity-missing");
6392
- if (!resolver.sampleTiming(
6802
+ const assembledTiming = resolver.sampleTiming(
6393
6803
  assembled.mpuSequenceNumber,
6394
6804
  movieFragmentSequenceNumber,
6395
6805
  sampleNumber
6396
- )) 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");
6397
6808
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
6398
6809
  return __privateMethod(this, _MmtpContainerParser_instances, drop_fn).call(this, "assembled-mpu-mismatch");
6399
6810
  let combined;
6400
6811
  try {
6401
- 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);
6402
6813
  } catch (error) {
6403
6814
  if (!(error instanceof SampleCombineError)) throw error;
6404
6815
  console.warn(
@@ -6492,9 +6903,37 @@ var BlockcastMmt = (() => {
6492
6903
  if (existing) return existing.resolver;
6493
6904
  if (!create) return null;
6494
6905
  const resolver = new IsoBmffTimingResolver(__privateGet(this, _maxPendingTimingSamples));
6495
- __privateGet(this, _timingStreams).set(streamKey, { packetId, resolver });
6906
+ __privateGet(this, _timingStreams).set(streamKey, { packetId, resolver, awaitingTiming: [] });
6496
6907
  return resolver;
6497
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
+ };
6498
6937
  dropTimingStream_fn = function(streamKey) {
6499
6938
  const state = __privateGet(this, _timingStreams).get(streamKey);
6500
6939
  if (!state) return;
@@ -6996,197 +7435,6 @@ var BlockcastMmt = (() => {
6996
7435
  });
6997
7436
  }
6998
7437
 
6999
- // src/multicast-auth-catalog.ts
7000
- var RAW_ED25519_KEY_LENGTH = 32;
7001
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
7002
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
7003
- function encodeBase64Url(bytes) {
7004
- let output = "";
7005
- for (let i = 0; i < bytes.length; i += 3) {
7006
- const b0 = bytes[i];
7007
- const b1 = bytes[i + 1];
7008
- const b2 = bytes[i + 2];
7009
- output += BASE64URL_ALPHABET[b0 >> 2];
7010
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
7011
- if (b1 === void 0) break;
7012
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
7013
- if (b2 === void 0) break;
7014
- output += BASE64URL_ALPHABET[b2 & 63];
7015
- }
7016
- return output;
7017
- }
7018
- var BASE64URL_DECODE_TABLE = (() => {
7019
- const table = new Int8Array(128).fill(-1);
7020
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
7021
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
7022
- }
7023
- return table;
7024
- })();
7025
- function decodeBase64Url(text) {
7026
- if (text.length % 4 === 1) {
7027
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
7028
- }
7029
- const bytes = [];
7030
- let buffer = 0;
7031
- let bits = 0;
7032
- for (let i = 0; i < text.length; i++) {
7033
- const code = text.charCodeAt(i);
7034
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
7035
- if (value === void 0 || value < 0) {
7036
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
7037
- }
7038
- buffer = buffer << 6 | value;
7039
- bits += 6;
7040
- if (bits >= 8) {
7041
- bits -= 8;
7042
- bytes.push(buffer >> bits & 255);
7043
- }
7044
- }
7045
- const decoded = Uint8Array.from(bytes);
7046
- if (encodeBase64Url(decoded) !== text) {
7047
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
7048
- }
7049
- return decoded;
7050
- }
7051
- function decodeAuthScope(authScope) {
7052
- const bytes = decodeBase64Url(authScope);
7053
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
7054
- throw new Error(
7055
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
7056
- );
7057
- }
7058
- return bytes;
7059
- }
7060
- function decodeEd25519PublicKey(publicKey) {
7061
- const bytes = decodeBase64Url(publicKey);
7062
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
7063
- throw new Error(
7064
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
7065
- );
7066
- }
7067
- return bytes;
7068
- }
7069
- function isNonEmptyString(value) {
7070
- return typeof value === "string" && value.length > 0;
7071
- }
7072
- function isValidAuthScopeField(value) {
7073
- if (!isNonEmptyString(value)) return false;
7074
- try {
7075
- decodeAuthScope(value);
7076
- return true;
7077
- } catch {
7078
- return false;
7079
- }
7080
- }
7081
- function isValidPublicKeyField(value) {
7082
- if (!isNonEmptyString(value)) return false;
7083
- try {
7084
- decodeEd25519PublicKey(value);
7085
- return true;
7086
- } catch {
7087
- return false;
7088
- }
7089
- }
7090
- function hasOnlyKeys(object, allowed) {
7091
- const allowedKeys = new Set(allowed);
7092
- return Object.keys(object).every((key) => allowedKeys.has(key));
7093
- }
7094
- function isMulticastAuthTrackConfig(obj) {
7095
- if (typeof obj !== "object" || obj === null) return false;
7096
- const o = obj;
7097
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
7098
- }
7099
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
7100
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
7101
- function hasUniqueMulticastAuthTrackBindings(tracks) {
7102
- const bindings = tracks.flatMap((track) => {
7103
- if (typeof track !== "object" || track === null) return [];
7104
- const value = track;
7105
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
7106
- return [];
7107
- }
7108
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
7109
- });
7110
- return new Set(bindings).size === bindings.length;
7111
- }
7112
- function isMulticastAuthConfig(obj) {
7113
- if (typeof obj !== "object" || obj === null) return false;
7114
- const o = obj;
7115
- if (o["scheme"] !== "bc-provenance") return false;
7116
- if (o["hash"] !== "blake3") return false;
7117
- if (o["sig"] !== "ed25519") return false;
7118
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
7119
- if (!isValidPublicKeyField(o["publicKey"])) return false;
7120
- if (!isNonEmptyString(o["keyId"])) return false;
7121
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
7122
- if (o["previousKey"] === o["publicKey"]) return false;
7123
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
7124
- if (o["enforcement"] !== void 0) {
7125
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
7126
- }
7127
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
7128
- const tracks = o["tracks"];
7129
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
7130
- const typedTracks = tracks;
7131
- const scopes = typedTracks.map((t) => t.authScope);
7132
- if (new Set(scopes).size !== scopes.length) return false;
7133
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
7134
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
7135
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
7136
- return true;
7137
- }
7138
- function resolveMulticastAuthMode(playerMode, auth) {
7139
- if (playerMode !== void 0) return playerMode;
7140
- if (auth === void 0) return "off";
7141
- return auth.enforcement ?? "shadow";
7142
- }
7143
- function resolveMulticastAuthCatalog(catalog, playerMode) {
7144
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
7145
- throw new Error("[multicast-auth-catalog] catalog must be an object");
7146
- }
7147
- const root = catalog;
7148
- const rawAuth = root["multicast.auth"];
7149
- if (rawAuth === void 0) {
7150
- if (playerMode === "enforce") {
7151
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
7152
- }
7153
- return void 0;
7154
- }
7155
- if (!isMulticastAuthConfig(rawAuth)) {
7156
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
7157
- }
7158
- const rawTracks = root["tracks"];
7159
- if (!Array.isArray(rawTracks)) {
7160
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
7161
- }
7162
- const catalogTrackNames = new Set(
7163
- rawTracks.flatMap(
7164
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
7165
- )
7166
- );
7167
- for (const track of rawAuth.tracks) {
7168
- if (!catalogTrackNames.has(track.mediaTrack)) {
7169
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
7170
- }
7171
- if (!catalogTrackNames.has(track.manifestTrack)) {
7172
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
7173
- }
7174
- }
7175
- return {
7176
- keyId: rawAuth.keyId,
7177
- acceptedPublicKeys: [
7178
- decodeEd25519PublicKey(rawAuth.publicKey),
7179
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
7180
- ],
7181
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
7182
- compaction: rawAuth.compaction,
7183
- tracks: rawAuth.tracks.map((track) => ({
7184
- ...track,
7185
- authScope: decodeAuthScope(track.authScope)
7186
- }))
7187
- };
7188
- }
7189
-
7190
7438
  // src/repair-layers.ts
7191
7439
  var REPAIR_PRIORITY_MIN = 192;
7192
7440
  var REPAIR_PRIORITY_MAX = 255;
@@ -7194,6 +7442,7 @@ var BlockcastMmt = (() => {
7194
7442
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
7195
7443
  var MAX_REPAIR_SYMBOLS = 16777215;
7196
7444
  var MAX_ENCODING_SYMBOL_ID = 16777215;
7445
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
7197
7446
  var RepairContractError = class extends Error {
7198
7447
  constructor(code, path, message) {
7199
7448
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -7376,11 +7625,12 @@ var BlockcastMmt = (() => {
7376
7625
  if (layered && !positiveInteger(source.sourceSymbols)) {
7377
7626
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
7378
7627
  }
7379
- if (layered && source.algorithm !== "raptorq") {
7628
+ const reedSolomon = source.algorithm === "reed-solomon";
7629
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
7380
7630
  fail(
7381
7631
  "track_fec",
7382
7632
  `${source.path}.algorithm`,
7383
- "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)"
7384
7634
  );
7385
7635
  }
7386
7636
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -7439,6 +7689,13 @@ var BlockcastMmt = (() => {
7439
7689
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7440
7690
  );
7441
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
+ }
7442
7699
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
7443
7700
  }
7444
7701
  let offset = layerZeroSymbols;
@@ -7483,6 +7740,13 @@ var BlockcastMmt = (() => {
7483
7740
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7484
7741
  );
7485
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
+ }
7486
7750
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
7487
7751
  }
7488
7752
 
@@ -7570,13 +7834,22 @@ var BlockcastMmt = (() => {
7570
7834
  function catalogError(code, path, message) {
7571
7835
  throw new CmsfCatalogValidationError(code, path, message);
7572
7836
  }
7573
- function validateCmsfMmtpCatalog(value) {
7837
+ function validateNetworkSourceRelays(sources, path) {
7838
+ if (!Array.isArray(sources)) return;
7839
+ sources.forEach((source, i) => {
7840
+ const s = source;
7841
+ if (s?.["type"] === "amt" && s["discovery"] === "driad" && s["relay"] !== void 0) {
7842
+ catalogError("multicast_network_source", `${path}[${i}].relay`, 'relay must be omitted with discovery "driad"');
7843
+ }
7844
+ });
7845
+ }
7846
+ function validateCmsfMmtpCatalog(value, options = {}) {
7574
7847
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
7575
7848
  catalogError("catalog_object", "$", "catalog must be an object");
7576
7849
  }
7577
7850
  const catalog = value;
7578
7851
  const rawVersion = catalog["version"];
7579
- const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") ? 1 : NaN : rawVersion;
7852
+ const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") || rawVersion === "draft-01" ? 1 : NaN : rawVersion;
7580
7853
  if (!Number.isInteger(normalizedVersion) || normalizedVersion <= 0) {
7581
7854
  catalogError("catalog_version", "$.version", "version must be a positive integer or a recognized format tag");
7582
7855
  }
@@ -7591,6 +7864,22 @@ var BlockcastMmt = (() => {
7591
7864
  "commonTrackFields is retired; every track carries its own fields"
7592
7865
  );
7593
7866
  }
7867
+ const initDataList = catalog["initDataList"];
7868
+ if (initDataList !== void 0) {
7869
+ if (!Array.isArray(initDataList)) {
7870
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
7871
+ }
7872
+ initDataList.forEach((entry, i) => {
7873
+ const e = entry;
7874
+ const entryPath = `$.initDataList[${i}]`;
7875
+ 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) {
7876
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
7877
+ }
7878
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
7879
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
7880
+ }
7881
+ });
7882
+ }
7594
7883
  const tracks = catalog["tracks"];
7595
7884
  const trackRecords = [];
7596
7885
  const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -7642,6 +7931,14 @@ var BlockcastMmt = (() => {
7642
7931
  if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
7643
7932
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
7644
7933
  }
7934
+ const anchor = track["presentationAnchorTicks"];
7935
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
7936
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
7937
+ }
7938
+ const initRef = track["initRef"];
7939
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
7940
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7941
+ }
7645
7942
  if (packaging === "fec-repair") {
7646
7943
  rejectRepairTrackGeometry(path, track, catalogError);
7647
7944
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -7649,9 +7946,8 @@ var BlockcastMmt = (() => {
7649
7946
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
7650
7947
  }
7651
7948
  if (packaging === "mmtp") {
7652
- const mmtpMode = track["mmtpMode"];
7653
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
7654
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
7949
+ if (track["mmtpMode"] !== "mfu") {
7950
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7655
7951
  }
7656
7952
  if (!positiveInteger2(timescale)) {
7657
7953
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -7674,8 +7970,8 @@ var BlockcastMmt = (() => {
7674
7970
  }
7675
7971
  const config = fec;
7676
7972
  const algorithm = config["algorithm"];
7677
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
7678
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
7973
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
7974
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
7679
7975
  }
7680
7976
  if ("interleaveDepth" in config || "interleaveMs" in config) {
7681
7977
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -7704,6 +8000,9 @@ var BlockcastMmt = (() => {
7704
8000
  }
7705
8001
  }
7706
8002
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
8003
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
8004
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
8005
+ }
7707
8006
  }
7708
8007
  }
7709
8008
  const repairDescriptors = trackRecords.flatMap(
@@ -7753,19 +8052,34 @@ var BlockcastMmt = (() => {
7753
8052
  const timescale = BigInt(track["timescale"]);
7754
8053
  const durationTicks = track["groupDurationTicks"];
7755
8054
  const ticks = durationTicks !== void 0 ? BigInt(durationTicks) : BigInt(track["groupDurationMs"]) * timescale / 1000n;
7756
- const anchor = switchingSets.get(altGroup);
7757
- if (anchor && ticks * anchor.timescale !== anchor.ticks * timescale) {
7758
- catalogError("track_switching_set", `$.tracks[${index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
8055
+ const framerate = track["framerate"];
8056
+ const intraOnly = positiveNumber(framerate) && Math.abs(Number(ticks) * framerate - Number(timescale)) <= Number(timescale) * 1e-3;
8057
+ const members = switchingSets.get(altGroup) ?? [];
8058
+ members.push({ index, name: track["name"], ticks, timescale, intraOnly });
8059
+ switchingSets.set(altGroup, members);
8060
+ }
8061
+ for (const [altGroup, members] of switchingSets) {
8062
+ const anchor = members.find((member) => !member.intraOnly) ?? members[0];
8063
+ for (const member of members) {
8064
+ if (member === anchor || member.ticks * anchor.timescale === anchor.ticks * member.timescale) continue;
8065
+ const nests = member.intraOnly && !anchor.intraOnly && anchor.ticks * member.timescale % (member.ticks * anchor.timescale) === 0n;
8066
+ if (!nests) {
8067
+ catalogError("track_switching_set", `$.tracks[${member.index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
8068
+ }
7759
8069
  }
7760
- if (!anchor) switchingSets.set(altGroup, { name: track["name"], ticks, timescale });
7761
8070
  }
7762
8071
  const multicast = catalog["multicast"];
7763
8072
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
8073
+ validateNetworkSourceRelays(multicast["networkSource"], "$.multicast.networkSource");
7764
8074
  const endpoints = multicast["endpoints"];
7765
8075
  if (Array.isArray(endpoints)) {
7766
8076
  for (let endpointIndex = 0; endpointIndex < endpoints.length; endpointIndex++) {
7767
8077
  const endpoint = endpoints[endpointIndex];
7768
8078
  if (typeof endpoint !== "object" || endpoint === null || Array.isArray(endpoint)) continue;
8079
+ validateNetworkSourceRelays(
8080
+ endpoint["networkSource"],
8081
+ `$.multicast.endpoints[${endpointIndex}].networkSource`
8082
+ );
7769
8083
  if ("relayAddress" in endpoint) {
7770
8084
  catalogError(
7771
8085
  "multicast_relay_address",
@@ -7805,15 +8119,8 @@ var BlockcastMmt = (() => {
7805
8119
  }
7806
8120
  }
7807
8121
  }
7808
- try {
7809
- resolveMulticastAuthCatalog(catalog);
7810
- } catch (error) {
7811
- catalogError(
7812
- "multicast_auth",
7813
- "$.multicast.auth",
7814
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
7815
- );
7816
- }
8122
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
8123
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
7817
8124
  validateArchive(catalog);
7818
8125
  return catalog;
7819
8126
  }
@@ -7823,14 +8130,42 @@ var BlockcastMmt = (() => {
7823
8130
  const ms = fec?.interleaveDepthMs;
7824
8131
  return typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0 ? ms : void 0;
7825
8132
  }
7826
- function computeFecTimeout(interleaveDepthMs, safetyFactor = 3) {
7827
- if (!Number.isFinite(interleaveDepthMs) || interleaveDepthMs <= 0) {
8133
+ function fecBlockDeadlineMs(params) {
8134
+ const { firstAcceptedAtMs, interleaveDepthMs, reorderToleranceMs } = params;
8135
+ if (!Number.isFinite(firstAcceptedAtMs)) {
8136
+ throw new Error(`[FEC] firstAcceptedAtMs must be finite (got ${firstAcceptedAtMs}).`);
8137
+ }
8138
+ return firstAcceptedAtMs + fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs);
8139
+ }
8140
+ function fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs) {
8141
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0)) {
8142
+ throw new Error(`[FEC] interleaveDepthMs must be a finite value > 0 (got ${interleaveDepthMs}ms). Fix encoder config.`);
8143
+ }
8144
+ if (!(reorderToleranceMs >= 0) || !Number.isFinite(reorderToleranceMs)) {
8145
+ 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.`);
8146
+ }
8147
+ return Math.ceil(interleaveDepthMs + reorderToleranceMs);
8148
+ }
8149
+ function deriveFecRetentionBlocks(deliveryWindowMs, interleaveDepthMs) {
8150
+ const blocks = tryDeriveFecRetentionBlocks(deliveryWindowMs, interleaveDepthMs);
8151
+ if (blocks !== void 0)
8152
+ return blocks;
8153
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0)) {
7828
8154
  throw new Error(`[FEC] interleaveDepthMs must be a finite value > 0 (got ${interleaveDepthMs}ms). Fix encoder config.`);
7829
8155
  }
7830
- if (!Number.isFinite(safetyFactor) || safetyFactor <= 0) {
7831
- throw new Error(`[FEC] safetyFactor must be a finite value > 0 (got ${safetyFactor}). Fix encoder config.`);
8156
+ if (!Number.isFinite(deliveryWindowMs) || !(deliveryWindowMs > 0)) {
8157
+ throw new Error(`[FEC] deliveryWindowMs must be a finite value > 0 (got ${deliveryWindowMs}ms). It is derived from catalog geometry, not a local default.`);
7832
8158
  }
7833
- return Math.ceil(interleaveDepthMs * safetyFactor);
8159
+ 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.`);
8160
+ }
8161
+ var MAX_FEC_RETENTION_BLOCKS = 255;
8162
+ function tryDeriveFecRetentionBlocks(deliveryWindowMs, interleaveDepthMs) {
8163
+ if (!Number.isFinite(interleaveDepthMs) || !(interleaveDepthMs > 0))
8164
+ return void 0;
8165
+ if (!Number.isFinite(deliveryWindowMs) || !(deliveryWindowMs > 0))
8166
+ return void 0;
8167
+ const blocks = Math.ceil(deliveryWindowMs / interleaveDepthMs) + 1;
8168
+ return blocks > MAX_FEC_RETENTION_BLOCKS ? void 0 : blocks;
7834
8169
  }
7835
8170
 
7836
8171
  // ../fec/dist/repair-group.js
@@ -7854,13 +8189,13 @@ var BlockcastMmt = (() => {
7854
8189
  function recordOf2(value) {
7855
8190
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7856
8191
  }
7857
- function isPositiveSafeInteger(value) {
8192
+ function isPositiveSafeInteger2(value) {
7858
8193
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
7859
8194
  }
7860
8195
  function catalogDeclaresFec(fec) {
7861
8196
  const block = recordOf2(fec);
7862
- if (block === void 0 || block["algorithm"] === "none") return false;
7863
- return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
8197
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
8198
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
7864
8199
  }
7865
8200
  function requireBoolean(value, field) {
7866
8201
  if (typeof value !== "boolean") {
@@ -7888,6 +8223,508 @@ var BlockcastMmt = (() => {
7888
8223
  return INACTIVE["reliable-moq"];
7889
8224
  }
7890
8225
 
8226
+ // src/held-layer-admission.ts
8227
+ var HORIZON_CAP = 1073741824;
8228
+ function heldLayerAnchorHorizon(retentionBlocks, k) {
8229
+ return retentionBlocks === void 0 || k <= 0 ? HORIZON_CAP : Math.min(HORIZON_CAP, retentionBlocks * k);
8230
+ }
8231
+ var _layerNames, _states;
8232
+ var HeldLayerAdmission = class {
8233
+ constructor(layers, heldLayers = [0]) {
8234
+ __privateAdd(this, _layerNames);
8235
+ __privateAdd(this, _states);
8236
+ const held = new Set(heldLayers);
8237
+ __privateSet(this, _layerNames, new Set(layers.map((l) => l.repairTrackName)));
8238
+ __privateSet(this, _states, layers.filter((l) => held.has(l.layer)).map((l) => ({ layer: l.layer, repairTrackName: l.repairTrackName, total: l.rsIdOffset + l.repairSymbols })));
8239
+ }
8240
+ /**
8241
+ * Judges one repair packet, after the 4.5 discards and the size check and
8242
+ * before it places a block. `repairTrackName` is the subscribed repair
8243
+ * track, never inferred from RS_ID; without it only (b) runs. A packet on a
8244
+ * repair track the catalog does not list is `'discard'` and anchors nothing.
8245
+ * `sourceFrontier` is the newest source SS_ID, if any: a repair more than
8246
+ * `horizon` past it is judged without moving the anchored state.
8247
+ *
8248
+ * @returns undefined to admit, `'discard'`, or the fail-closed reason.
8249
+ */
8250
+ admit(repairTrackName, ssStart, rsbLength, horizon, sourceFrontier) {
8251
+ if (repairTrackName !== void 0 && !__privateGet(this, _layerNames).has(repairTrackName)) return "discard";
8252
+ const farAhead = sourceFrontier !== void 0 && serial32Precedes(sourceFrontier, ssStart) && serial32Distance(sourceFrontier, ssStart) > horizon;
8253
+ for (const state of __privateGet(this, _states)) {
8254
+ let code;
8255
+ if (farAhead) {
8256
+ if (rsbLength < state.total) {
8257
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
8258
+ else if (state.anchor !== void 0 || state.settled) code = "below_anchored_total";
8259
+ }
8260
+ } else {
8261
+ if (state.newest === void 0 || serial32Precedes(state.newest, ssStart)) state.newest = ssStart;
8262
+ const stale = (s) => serial32Distance(s, state.newest) > horizon;
8263
+ if (state.latestBelow !== void 0 && stale(state.latestBelow)) {
8264
+ delete state.latestBelow;
8265
+ delete state.latestBelowRsb;
8266
+ }
8267
+ if (state.anchor !== void 0 && stale(state.anchor)) state.settled = true;
8268
+ if (rsbLength < state.total) {
8269
+ if (state.layer > 0 && repairTrackName === state.repairTrackName) code = "below_own_track_total";
8270
+ else if (stale(ssStart)) continue;
8271
+ else if (state.settled || state.anchor !== void 0 && !serial32Precedes(ssStart, state.anchor)) code = "below_anchored_total";
8272
+ else if (state.latestBelow === void 0 || serial32Precedes(state.latestBelow, ssStart)) {
8273
+ state.latestBelow = ssStart;
8274
+ state.latestBelowRsb = rsbLength;
8275
+ }
8276
+ } else if (!state.settled && !stale(ssStart)) {
8277
+ if (state.anchor === void 0 || serial32Precedes(ssStart, state.anchor)) state.anchor = ssStart;
8278
+ if (state.latestBelow !== void 0 && !serial32Precedes(state.latestBelow, state.anchor)) {
8279
+ code = "below_anchored_total";
8280
+ ssStart = state.latestBelow;
8281
+ rsbLength = state.latestBelowRsb;
8282
+ }
8283
+ }
8284
+ }
8285
+ if (code !== void 0) {
8286
+ return {
8287
+ code,
8288
+ layer: state.layer,
8289
+ total: state.total,
8290
+ rsbLength,
8291
+ ssStart,
8292
+ ...state.anchor === void 0 ? {} : { anchor: state.anchor }
8293
+ };
8294
+ }
8295
+ }
8296
+ return void 0;
8297
+ }
8298
+ };
8299
+ _layerNames = new WeakMap();
8300
+ _states = new WeakMap();
8301
+
8302
+ // src/mmtp-fec-session.ts
8303
+ var PATH_BITS = { moq: 1, multicast: 2 };
8304
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8305
+ var _decoder, _blocks, _settled, _have, _newest, _prunedAt, _repairPacketId, _newestSource, _heldLayers, _anchorHorizon, _stats3, _MmtpFecSession_instances, drop_fn2, noteNewest_fn, blockStartOf_fn, countHeld_fn, noteMixed_fn, behindHorizon_fn, settle_fn, settleClean_fn, settleDecoded_fn, retireBehindHorizon_fn;
8306
+ var MmtpFecSession = class {
8307
+ /**
8308
+ * @throws when the catalog block lacks or misstates a field the session
8309
+ * needs: the block profile, K, P_0 (`repairSymbols`), T, `interleaveDepthMs` or
8310
+ * `reorderToleranceMs`. None is defaulted.
8311
+ */
8312
+ constructor(config) {
8313
+ __privateAdd(this, _MmtpFecSession_instances);
8314
+ __privateAdd(this, _decoder);
8315
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
8316
+ __privateAdd(this, _blocks, /* @__PURE__ */ new Map());
8317
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
8318
+ __privateAdd(this, _settled, /* @__PURE__ */ new Set());
8319
+ /**
8320
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
8321
+ * received on, or 0 for one the session recovered.
8322
+ */
8323
+ __privateAdd(this, _have, /* @__PURE__ */ new Map());
8324
+ __privateAdd(this, _newest);
8325
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
8326
+ __privateAdd(this, _prunedAt);
8327
+ __privateAdd(this, _repairPacketId);
8328
+ __privateAdd(this, _newestSource);
8329
+ __privateAdd(this, _heldLayers);
8330
+ __privateAdd(this, _anchorHorizon);
8331
+ __privateAdd(this, _stats3, {
8332
+ sourceSymbols: 0,
8333
+ repairSymbols: 0,
8334
+ blocksClean: 0,
8335
+ blocksRecovered: 0,
8336
+ blocksFailed: 0,
8337
+ blocksReleased: 0,
8338
+ packetsRecovered: 0,
8339
+ packetsLost: 0,
8340
+ dropped: {},
8341
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
8342
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
8343
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
8344
+ failClosed: null
8345
+ });
8346
+ const fec = config?.fec;
8347
+ if (!fec || typeof fec !== "object") {
8348
+ throw new Error("MmtpFecSession: the catalog fec block is required");
8349
+ }
8350
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
8351
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
8352
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
8353
+ }
8354
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
8355
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8356
+ this.repairSymbols = requirePositiveInteger(fec.repairSymbols, "fec.repairSymbols");
8357
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8358
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8359
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
8360
+ this.retentionBlocks = deriveFecRetentionBlocks(
8361
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
8362
+ interleaveDepthMs
8363
+ );
8364
+ __privateSet(this, _heldLayers, new HeldLayerAdmission(
8365
+ config.repairLayers ?? [
8366
+ {
8367
+ layer: 0,
8368
+ repairTrackName: typeof fec.repairTrack === "string" ? fec.repairTrack : "",
8369
+ rsIdOffset: 0,
8370
+ repairSymbols: this.repairSymbols
8371
+ }
8372
+ ],
8373
+ config.heldLayers
8374
+ ));
8375
+ __privateSet(this, _anchorHorizon, heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols));
8376
+ if (typeof config.Decoder !== "function") {
8377
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8378
+ }
8379
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
8380
+ try {
8381
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
8382
+ } catch (error) {
8383
+ decoder.free();
8384
+ throw error;
8385
+ }
8386
+ __privateSet(this, _decoder, decoder);
8387
+ }
8388
+ /** True once release() ran. */
8389
+ get released() {
8390
+ return __privateGet(this, _decoder) === null;
8391
+ }
8392
+ get stats() {
8393
+ return {
8394
+ ...__privateGet(this, _stats3),
8395
+ dropped: { ...__privateGet(this, _stats3).dropped },
8396
+ sourceSymbolsByPath: { ...__privateGet(this, _stats3).sourceSymbolsByPath },
8397
+ repairSymbolsByPath: { ...__privateGet(this, _stats3).repairSymbolsByPath },
8398
+ mixedPath: { ...__privateGet(this, _stats3).mixedPath },
8399
+ failClosed: __privateGet(this, _stats3).failClosed && { ...__privateGet(this, _stats3).failClosed }
8400
+ };
8401
+ }
8402
+ /**
8403
+ * Feeds one received source packet: the MMTP packet without its four-byte
8404
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
8405
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
8406
+ * was received; a caller that only subscribes over MoQT can leave it out.
8407
+ *
8408
+ * @returns the protected packets of this packet's block that it recovered,
8409
+ * in SS_ID order, for the caller to feed to its parser with
8410
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
8411
+ */
8412
+ addSource(ssId, packet, path = "moq") {
8413
+ const decoder = __privateGet(this, _decoder);
8414
+ if (!decoder) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:released");
8415
+ const pathBit = PATH_BITS[path];
8416
+ if (!pathBit) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:unknown-path");
8417
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:bad-ss-id");
8418
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:exceeds-symbol");
8419
+ if (__privateGet(this, _have).has(ssId)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:duplicate");
8420
+ __privateGet(this, _have).set(ssId, pathBit);
8421
+ __privateGet(this, _stats3).sourceSymbols++;
8422
+ __privateGet(this, _stats3).sourceSymbolsByPath[path]++;
8423
+ __privateMethod(this, _MmtpFecSession_instances, noteNewest_fn).call(this, ssId);
8424
+ if (__privateGet(this, _newestSource) === void 0 || serial32Precedes(__privateGet(this, _newestSource), ssId)) __privateSet(this, _newestSource, ssId);
8425
+ const start = __privateMethod(this, _MmtpFecSession_instances, blockStartOf_fn).call(this, ssId);
8426
+ const block = start === void 0 ? void 0 : __privateGet(this, _blocks).get(start);
8427
+ if (block) {
8428
+ block.received++;
8429
+ block.paths |= pathBit;
8430
+ }
8431
+ let output;
8432
+ try {
8433
+ output = decoder.add_source(ssId, packet, 0);
8434
+ } catch {
8435
+ __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "source:decoder-refused");
8436
+ output = void 0;
8437
+ }
8438
+ const recovered = [];
8439
+ if (start !== void 0 && block) {
8440
+ if (output) {
8441
+ recovered.push(...__privateMethod(this, _MmtpFecSession_instances, settleDecoded_fn).call(this, start, block, output));
8442
+ } else if (block.received >= block.ssbLength) {
8443
+ __privateMethod(this, _MmtpFecSession_instances, settleClean_fn).call(this, start);
8444
+ }
8445
+ }
8446
+ __privateMethod(this, _MmtpFecSession_instances, retireBehindHorizon_fn).call(this);
8447
+ return recovered;
8448
+ }
8449
+ /**
8450
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
8451
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
8452
+ * repair packet fixes its packet ID and a packet of any other is refused.
8453
+ * `path` is where it was received, as for addSource(). `repairTrackName`
8454
+ * is the repair track it was received on, for the 6.3.9 own-track rule; a
8455
+ * track the layers do not list is refused as `repair:unlisted-track`.
8456
+ *
8457
+ * @returns the protected packets this repair symbol recovered, as for
8458
+ * addSource().
8459
+ */
8460
+ addRepair(packet, path = "moq", repairTrackName) {
8461
+ const decoder = __privateGet(this, _decoder);
8462
+ if (!decoder) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:released");
8463
+ if (__privateGet(this, _stats3).failClosed) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:fail-closed");
8464
+ const pathBit = PATH_BITS[path];
8465
+ if (!pathBit) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:unknown-path");
8466
+ let header;
8467
+ try {
8468
+ header = parseMMTPHeader(packet);
8469
+ } catch {
8470
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:malformed");
8471
+ }
8472
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
8473
+ if (!frame) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:malformed");
8474
+ if (__privateGet(this, _repairPacketId) === void 0) {
8475
+ __privateSet(this, _repairPacketId, frame.packetId);
8476
+ } else if (frame.packetId !== __privateGet(this, _repairPacketId)) {
8477
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:foreign-packet-id");
8478
+ }
8479
+ if (frame.symbolData.byteLength !== this.symbolSize) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:symbol-size");
8480
+ if (frame.ssbLength > this.sourceSymbols) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:ssb-length");
8481
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
8482
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:rs-block-length");
8483
+ }
8484
+ const verdict = __privateGet(this, _heldLayers).admit(
8485
+ repairTrackName,
8486
+ frame.ssStart,
8487
+ frame.rsbLength,
8488
+ __privateGet(this, _anchorHorizon),
8489
+ __privateGet(this, _newestSource)
8490
+ );
8491
+ if (verdict === "discard") return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:unlisted-track");
8492
+ if (verdict !== void 0) {
8493
+ __privateGet(this, _stats3).failClosed = verdict;
8494
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:fail-closed");
8495
+ }
8496
+ const start = frame.ssStart;
8497
+ let block = __privateGet(this, _blocks).get(start);
8498
+ if (block && block.ssbLength !== frame.ssbLength) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:conflicting-ssb-length");
8499
+ if (block?.rsIds.has(frame.rsId)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:duplicate");
8500
+ if (!block) {
8501
+ if (__privateGet(this, _settled).has(start)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:block-settled");
8502
+ if (__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, start)) return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:behind-horizon");
8503
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
8504
+ __privateMethod(this, _MmtpFecSession_instances, countHeld_fn).call(this, start, block);
8505
+ __privateGet(this, _blocks).set(start, block);
8506
+ }
8507
+ __privateMethod(this, _MmtpFecSession_instances, noteNewest_fn).call(this, serial32Add(start, frame.ssbLength - 1));
8508
+ if (block.received >= block.ssbLength) {
8509
+ __privateMethod(this, _MmtpFecSession_instances, settleClean_fn).call(this, start);
8510
+ __privateMethod(this, _MmtpFecSession_instances, retireBehindHorizon_fn).call(this);
8511
+ return [];
8512
+ }
8513
+ let output;
8514
+ try {
8515
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
8516
+ } catch {
8517
+ return __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "repair:decoder-refused");
8518
+ }
8519
+ block.rsIds.add(frame.rsId);
8520
+ __privateGet(this, _stats3).repairSymbols++;
8521
+ __privateGet(this, _stats3).repairSymbolsByPath[path]++;
8522
+ block.paths |= pathBit;
8523
+ const recovered = output ? __privateMethod(this, _MmtpFecSession_instances, settleDecoded_fn).call(this, start, block, output) : [];
8524
+ __privateMethod(this, _MmtpFecSession_instances, retireBehindHorizon_fn).call(this);
8525
+ return recovered;
8526
+ }
8527
+ /**
8528
+ * Frees the decoder and every block. Blocks still unsettled are counted as
8529
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
8530
+ * returns whether this call released anything.
8531
+ */
8532
+ release() {
8533
+ const decoder = __privateGet(this, _decoder);
8534
+ if (!decoder) return false;
8535
+ __privateSet(this, _decoder, null);
8536
+ __privateGet(this, _stats3).blocksReleased += __privateGet(this, _blocks).size;
8537
+ for (const block of __privateGet(this, _blocks).values()) __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "released");
8538
+ __privateGet(this, _blocks).clear();
8539
+ __privateGet(this, _settled).clear();
8540
+ __privateGet(this, _have).clear();
8541
+ decoder.free();
8542
+ return true;
8543
+ }
8544
+ };
8545
+ _decoder = new WeakMap();
8546
+ _blocks = new WeakMap();
8547
+ _settled = new WeakMap();
8548
+ _have = new WeakMap();
8549
+ _newest = new WeakMap();
8550
+ _prunedAt = new WeakMap();
8551
+ _repairPacketId = new WeakMap();
8552
+ _newestSource = new WeakMap();
8553
+ _heldLayers = new WeakMap();
8554
+ _anchorHorizon = new WeakMap();
8555
+ _stats3 = new WeakMap();
8556
+ _MmtpFecSession_instances = new WeakSet();
8557
+ drop_fn2 = function(reason) {
8558
+ __privateGet(this, _stats3).dropped[reason] = (__privateGet(this, _stats3).dropped[reason] ?? 0) + 1;
8559
+ return [];
8560
+ };
8561
+ noteNewest_fn = function(ssId) {
8562
+ if (__privateGet(this, _newest) === void 0 || serial32Precedes(__privateGet(this, _newest), ssId)) __privateSet(this, _newest, ssId);
8563
+ };
8564
+ blockStartOf_fn = function(ssId) {
8565
+ for (const [start, block] of __privateGet(this, _blocks)) {
8566
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
8567
+ }
8568
+ return void 0;
8569
+ };
8570
+ /** Counts the sources of a new block the parser already has, and their paths. */
8571
+ countHeld_fn = function(start, block) {
8572
+ for (let i = 0; i < block.ssbLength; i++) {
8573
+ const pathBit = __privateGet(this, _have).get(serial32Add(start, i));
8574
+ if (pathBit === void 0) continue;
8575
+ block.received++;
8576
+ block.paths |= pathBit;
8577
+ }
8578
+ };
8579
+ noteMixed_fn = function(block, outcome) {
8580
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) __privateGet(this, _stats3).mixedPath[outcome]++;
8581
+ };
8582
+ /** The decoder's own rule: more than its retention behind, counted from below. */
8583
+ behindHorizon_fn = function(start) {
8584
+ const newest = __privateGet(this, _newest);
8585
+ if (newest === void 0) return false;
8586
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
8587
+ };
8588
+ settle_fn = function(start) {
8589
+ __privateGet(this, _blocks).delete(start);
8590
+ __privateGet(this, _settled).add(start);
8591
+ };
8592
+ settleClean_fn = function(start) {
8593
+ const block = __privateGet(this, _blocks).get(start);
8594
+ if (!block) return;
8595
+ __privateMethod(this, _MmtpFecSession_instances, settle_fn).call(this, start);
8596
+ __privateGet(this, _stats3).blocksClean++;
8597
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "clean");
8598
+ try {
8599
+ __privateGet(this, _decoder)?.cleanup_blocks_detailed(Uint32Array.of(start));
8600
+ } catch {
8601
+ }
8602
+ };
8603
+ /**
8604
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
8605
+ * concatenated: split by T, trim by each symbol's length field, and hand
8606
+ * back the packets the parser does not have yet.
8607
+ */
8608
+ settleDecoded_fn = function(start, block, output) {
8609
+ __privateMethod(this, _MmtpFecSession_instances, settle_fn).call(this, start);
8610
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
8611
+ __privateGet(this, _stats3).blocksFailed++;
8612
+ __privateGet(this, _stats3).packetsLost += block.ssbLength - block.received;
8613
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "failed");
8614
+ __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "block:decoded-length");
8615
+ return [];
8616
+ }
8617
+ const recovered = [];
8618
+ let refused = 0;
8619
+ for (let i = 0; i < block.ssbLength; i++) {
8620
+ const ssId = serial32Add(start, i);
8621
+ if (__privateGet(this, _have).has(ssId)) continue;
8622
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
8623
+ const packet = trimSsbg1SourceSymbol(symbol);
8624
+ if (!packet) {
8625
+ refused++;
8626
+ continue;
8627
+ }
8628
+ __privateGet(this, _have).set(ssId, 0);
8629
+ recovered.push(packet.slice());
8630
+ }
8631
+ if (refused > 0) {
8632
+ __privateGet(this, _stats3).blocksFailed++;
8633
+ __privateGet(this, _stats3).packetsLost += refused;
8634
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "failed");
8635
+ __privateMethod(this, _MmtpFecSession_instances, drop_fn2).call(this, "block:bad-ssbg1-symbol");
8636
+ } else if (recovered.length === 0) {
8637
+ __privateGet(this, _stats3).blocksClean++;
8638
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "clean");
8639
+ } else {
8640
+ __privateGet(this, _stats3).blocksRecovered++;
8641
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "recovered");
8642
+ }
8643
+ __privateGet(this, _stats3).packetsRecovered += recovered.length;
8644
+ return recovered;
8645
+ };
8646
+ /**
8647
+ * Retires every block, and every SS_ID the session remembers, that the
8648
+ * newest SS_ID has moved past the retention. An unsettled block retired
8649
+ * here is a failure: more of its sources were lost than its repair could
8650
+ * restore, or its repair never arrived.
8651
+ */
8652
+ retireBehindHorizon_fn = function() {
8653
+ const decoder = __privateGet(this, _decoder);
8654
+ const newest = __privateGet(this, _newest);
8655
+ if (!decoder || newest === void 0) return;
8656
+ try {
8657
+ decoder.cleanup_by_ss_start(newest);
8658
+ } catch {
8659
+ }
8660
+ for (const [start, block] of __privateGet(this, _blocks)) {
8661
+ if (!__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, start)) continue;
8662
+ __privateMethod(this, _MmtpFecSession_instances, settle_fn).call(this, start);
8663
+ __privateGet(this, _stats3).blocksFailed++;
8664
+ __privateGet(this, _stats3).packetsLost += block.ssbLength - block.received;
8665
+ __privateMethod(this, _MmtpFecSession_instances, noteMixed_fn).call(this, block, "failed");
8666
+ }
8667
+ const prunedAt = __privateGet(this, _prunedAt);
8668
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
8669
+ __privateSet(this, _prunedAt, newest);
8670
+ for (const ssId of __privateGet(this, _have).keys()) {
8671
+ if (__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, ssId)) __privateGet(this, _have).delete(ssId);
8672
+ }
8673
+ for (const start of __privateGet(this, _settled)) {
8674
+ if (__privateMethod(this, _MmtpFecSession_instances, behindHorizon_fn).call(this, start)) __privateGet(this, _settled).delete(start);
8675
+ }
8676
+ };
8677
+ function requirePositiveInteger(value, path) {
8678
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
8679
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
8680
+ }
8681
+ return value;
8682
+ }
8683
+ function requireNumber(value, path) {
8684
+ if (typeof value !== "number") {
8685
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
8686
+ }
8687
+ return value;
8688
+ }
8689
+
8690
+ // src/catalog-network-source.ts
8691
+ function normalizePort(value) {
8692
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
8693
+ return Number.isInteger(n) && n > 0 && n <= 65535 ? n : void 0;
8694
+ }
8695
+ function catalogAmtNetworkSource(networkSource) {
8696
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8697
+ for (const raw of entries) {
8698
+ if (!raw || typeof raw !== "object") continue;
8699
+ const ns = raw;
8700
+ if (ns.type !== "amt") continue;
8701
+ if (ns.discovery === "driad") continue;
8702
+ const relay = typeof ns.relay === "string" ? ns.relay.trim() : "";
8703
+ if (!relay) continue;
8704
+ return { relay, port: normalizePort(ns.port) ?? DEFAULT_AMT_RELAY_PORT };
8705
+ }
8706
+ return void 0;
8707
+ }
8708
+ function intIn(value, min, max) {
8709
+ return Number.isInteger(value) && value >= min && value <= max;
8710
+ }
8711
+ function catalogAtsc3NetworkSource(networkSource) {
8712
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8713
+ for (const raw of entries) {
8714
+ if (!raw || typeof raw !== "object") continue;
8715
+ const ns = raw;
8716
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
8717
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
8718
+ return {
8719
+ frequency: ns.frequency,
8720
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
8721
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
8722
+ ...slsUri ? { slsUri } : {}
8723
+ };
8724
+ }
8725
+ return void 0;
8726
+ }
8727
+
7891
8728
  // src/mmtp-to-cmaf.ts
7892
8729
  function box(type, ...children2) {
7893
8730
  let size = 8;
@@ -7930,8 +8767,8 @@ var BlockcastMmt = (() => {
7930
8767
  }
7931
8768
  var KEYFRAME_FLAGS = 33554432;
7932
8769
  var DELTA_FLAGS = 16842752;
7933
- var UINT32_MAX = 4294967295;
7934
- var MAX_TRACK_ID = UINT32_MAX - 1;
8770
+ var UINT32_MAX2 = 4294967295;
8771
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
7935
8772
  var INT32_MIN = -2147483648;
7936
8773
  var INT32_MAX = 2147483647;
7937
8774
  function assertTrackId(trackId, label) {
@@ -7940,8 +8777,8 @@ var BlockcastMmt = (() => {
7940
8777
  }
7941
8778
  }
7942
8779
  function assertTimescale(timescale, label) {
7943
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
7944
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
8780
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
8781
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
7945
8782
  }
7946
8783
  }
7947
8784
  function assertCompositionTimeOffsets(samples) {
@@ -9005,7 +9842,7 @@ var BlockcastMmt = (() => {
9005
9842
  var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
9006
9843
  var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
9007
9844
  var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
9008
- var SOURCE_AUTH_SCOPE_LENGTH2 = 32;
9845
+ var SOURCE_AUTH_SCOPE_LENGTH = 32;
9009
9846
  var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
9010
9847
  function requireBytes(name, value, length) {
9011
9848
  if (value.byteLength !== length) {
@@ -9082,7 +9919,7 @@ var BlockcastMmt = (() => {
9082
9919
  throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
9083
9920
  }
9084
9921
  requireU64("groupId", groupId);
9085
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH2);
9922
+ requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
9086
9923
  requireBytes("root", root, 32);
9087
9924
  const preimage = new Uint8Array(100);
9088
9925
  const view2 = new DataView(preimage.buffer);
@@ -9133,6 +9970,20 @@ var BlockcastMmt = (() => {
9133
9970
  }
9134
9971
 
9135
9972
  // ../mmt-manifest-verify/dist/verifier.js
9973
+ function manifestKeyFor(keys, epoch, kid) {
9974
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length)
9975
+ return void 0;
9976
+ if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
9977
+ return void 0;
9978
+ let signer;
9979
+ for (const key of keys) {
9980
+ if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
9981
+ signer = key;
9982
+ }
9983
+ if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
9984
+ return void 0;
9985
+ return signer.publicKey;
9986
+ }
9136
9987
  function manifestBindingId(trackName, sourceSymbolFormat) {
9137
9988
  return JSON.stringify([trackName, sourceSymbolFormat]);
9138
9989
  }
@@ -9161,7 +10012,7 @@ var BlockcastMmt = (() => {
9161
10012
  return diff === 0;
9162
10013
  };
9163
10014
  var isPromiseLike = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
9164
- 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;
10015
+ 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;
9165
10016
  var ManifestVerifier = class {
9166
10017
  constructor(options) {
9167
10018
  __privateAdd(this, _ManifestVerifier_instances);
@@ -9169,7 +10020,7 @@ var BlockcastMmt = (() => {
9169
10020
  __privateAdd(this, _verifySignature);
9170
10021
  __privateAdd(this, _onFailure);
9171
10022
  __privateAdd(this, _tracks2, /* @__PURE__ */ new Map());
9172
- __privateAdd(this, _stats3, {
10023
+ __privateAdd(this, _stats4, {
9173
10024
  verified: 0,
9174
10025
  failures: Object.fromEntries(FAILURE_REASONS.map((reason) => [reason, 0])),
9175
10026
  quarantinedBytes: 0
@@ -9187,10 +10038,10 @@ var BlockcastMmt = (() => {
9187
10038
  for (const track of __privateGet(this, _tracks2).values())
9188
10039
  quarantined += track.quarantine.length;
9189
10040
  return {
9190
- verified: __privateGet(this, _stats3).verified,
9191
- failures: { ...__privateGet(this, _stats3).failures },
10041
+ verified: __privateGet(this, _stats4).verified,
10042
+ failures: { ...__privateGet(this, _stats4).failures },
9192
10043
  quarantined,
9193
- quarantinedBytes: __privateGet(this, _stats3).quarantinedBytes
10044
+ quarantinedBytes: __privateGet(this, _stats4).quarantinedBytes
9194
10045
  };
9195
10046
  }
9196
10047
  setMode(mode) {
@@ -9211,11 +10062,12 @@ var BlockcastMmt = (() => {
9211
10062
  }
9212
10063
  if (context.authScope.byteLength !== 32)
9213
10064
  throw new Error("manifest authScope must be 32 bytes");
9214
- if (context.publicKey.byteLength !== 32)
9215
- throw new Error("manifest publicKey must be 32 bytes");
9216
- for (const key of context.acceptedPublicKeys ?? []) {
9217
- if (key.byteLength !== 32)
9218
- throw new Error("manifest acceptedPublicKeys must contain 32-byte keys");
10065
+ for (const key of context.keys) {
10066
+ if (key.publicKey.byteLength !== 32)
10067
+ throw new Error("manifest keys must carry 32-byte public keys");
10068
+ }
10069
+ if (manifestKeyFor(context.keys, context.keyEpoch) === void 0) {
10070
+ throw new Error(`manifest keys hold no key set signing keyEpoch ${context.keyEpoch}`);
9219
10071
  }
9220
10072
  for (const [name, value] of Object.entries({
9221
10073
  broadcastNamespaceId: context.broadcastNamespaceId,
@@ -9325,7 +10177,7 @@ var BlockcastMmt = (() => {
9325
10177
  _verifySignature = new WeakMap();
9326
10178
  _onFailure = new WeakMap();
9327
10179
  _tracks2 = new WeakMap();
9328
- _stats3 = new WeakMap();
10180
+ _stats4 = new WeakMap();
9329
10181
  _disposed2 = new WeakMap();
9330
10182
  _ManifestVerifier_instances = new WeakSet();
9331
10183
  requireTrack_fn = function(bindingId) {
@@ -9377,7 +10229,7 @@ var BlockcastMmt = (() => {
9377
10229
  return { action: "stall", verified: false };
9378
10230
  }
9379
10231
  release();
9380
- __privateGet(this, _stats3).verified++;
10232
+ __privateGet(this, _stats4).verified++;
9381
10233
  return { action: "play", verified: true };
9382
10234
  };
9383
10235
  rejectOrShadow_fn = function(identity, release, reason) {
@@ -9468,7 +10320,7 @@ var BlockcastMmt = (() => {
9468
10320
  }
9469
10321
  };
9470
10322
  verifyAcceptedSignature_fn = function(track, message, signature) {
9471
- const keys = track.context.acceptedPublicKeys ?? [track.context.publicKey];
10323
+ const keys = [manifestKeyFor(track.context.keys, track.context.keyEpoch)];
9472
10324
  const pending = [];
9473
10325
  let hadSynchronousError = false;
9474
10326
  for (const key of keys) {
@@ -9517,7 +10369,7 @@ var BlockcastMmt = (() => {
9517
10369
  if (index >= 0)
9518
10370
  track.quarantine.splice(index, 1);
9519
10371
  track.quarantinedBytes -= pending.bytes;
9520
- __privateGet(this, _stats3).quarantinedBytes -= pending.bytes;
10372
+ __privateGet(this, _stats4).quarantinedBytes -= pending.bytes;
9521
10373
  };
9522
10374
  quarantine_fn = function(track, group, pending) {
9523
10375
  if (group.pending.has(pending.identity.objectId))
@@ -9525,7 +10377,7 @@ var BlockcastMmt = (() => {
9525
10377
  group.pending.set(pending.identity.objectId, pending);
9526
10378
  track.quarantine.push(pending);
9527
10379
  track.quarantinedBytes += pending.bytes;
9528
- __privateGet(this, _stats3).quarantinedBytes += pending.bytes;
10380
+ __privateGet(this, _stats4).quarantinedBytes += pending.bytes;
9529
10381
  __privateMethod(this, _ManifestVerifier_instances, enforceCap_fn).call(this, track);
9530
10382
  return true;
9531
10383
  };
@@ -9536,7 +10388,7 @@ var BlockcastMmt = (() => {
9536
10388
  if (group)
9537
10389
  group.pending.delete(pending.identity.objectId);
9538
10390
  track.quarantinedBytes -= pending.bytes;
9539
- __privateGet(this, _stats3).quarantinedBytes -= pending.bytes;
10391
+ __privateGet(this, _stats4).quarantinedBytes -= pending.bytes;
9540
10392
  __privateMethod(this, _ManifestVerifier_instances, giveUpOnPending_fn).call(this, pending);
9541
10393
  __privateMethod(this, _ManifestVerifier_instances, failure_fn).call(this, pending.identity, "manifestAbsent");
9542
10394
  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"}`);
@@ -9593,7 +10445,7 @@ var BlockcastMmt = (() => {
9593
10445
  };
9594
10446
  failure_fn = function(identity, reason) {
9595
10447
  var _a;
9596
- __privateGet(this, _stats3).failures[reason]++;
10448
+ __privateGet(this, _stats4).failures[reason]++;
9597
10449
  (_a = __privateGet(this, _onFailure)) == null ? void 0 : _a.call(this, {
9598
10450
  trackName: identity.trackName,
9599
10451
  ...identity.bindingId === void 0 ? {} : { bindingId: identity.bindingId },
@@ -9603,59 +10455,140 @@ var BlockcastMmt = (() => {
9603
10455
  });
9604
10456
  };
9605
10457
 
9606
- // src/manifest-auth-plan.ts
9607
- function createManifestAuthPlan(catalog, options) {
9608
- const resolved = resolveMulticastAuthCatalog(catalog, options.playerMode);
9609
- if (!resolved || resolved.mode === "off") return void 0;
9610
- const verifier = new ManifestVerifier({
9611
- manifestAuth: {
9612
- mode: resolved.mode,
9613
- onMissingManifest: options.onMissingManifest ?? (resolved.mode === "enforce" ? "stall" : "fallback-shadow")
9614
- },
9615
- verifySignature: options.verifySignature,
9616
- ...options.onFailure === void 0 ? {} : { onFailure: options.onFailure }
9617
- });
9618
- const byManifestTrack = /* @__PURE__ */ new Map();
9619
- const bindings = resolved.tracks.map((binding) => {
9620
- const bindingId = manifestBindingId(binding.mediaTrack, binding.sourceSymbolFormat);
9621
- const planned = {
9622
- bindingId,
9623
- mediaTrack: binding.mediaTrack,
9624
- manifestTrack: binding.manifestTrack,
9625
- sourceSymbolFormat: binding.sourceSymbolFormat
9626
- };
9627
- verifier.registerTrack({
9628
- ...options.contextFor(binding, resolved),
9629
- bindingId,
9630
- trackName: binding.mediaTrack,
9631
- sourceSymbolFormat: binding.sourceSymbolFormat,
9632
- authScope: binding.authScope,
9633
- publicKey: resolved.acceptedPublicKeys[0],
9634
- acceptedPublicKeys: resolved.acceptedPublicKeys
10458
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10459
+ var BCPV2_HEADER_LENGTH = 68;
10460
+ var BCPV2_SIGNATURE_LENGTH = 64;
10461
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10462
+ var text = new TextEncoder();
10463
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10464
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10465
+
10466
+ // src/multicast-auth-catalog.ts
10467
+ var RAW_ED25519_KEY_LENGTH = 32;
10468
+ var DEFAULT_MAX_AUTH_DELAY_MS = 200;
10469
+ var DEFAULT_MANIFEST_TIMER_MS = 20;
10470
+ var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10471
+ function encodeBase64Url(bytes) {
10472
+ let output = "";
10473
+ for (let i = 0; i < bytes.length; i += 3) {
10474
+ const b0 = bytes[i];
10475
+ const b1 = bytes[i + 1];
10476
+ const b2 = bytes[i + 2];
10477
+ output += BASE64URL_ALPHABET[b0 >> 2];
10478
+ output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
10479
+ if (b1 === void 0) break;
10480
+ output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
10481
+ if (b2 === void 0) break;
10482
+ output += BASE64URL_ALPHABET[b2 & 63];
10483
+ }
10484
+ return output;
10485
+ }
10486
+ var BASE64URL_DECODE_TABLE = (() => {
10487
+ const table = new Int8Array(128).fill(-1);
10488
+ for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
10489
+ table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
10490
+ }
10491
+ return table;
10492
+ })();
10493
+ function decodeBase64Url(text2) {
10494
+ if (text2.length % 4 === 1) {
10495
+ throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
10496
+ }
10497
+ const bytes = [];
10498
+ let buffer = 0;
10499
+ let bits = 0;
10500
+ for (let i = 0; i < text2.length; i++) {
10501
+ const code = text2.charCodeAt(i);
10502
+ const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
10503
+ if (value === void 0 || value < 0) {
10504
+ throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
10505
+ }
10506
+ buffer = buffer << 6 | value;
10507
+ bits += 6;
10508
+ if (bits >= 8) {
10509
+ bits -= 8;
10510
+ bytes.push(buffer >> bits & 255);
10511
+ }
10512
+ }
10513
+ const decoded = Uint8Array.from(bytes);
10514
+ if (encodeBase64Url(decoded) !== text2) {
10515
+ throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
10516
+ }
10517
+ return decoded;
10518
+ }
10519
+ function decodeEd25519PublicKey(publicKey) {
10520
+ const bytes = decodeBase64Url(publicKey);
10521
+ if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
10522
+ throw new Error(
10523
+ `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
10524
+ );
10525
+ }
10526
+ return bytes;
10527
+ }
10528
+ function resolveMulticastAuthCatalog(catalog, options = {}) {
10529
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
10530
+ throw new Error("[multicast-auth-catalog] catalog must be an object");
10531
+ }
10532
+ const issues = multicastCatalogIssues(catalog, options);
10533
+ const fatal = issues.find((issue) => issue.endpointIndex === void 0);
10534
+ if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
10535
+ const multicast = catalog["multicast"];
10536
+ const auth = multicast?.["auth"];
10537
+ if (auth === void 0) {
10538
+ if (options.requireAuth) {
10539
+ throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
10540
+ }
10541
+ return void 0;
10542
+ }
10543
+ const ignored = new Set(issues.map((issue) => issue.endpointIndex));
10544
+ const endpoints = multicast["endpoints"] ?? [];
10545
+ const flows = [];
10546
+ endpoints.forEach((endpoint, endpointIndex) => {
10547
+ if (ignored.has(endpointIndex)) return;
10548
+ const flowAuth = endpoint["auth"];
10549
+ flows.push({
10550
+ endpointIndex,
10551
+ source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
10552
+ groupAddress: endpoint["groupAddress"],
10553
+ port: endpoint["port"],
10554
+ bandwidth: endpoint["bandwidth"],
10555
+ manifestPort: flowAuth.manifestPort,
10556
+ streamId: flowAuth.streamId,
10557
+ maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
10558
+ manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
10559
+ ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
10560
+ tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
10561
+ name,
10562
+ packetId
10563
+ }))
9635
10564
  });
9636
- byManifestTrack.set(binding.manifestTrack, planned);
9637
- return planned;
9638
10565
  });
9639
- let disposed = false;
9640
10566
  return {
9641
- verifier,
9642
- mode: resolved.mode,
9643
- bindings,
10567
+ keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
10568
+ minEpoch: auth.minEpoch,
10569
+ flows
10570
+ };
10571
+ }
10572
+ function multicastAuthKeyFor(resolved, kid, epoch) {
10573
+ return manifestKeyFor(resolved.keys, epoch, kid);
10574
+ }
10575
+
10576
+ // src/manifest-auth-plan.ts
10577
+ function createManifestAuthPlan(catalog, options = {}) {
10578
+ const resolved = resolveMulticastAuthCatalog(catalog, options);
10579
+ if (!resolved) return void 0;
10580
+ const byManifestTrack = /* @__PURE__ */ new Map();
10581
+ for (const flow of resolved.flows) {
10582
+ if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
10583
+ }
10584
+ return {
10585
+ keys: resolved.keys,
10586
+ minEpoch: resolved.minEpoch,
10587
+ flows: resolved.flows,
9644
10588
  manifestTracks: [...byManifestTrack.keys()],
9645
- bindingIdFor(mediaTrack, sourceSymbolFormat) {
9646
- const bindingId = manifestBindingId(mediaTrack, sourceSymbolFormat);
9647
- return bindings.some((binding) => binding.bindingId === bindingId) ? bindingId : void 0;
9648
- },
9649
- ingestManifestPayload(manifestTrack, payload) {
9650
- const binding = byManifestTrack.get(manifestTrack);
9651
- if (!binding) throw new Error(`unknown manifest subscription track ${manifestTrack}`);
9652
- verifier.ingestManifestFrame(binding.bindingId, payload);
9653
- },
9654
- dispose() {
9655
- if (disposed) return;
9656
- disposed = true;
9657
- verifier.dispose();
9658
- }
10589
+ keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
10590
+ flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
10591
+ flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
9659
10592
  };
9660
10593
  }
9661
10594
  return __toCommonJS(no_modules_exports);