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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/README.md +31 -17
  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 +1192 -375
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +67 -31
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +291 -199
  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 +24 -2
  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/delivery-catalog.js +18 -12
  25. package/dist/delivery-catalog.js.map +4 -4
  26. package/dist/fec-manager.d.ts +49 -1
  27. package/dist/fec-manager.d.ts.map +1 -1
  28. package/dist/fec-manager.js +176 -23
  29. package/dist/fec-manager.js.map +3 -3
  30. package/dist/fec-state.d.ts +2 -1
  31. package/dist/fec-state.d.ts.map +1 -1
  32. package/dist/fec-state.js +18 -3
  33. package/dist/fec-state.js.map +3 -3
  34. package/dist/fec-worker-setup.d.ts +2 -0
  35. package/dist/fec-worker-setup.d.ts.map +1 -1
  36. package/dist/fec-worker-setup.js +2 -1
  37. package/dist/fec-worker-setup.js.map +2 -2
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +8 -8
  41. package/dist/index.js.map +2 -2
  42. package/dist/iso-block-locator.d.ts +29 -0
  43. package/dist/iso-block-locator.d.ts.map +1 -1
  44. package/dist/iso-block-locator.js +97 -17
  45. package/dist/iso-block-locator.js.map +3 -3
  46. package/dist/manifest-auth-plan.d.ts +26 -25
  47. package/dist/manifest-auth-plan.d.ts.map +1 -1
  48. package/dist/manifest-auth-plan.js +331 -1171
  49. package/dist/manifest-auth-plan.js.map +4 -4
  50. package/dist/mfu-reassembler.js.map +2 -2
  51. package/dist/mmtp-container-parser.js.map +2 -2
  52. package/dist/mmtp-container-parser.no-modules.js +1014 -289
  53. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  54. package/dist/mmtp-decode-pipeline.js.map +2 -2
  55. package/dist/mmtp-fec-session.d.ts +159 -0
  56. package/dist/mmtp-fec-session.d.ts.map +1 -0
  57. package/dist/mmtp-fec-session.js +531 -0
  58. package/dist/mmtp-fec-session.js.map +7 -0
  59. package/dist/mmtp-router.d.ts +17 -1
  60. package/dist/mmtp-router.d.ts.map +1 -1
  61. package/dist/mmtp-router.js +29 -0
  62. package/dist/mmtp-router.js.map +2 -2
  63. package/dist/multicast-auth-catalog.d.ts +86 -92
  64. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  65. package/dist/multicast-auth-catalog.js +347 -132
  66. package/dist/multicast-auth-catalog.js.map +4 -4
  67. package/dist/multicast-input.d.ts +28 -6
  68. package/dist/multicast-input.d.ts.map +1 -1
  69. package/dist/multicast-input.js +290 -28
  70. package/dist/multicast-input.js.map +3 -3
  71. package/dist/multicast-manager.d.ts +40 -5
  72. package/dist/multicast-manager.d.ts.map +1 -1
  73. package/dist/multicast-manager.js +293 -54
  74. package/dist/multicast-manager.js.map +4 -4
  75. package/dist/multicast-transport.d.ts +6 -0
  76. package/dist/multicast-transport.d.ts.map +1 -1
  77. package/dist/multicast-transport.js +18 -11
  78. package/dist/multicast-transport.js.map +4 -4
  79. package/dist/multicast-unwrap.js.map +2 -2
  80. package/dist/no-modules.d.ts +4 -1
  81. package/dist/no-modules.d.ts.map +1 -1
  82. package/dist/no-modules.js +964 -274
  83. package/dist/no-modules.js.map +4 -4
  84. package/dist/phase14-catalog-override.d.ts +1 -1
  85. package/dist/phase14-catalog-override.d.ts.map +1 -1
  86. package/dist/phase14-catalog-override.js +2 -2
  87. package/dist/phase14-catalog-override.js.map +2 -2
  88. package/dist/repair-fetch.d.ts +81 -6
  89. package/dist/repair-fetch.d.ts.map +1 -1
  90. package/dist/repair-fetch.js +156 -31
  91. package/dist/repair-fetch.js.map +3 -3
  92. package/dist/repair-layers.d.ts +2 -0
  93. package/dist/repair-layers.d.ts.map +1 -1
  94. package/dist/repair-layers.js +19 -2
  95. package/dist/repair-layers.js.map +2 -2
  96. package/dist/signaling.d.ts +2 -2
  97. package/dist/signaling.d.ts.map +1 -1
  98. package/dist/signaling.js +3 -3
  99. package/dist/signaling.js.map +2 -2
  100. package/dist/source-auth.js +2710 -7
  101. package/dist/source-auth.js.map +4 -4
  102. package/dist/switching-set-alignment.d.ts +1 -1
  103. package/dist/switching-set-alignment.js.map +1 -1
  104. package/dist/timestamp-codec.js.map +2 -2
  105. package/dist/wasm-mfu-reassembler.js.map +1 -1
  106. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  107. package/package.json +6 -9
  108. package/schemas/catalog.schema.json +124 -37
  109. package/src/align.ts +52 -21
  110. package/src/carp-catalog.ts +131 -52
  111. package/src/catalog-fec-params.ts +28 -3
  112. package/src/catalog-network-source.ts +45 -2
  113. package/src/catalog-validator.ts +4 -11
  114. package/src/fec-manager.ts +128 -14
  115. package/src/fec-state.ts +11 -4
  116. package/src/fec-worker-setup.ts +4 -1
  117. package/src/index.ts +24 -10
  118. package/src/iso-block-locator.ts +97 -6
  119. package/src/manifest-auth-plan.ts +39 -91
  120. package/src/mmtp-fec-session.ts +533 -0
  121. package/src/mmtp-router.ts +57 -0
  122. package/src/multicast-auth-catalog.ts +131 -238
  123. package/src/multicast-input.ts +119 -61
  124. package/src/multicast-manager.ts +115 -14
  125. package/src/multicast-transport.ts +3 -0
  126. package/src/no-modules.ts +7 -1
  127. package/src/phase14-catalog-override.ts +3 -3
  128. package/src/repair-fetch.ts +283 -39
  129. package/src/repair-layers.ts +22 -2
  130. package/src/signaling.ts +2 -2
  131. package/src/switching-set-alignment.ts +1 -1
  132. package/test-vectors/align.json +108 -32
  133. package/test-vectors/bc-provenance-v2.json +1526 -0
  134. package/test-vectors/catalog/README.md +60 -3
  135. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  136. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  137. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  138. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  139. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  140. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  141. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  142. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  143. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  144. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  145. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  146. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  147. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  148. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  149. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  150. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  151. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  152. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  153. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  154. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  155. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  156. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  157. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  158. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  159. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  160. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  161. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  162. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  163. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  164. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  165. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  166. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  167. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  168. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  169. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  170. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  171. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  172. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  173. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  174. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  175. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +2 -2
  176. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  177. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  178. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  179. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  180. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  181. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  182. package/test-vectors/catalog/section-codes.json +30 -1
  183. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  184. package/test-vectors/catalog-validation.json +6 -5
  185. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  186. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  187. package/dist/fec-codec.d.ts +0 -32
  188. package/dist/fec-codec.d.ts.map +0 -1
  189. package/dist/fec-codec.js +0 -47
  190. package/dist/fec-codec.js.map +0 -7
  191. package/src/fec-codec.ts +0 -61
@@ -289,12 +289,86 @@ function sourceFecPayloadIdOf(mmtpPacket, header) {
289
289
  ssId: (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0
290
290
  };
291
291
  }
292
+ var REPAIR_FEC_PID_SIZE = 13;
293
+ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
294
+ let header;
295
+ if (parsedHeader) {
296
+ header = parsedHeader;
297
+ } else {
298
+ try {
299
+ header = parseMMTPHeader(mmtpPacket);
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
304
+ if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2)
305
+ return null;
306
+ const off = header.headerLength;
307
+ if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE)
308
+ return null;
309
+ const ssStart = (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0;
310
+ const rsbLength = mmtpPacket[off + 4] << 16 | mmtpPacket[off + 5] << 8 | mmtpPacket[off + 6];
311
+ const rsId = mmtpPacket[off + 7] << 16 | mmtpPacket[off + 8] << 8 | mmtpPacket[off + 9];
312
+ const ssbLength = mmtpPacket[off + 10] << 16 | mmtpPacket[off + 11] << 8 | mmtpPacket[off + 12];
313
+ return {
314
+ packetId: header.packetId,
315
+ ssStart,
316
+ rsbLength,
317
+ rsId,
318
+ ssbLength,
319
+ dataOffset: off + REPAIR_FEC_PID_SIZE
320
+ };
321
+ }
322
+ function parseMoqRepairFrameWithHeader(frame, header) {
323
+ return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header));
324
+ }
325
+ function moqRepairFrameFrom(frame, repairId) {
326
+ if (!repairId)
327
+ return null;
328
+ const symbolData = frame.subarray(repairId.dataOffset);
329
+ if (repairId.rsbLength === 0 || repairId.ssbLength === 0 || repairId.rsId >= repairId.rsbLength || symbolData.length === 0)
330
+ return null;
331
+ return {
332
+ packetId: repairId.packetId,
333
+ ssStart: repairId.ssStart,
334
+ rsbLength: repairId.rsbLength,
335
+ rsId: repairId.rsId,
336
+ ssbLength: repairId.ssbLength,
337
+ symbolData
338
+ };
339
+ }
340
+
341
+ // ../mmt-base/dist/net-constants.js
342
+ var DEFAULT_AMT_RELAY_PORT = 2268;
292
343
 
293
344
  // ../mmt-base/dist/ntp-short.js
294
345
  var NTP_SHORT_BITS = 32;
295
346
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
296
347
  var NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1);
297
348
 
349
+ // ../mmt-base/dist/serial-number.js
350
+ var SERIAL32_SPAN = 4294967296;
351
+ var SERIAL32_HALF = 2147483648;
352
+ function assertUint32(value, name) {
353
+ if (!Number.isInteger(value) || value < 0 || value >= SERIAL32_SPAN) {
354
+ throw new RangeError(`${name} must be a uint32 (got ${value})`);
355
+ }
356
+ }
357
+ function serial32Add(s, n) {
358
+ assertUint32(s, "s");
359
+ if (!Number.isInteger(n) || n <= -SERIAL32_HALF || n >= SERIAL32_HALF) {
360
+ throw new RangeError(`serial addend must lie in (-2^31, 2^31) (got ${n})`);
361
+ }
362
+ return (s + n + SERIAL32_SPAN) % SERIAL32_SPAN;
363
+ }
364
+ function serial32Distance(from, to) {
365
+ return to - from >>> 0;
366
+ }
367
+ function serial32Precedes(a, b) {
368
+ const distance = serial32Distance(a, b);
369
+ return distance !== 0 && distance < SERIAL32_HALF;
370
+ }
371
+
298
372
  // ../mmt-base/dist/fec-block-profile.js
299
373
  var FEC_BLOCK_PROFILES = Object.freeze([
300
374
  "iso-ssbg1-v1"
@@ -310,6 +384,35 @@ function parseFecBlockProfile(value, where) {
310
384
  }
311
385
  throw new Error(`${where} must be "iso-ssbg1-v1" (got ${JSON.stringify(value)})`);
312
386
  }
387
+ var SSBG1_LENGTH_FIELD_BYTES = 2;
388
+ function ssbg1MaxPacketLength(symbolSize) {
389
+ return symbolSize - SSBG1_LENGTH_FIELD_BYTES;
390
+ }
391
+ function ssbg1FitsSymbol(packetLength, symbolSize) {
392
+ return Number.isSafeInteger(packetLength) && packetLength >= 0 && packetLength <= ssbg1MaxPacketLength(symbolSize) && packetLength <= 65535;
393
+ }
394
+ function trimSsbg1SourceSymbol(symbol) {
395
+ if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES)
396
+ return null;
397
+ const length = symbol[0] << 8 | symbol[1];
398
+ const end = SSBG1_LENGTH_FIELD_BYTES + length;
399
+ if (end > symbol.byteLength)
400
+ return null;
401
+ for (let i = end; i < symbol.byteLength; i++) {
402
+ if (symbol[i] !== 0)
403
+ return null;
404
+ }
405
+ return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end);
406
+ }
407
+ function isoBlockContains(ssStart, ssbLength, ssId) {
408
+ return serial32Distance(ssStart, ssId) < ssbLength;
409
+ }
410
+ function isoBlocksBehindLowerBound(a, b, kMax) {
411
+ if (!Number.isSafeInteger(kMax) || kMax <= 0) {
412
+ throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`);
413
+ }
414
+ return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
415
+ }
313
416
 
314
417
  // ../mmt-base/dist/catalog-fec-source.js
315
418
  var ALL_ROLES = Object.freeze(["video", "audio"]);
@@ -323,6 +426,269 @@ function isoBlockSpanUsable(fec) {
323
426
  const ms = block["interleaveDepthMs"];
324
427
  return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
325
428
  }
429
+ function fecAlgorithmUnimplemented(algorithm) {
430
+ return typeof algorithm === "string" && algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon";
431
+ }
432
+ function isPositiveSafeInteger(value) {
433
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
434
+ }
435
+ var ISO_SSBG1_MIN_SYMBOL_SIZE = 14;
436
+ function catalogFecDeclaresUnconfigurableInstance(fec) {
437
+ const block = recordOf(fec);
438
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"]))
439
+ return false;
440
+ if (!(isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"])))
441
+ return true;
442
+ return block["blockProfile"] === "iso-ssbg1-v1" && block["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE;
443
+ }
444
+
445
+ // ../mmt-base/dist/multicast-catalog.js
446
+ var ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
447
+ var UINT32_MAX = 4294967295;
448
+ var AUTH_MEMBERS = /* @__PURE__ */ new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
449
+ var KEY_MEMBERS = /* @__PURE__ */ new Set(["kid", "publicKey", "firstEpoch"]);
450
+ var ENDPOINT_AUTH_MEMBERS = /* @__PURE__ */ new Set([
451
+ "manifestPort",
452
+ "streamId",
453
+ "senderAddress",
454
+ "maxAuthDelayMs",
455
+ "manifestTimerMs",
456
+ "manifestTrack"
457
+ ]);
458
+ function isObject(value) {
459
+ return typeof value === "object" && value !== null && !Array.isArray(value);
460
+ }
461
+ function isNonEmptyString(value) {
462
+ return typeof value === "string" && value.trim().length > 0;
463
+ }
464
+ function isIntegerIn(value, min, max) {
465
+ return Number.isSafeInteger(value) && value >= min && value <= max;
466
+ }
467
+ function multicastEndpointSource(endpoint) {
468
+ if (!isObject(endpoint))
469
+ return void 0;
470
+ const sourceAddress = endpoint["sourceAddress"];
471
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress))
472
+ return void 0;
473
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
474
+ const protocol = endpoint["protocol"];
475
+ if (protocol !== void 0 && protocol !== mode)
476
+ return void 0;
477
+ const auth = endpoint["auth"];
478
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : void 0;
479
+ if (mode === "ssm")
480
+ return senderAddress === void 0 ? { mode, source: sourceAddress } : void 0;
481
+ if (auth === void 0)
482
+ return { mode };
483
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : void 0;
484
+ }
485
+ function authIssues(auth) {
486
+ const base = "$.multicast.auth";
487
+ const issue = (path, message) => [
488
+ { code: "multicast_auth", path: `${base}${path}`, message }
489
+ ];
490
+ if (!isObject(auth))
491
+ return issue("", "auth must be an object");
492
+ const unknown = Object.keys(auth).filter((key) => !AUTH_MEMBERS.has(key));
493
+ if (unknown.length > 0) {
494
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
495
+ }
496
+ if (auth["scheme"] !== "bc-provenance")
497
+ return issue(".scheme", 'scheme must be "bc-provenance"');
498
+ if (auth["version"] !== 2)
499
+ return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
500
+ if (auth["sig"] !== "ed25519")
501
+ return issue(".sig", 'sig must be "ed25519"');
502
+ const keys = auth["keys"];
503
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
504
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
505
+ }
506
+ const kids = /* @__PURE__ */ new Set();
507
+ const firstEpochs = /* @__PURE__ */ new Set();
508
+ for (let index = 0; index < keys.length; index++) {
509
+ const key = keys[index];
510
+ const at = `.keys[${index}]`;
511
+ if (!isObject(key) || Object.keys(key).some((member) => !KEY_MEMBERS.has(member))) {
512
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
513
+ }
514
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX))
515
+ return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
516
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
517
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
518
+ }
519
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
520
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
521
+ }
522
+ if (kids.has(key["kid"]))
523
+ return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
524
+ if (firstEpochs.has(key["firstEpoch"])) {
525
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
526
+ }
527
+ kids.add(key["kid"]);
528
+ firstEpochs.add(key["firstEpoch"]);
529
+ }
530
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
531
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
532
+ }
533
+ return [];
534
+ }
535
+ function endpointAuthIssue(endpoint, mode, at) {
536
+ const auth = endpoint["auth"];
537
+ if (!isObject(auth))
538
+ return { path: `${at}.auth`, message: "auth must be an object" };
539
+ const unknown = Object.keys(auth).filter((key) => !ENDPOINT_AUTH_MEMBERS.has(key));
540
+ if (unknown.length > 0)
541
+ return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
542
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
543
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
544
+ }
545
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
546
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
547
+ }
548
+ if (mode === "ssm" && auth["senderAddress"] !== void 0) {
549
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
550
+ }
551
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
552
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
553
+ }
554
+ if (auth["maxAuthDelayMs"] !== void 0 && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1e3)) {
555
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
556
+ }
557
+ if (auth["manifestTimerMs"] !== void 0 && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
558
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
559
+ }
560
+ if (auth["manifestTrack"] !== void 0 && !isNonEmptyString(auth["manifestTrack"])) {
561
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
562
+ }
563
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
564
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
565
+ }
566
+ return void 0;
567
+ }
568
+ var CATALOG_NAMESPACE = /* @__PURE__ */ Symbol.for("@blockcast/mmt-base/catalogNamespace");
569
+ function multicastCatalogIssues(catalog, options = {}) {
570
+ if (!isObject(catalog))
571
+ return [];
572
+ const issues = [];
573
+ if ("multicast.auth" in catalog) {
574
+ issues.push({
575
+ code: "multicast_auth",
576
+ path: '$["multicast.auth"]',
577
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)'
578
+ });
579
+ }
580
+ const multicast = catalog["multicast"];
581
+ if (!isObject(multicast))
582
+ return issues;
583
+ const protectedCatalog = multicast["auth"] !== void 0;
584
+ if (protectedCatalog)
585
+ issues.push(...authIssues(multicast["auth"]));
586
+ const endpoints = multicast["endpoints"];
587
+ if (!Array.isArray(endpoints))
588
+ return issues;
589
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
590
+ const namespaceOf = /* @__PURE__ */ new Map();
591
+ for (const track of tracks) {
592
+ if (isObject(track) && typeof track["name"] === "string")
593
+ namespaceOf.set(track["name"], track["namespace"]);
594
+ }
595
+ const tagged = catalog[CATALOG_NAMESPACE];
596
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
597
+ const sources = [];
598
+ for (let index = 0; index < endpoints.length; index++) {
599
+ const endpoint = endpoints[index];
600
+ const at = `$.multicast.endpoints[${index}]`;
601
+ const fail = (code, path, message) => {
602
+ issues.push({ code, path, message, endpointIndex: index });
603
+ };
604
+ sources.push(void 0);
605
+ if (!isObject(endpoint)) {
606
+ fail("multicast_endpoint", at, "endpoint must be an object");
607
+ continue;
608
+ }
609
+ const protocol = endpoint["protocol"];
610
+ if (protocol !== void 0 && protocol !== "ssm" && protocol !== "asm") {
611
+ fail("multicast_endpoint", `${at}.protocol`, `protocol must be "ssm" or "asm"; a bearer such as ${JSON.stringify(protocol)} is a networkSource entry (draft -01 4.2)`);
612
+ continue;
613
+ }
614
+ const hasAuth = endpoint["auth"] !== void 0;
615
+ if (protectedCatalog !== hasAuth) {
616
+ fail("multicast_endpoint_auth", `${at}.auth`, protectedCatalog ? "every endpoint requires auth when multicast carries auth; a receiver ignores this endpoint" : "auth names no key without multicast.auth; a receiver ignores this endpoint");
617
+ continue;
618
+ }
619
+ const sourceAddress = endpoint["sourceAddress"];
620
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress)) {
621
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
622
+ continue;
623
+ }
624
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
625
+ if (protocol !== void 0 && protocol !== mode) {
626
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
627
+ continue;
628
+ }
629
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
630
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
631
+ continue;
632
+ }
633
+ if (hasAuth) {
634
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
635
+ if (authIssue) {
636
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
637
+ continue;
638
+ }
639
+ }
640
+ sources[index] = multicastEndpointSource(endpoint);
641
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
642
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
643
+ const ref = refs[refIndex];
644
+ const name = isObject(ref) ? ref["name"] : ref;
645
+ if (typeof name !== "string")
646
+ continue;
647
+ const namespace = namespaceOf.get(name);
648
+ if (typeof namespace !== "string")
649
+ continue;
650
+ referenceNamespace ??= namespace;
651
+ if (namespace !== referenceNamespace) {
652
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
653
+ }
654
+ }
655
+ }
656
+ const tupleOf = (index) => {
657
+ const endpoint = endpoints[index];
658
+ const auth = endpoint["auth"];
659
+ return {
660
+ sg: JSON.stringify([sources[index].source ?? null, endpoint["groupAddress"]]),
661
+ port: endpoint["port"],
662
+ manifestPort: isObject(auth) ? auth["manifestPort"] : void 0
663
+ };
664
+ };
665
+ for (let index = 0; index < endpoints.length; index++) {
666
+ if (!sources[index])
667
+ continue;
668
+ const own = tupleOf(index);
669
+ const at = `$.multicast.endpoints[${index}]`;
670
+ if (own.manifestPort !== void 0 && own.manifestPort === own.port) {
671
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
672
+ continue;
673
+ }
674
+ for (let other = 0; other < endpoints.length; other++) {
675
+ if (other === index || !sources[other])
676
+ continue;
677
+ const peer = tupleOf(other);
678
+ if (peer.sg !== own.sg)
679
+ continue;
680
+ if (peer.port === own.port) {
681
+ issues.push({ code: "multicast_endpoint", path: `${at}.port`, message: `(S, G, port) is shared with endpoint ${other}; one endpoint object per multicast tuple`, endpointIndex: index });
682
+ break;
683
+ }
684
+ if (own.manifestPort !== void 0 && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
685
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: `manifestPort is a port or manifestPort of endpoint ${other} on the same (S, G)`, endpointIndex: index });
686
+ break;
687
+ }
688
+ }
689
+ }
690
+ return issues;
691
+ }
326
692
 
327
693
  // src/mfu-reassembler.ts
328
694
  function fragmentProvenance(fragment) {
@@ -6969,197 +7335,6 @@ function createWasmMmtpContainerParser(config) {
6969
7335
  });
6970
7336
  }
6971
7337
 
6972
- // src/multicast-auth-catalog.ts
6973
- var RAW_ED25519_KEY_LENGTH = 32;
6974
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
6975
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6976
- function encodeBase64Url(bytes) {
6977
- let output = "";
6978
- for (let i = 0; i < bytes.length; i += 3) {
6979
- const b0 = bytes[i];
6980
- const b1 = bytes[i + 1];
6981
- const b2 = bytes[i + 2];
6982
- output += BASE64URL_ALPHABET[b0 >> 2];
6983
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
6984
- if (b1 === void 0) break;
6985
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
6986
- if (b2 === void 0) break;
6987
- output += BASE64URL_ALPHABET[b2 & 63];
6988
- }
6989
- return output;
6990
- }
6991
- var BASE64URL_DECODE_TABLE = (() => {
6992
- const table = new Int8Array(128).fill(-1);
6993
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
6994
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
6995
- }
6996
- return table;
6997
- })();
6998
- function decodeBase64Url(text) {
6999
- if (text.length % 4 === 1) {
7000
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
7001
- }
7002
- const bytes = [];
7003
- let buffer = 0;
7004
- let bits = 0;
7005
- for (let i = 0; i < text.length; i++) {
7006
- const code = text.charCodeAt(i);
7007
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
7008
- if (value === void 0 || value < 0) {
7009
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
7010
- }
7011
- buffer = buffer << 6 | value;
7012
- bits += 6;
7013
- if (bits >= 8) {
7014
- bits -= 8;
7015
- bytes.push(buffer >> bits & 255);
7016
- }
7017
- }
7018
- const decoded = Uint8Array.from(bytes);
7019
- if (encodeBase64Url(decoded) !== text) {
7020
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
7021
- }
7022
- return decoded;
7023
- }
7024
- function decodeAuthScope(authScope) {
7025
- const bytes = decodeBase64Url(authScope);
7026
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
7027
- throw new Error(
7028
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
7029
- );
7030
- }
7031
- return bytes;
7032
- }
7033
- function decodeEd25519PublicKey(publicKey) {
7034
- const bytes = decodeBase64Url(publicKey);
7035
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
7036
- throw new Error(
7037
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
7038
- );
7039
- }
7040
- return bytes;
7041
- }
7042
- function isNonEmptyString(value) {
7043
- return typeof value === "string" && value.length > 0;
7044
- }
7045
- function isValidAuthScopeField(value) {
7046
- if (!isNonEmptyString(value)) return false;
7047
- try {
7048
- decodeAuthScope(value);
7049
- return true;
7050
- } catch {
7051
- return false;
7052
- }
7053
- }
7054
- function isValidPublicKeyField(value) {
7055
- if (!isNonEmptyString(value)) return false;
7056
- try {
7057
- decodeEd25519PublicKey(value);
7058
- return true;
7059
- } catch {
7060
- return false;
7061
- }
7062
- }
7063
- function hasOnlyKeys(object, allowed) {
7064
- const allowedKeys = new Set(allowed);
7065
- return Object.keys(object).every((key) => allowedKeys.has(key));
7066
- }
7067
- function isMulticastAuthTrackConfig(obj) {
7068
- if (typeof obj !== "object" || obj === null) return false;
7069
- const o = obj;
7070
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
7071
- }
7072
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
7073
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
7074
- function hasUniqueMulticastAuthTrackBindings(tracks) {
7075
- const bindings = tracks.flatMap((track) => {
7076
- if (typeof track !== "object" || track === null) return [];
7077
- const value = track;
7078
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
7079
- return [];
7080
- }
7081
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
7082
- });
7083
- return new Set(bindings).size === bindings.length;
7084
- }
7085
- function isMulticastAuthConfig(obj) {
7086
- if (typeof obj !== "object" || obj === null) return false;
7087
- const o = obj;
7088
- if (o["scheme"] !== "bc-provenance") return false;
7089
- if (o["hash"] !== "blake3") return false;
7090
- if (o["sig"] !== "ed25519") return false;
7091
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
7092
- if (!isValidPublicKeyField(o["publicKey"])) return false;
7093
- if (!isNonEmptyString(o["keyId"])) return false;
7094
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
7095
- if (o["previousKey"] === o["publicKey"]) return false;
7096
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
7097
- if (o["enforcement"] !== void 0) {
7098
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
7099
- }
7100
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
7101
- const tracks = o["tracks"];
7102
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
7103
- const typedTracks = tracks;
7104
- const scopes = typedTracks.map((t) => t.authScope);
7105
- if (new Set(scopes).size !== scopes.length) return false;
7106
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
7107
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
7108
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
7109
- return true;
7110
- }
7111
- function resolveMulticastAuthMode(playerMode, auth) {
7112
- if (playerMode !== void 0) return playerMode;
7113
- if (auth === void 0) return "off";
7114
- return auth.enforcement ?? "shadow";
7115
- }
7116
- function resolveMulticastAuthCatalog(catalog, playerMode) {
7117
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
7118
- throw new Error("[multicast-auth-catalog] catalog must be an object");
7119
- }
7120
- const root = catalog;
7121
- const rawAuth = root["multicast.auth"];
7122
- if (rawAuth === void 0) {
7123
- if (playerMode === "enforce") {
7124
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
7125
- }
7126
- return void 0;
7127
- }
7128
- if (!isMulticastAuthConfig(rawAuth)) {
7129
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
7130
- }
7131
- const rawTracks = root["tracks"];
7132
- if (!Array.isArray(rawTracks)) {
7133
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
7134
- }
7135
- const catalogTrackNames = new Set(
7136
- rawTracks.flatMap(
7137
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
7138
- )
7139
- );
7140
- for (const track of rawAuth.tracks) {
7141
- if (!catalogTrackNames.has(track.mediaTrack)) {
7142
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
7143
- }
7144
- if (!catalogTrackNames.has(track.manifestTrack)) {
7145
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
7146
- }
7147
- }
7148
- return {
7149
- keyId: rawAuth.keyId,
7150
- acceptedPublicKeys: [
7151
- decodeEd25519PublicKey(rawAuth.publicKey),
7152
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
7153
- ],
7154
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
7155
- compaction: rawAuth.compaction,
7156
- tracks: rawAuth.tracks.map((track) => ({
7157
- ...track,
7158
- authScope: decodeAuthScope(track.authScope)
7159
- }))
7160
- };
7161
- }
7162
-
7163
7338
  // src/repair-layers.ts
7164
7339
  var REPAIR_PRIORITY_MIN = 192;
7165
7340
  var REPAIR_PRIORITY_MAX = 255;
@@ -7167,6 +7342,7 @@ var DEFAULT_REPAIR_PRIORITY = 240;
7167
7342
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
7168
7343
  var MAX_REPAIR_SYMBOLS = 16777215;
7169
7344
  var MAX_ENCODING_SYMBOL_ID = 16777215;
7345
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
7170
7346
  var RepairContractError = class extends Error {
7171
7347
  constructor(code, path, message) {
7172
7348
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -7349,11 +7525,12 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7349
7525
  if (layered && !positiveInteger(source.sourceSymbols)) {
7350
7526
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
7351
7527
  }
7352
- if (layered && source.algorithm !== "raptorq") {
7528
+ const reedSolomon = source.algorithm === "reed-solomon";
7529
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
7353
7530
  fail(
7354
7531
  "track_fec",
7355
7532
  `${source.path}.algorithm`,
7356
- "repair layers and overlays are defined only for raptorq: a block code fixes its codeword length, so symbols of a larger P are not symbols of the code a receiver holding fewer layers decodes"
7533
+ "repair layers and overlays are defined only for raptorq and reed-solomon (draft-ramadan-moq-fec-01 6.3.4 rule 7)"
7357
7534
  );
7358
7535
  }
7359
7536
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -7412,6 +7589,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7412
7589
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7413
7590
  );
7414
7591
  }
7592
+ if (reedSolomon && sourceSymbols + repairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
7593
+ fail(
7594
+ "track_fec_bounds",
7595
+ `${d.path}.repairSymbols`,
7596
+ `reed-solomon overlay sourceSymbols + repairSymbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
7597
+ );
7598
+ }
7415
7599
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
7416
7600
  }
7417
7601
  let offset = layerZeroSymbols;
@@ -7456,6 +7640,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7456
7640
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7457
7641
  );
7458
7642
  }
7643
+ if (reedSolomon && k + totalBaseRepairSymbols > MAX_REED_SOLOMON_BLOCK_SYMBOLS) {
7644
+ fail(
7645
+ "track_fec_bounds",
7646
+ `${source.path}.sourceSymbols`,
7647
+ `reed-solomon sourceSymbols + total base repair symbols exceeds ${MAX_REED_SOLOMON_BLOCK_SYMBOLS} (draft-ramadan-moq-fec-01 6.3.4 rule 12)`
7648
+ );
7649
+ }
7459
7650
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
7460
7651
  }
7461
7652
 
@@ -7543,7 +7734,7 @@ var CmsfCatalogValidationError = class extends Error {
7543
7734
  function catalogError(code, path, message) {
7544
7735
  throw new CmsfCatalogValidationError(code, path, message);
7545
7736
  }
7546
- function validateCmsfMmtpCatalog(value) {
7737
+ function validateCmsfMmtpCatalog(value, options = {}) {
7547
7738
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
7548
7739
  catalogError("catalog_object", "$", "catalog must be an object");
7549
7740
  }
@@ -7564,6 +7755,22 @@ function validateCmsfMmtpCatalog(value) {
7564
7755
  "commonTrackFields is retired; every track carries its own fields"
7565
7756
  );
7566
7757
  }
7758
+ const initDataList = catalog["initDataList"];
7759
+ if (initDataList !== void 0) {
7760
+ if (!Array.isArray(initDataList)) {
7761
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
7762
+ }
7763
+ initDataList.forEach((entry, i) => {
7764
+ const e = entry;
7765
+ const entryPath = `$.initDataList[${i}]`;
7766
+ if (typeof e !== "object" || e === null || Array.isArray(e) || typeof e["id"] !== "string" || e["id"].length === 0 || typeof e["type"] !== "string" || e["type"].length === 0) {
7767
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
7768
+ }
7769
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
7770
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
7771
+ }
7772
+ });
7773
+ }
7567
7774
  const tracks = catalog["tracks"];
7568
7775
  const trackRecords = [];
7569
7776
  const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -7615,6 +7822,14 @@ function validateCmsfMmtpCatalog(value) {
7615
7822
  if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
7616
7823
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
7617
7824
  }
7825
+ const anchor = track["presentationAnchorTicks"];
7826
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
7827
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
7828
+ }
7829
+ const initRef = track["initRef"];
7830
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
7831
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7832
+ }
7618
7833
  if (packaging === "fec-repair") {
7619
7834
  rejectRepairTrackGeometry(path, track, catalogError);
7620
7835
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -7622,9 +7837,8 @@ function validateCmsfMmtpCatalog(value) {
7622
7837
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
7623
7838
  }
7624
7839
  if (packaging === "mmtp") {
7625
- const mmtpMode = track["mmtpMode"];
7626
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
7627
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
7840
+ if (track["mmtpMode"] !== "mfu") {
7841
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7628
7842
  }
7629
7843
  if (!positiveInteger2(timescale)) {
7630
7844
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -7647,8 +7861,8 @@ function validateCmsfMmtpCatalog(value) {
7647
7861
  }
7648
7862
  const config = fec;
7649
7863
  const algorithm = config["algorithm"];
7650
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
7651
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
7864
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
7865
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
7652
7866
  }
7653
7867
  if ("interleaveDepth" in config || "interleaveMs" in config) {
7654
7868
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -7677,6 +7891,9 @@ function validateCmsfMmtpCatalog(value) {
7677
7891
  }
7678
7892
  }
7679
7893
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
7894
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
7895
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
7896
+ }
7680
7897
  }
7681
7898
  }
7682
7899
  const repairDescriptors = trackRecords.flatMap(
@@ -7788,21 +8005,14 @@ function validateCmsfMmtpCatalog(value) {
7788
8005
  }
7789
8006
  }
7790
8007
  }
7791
- try {
7792
- resolveMulticastAuthCatalog(catalog);
7793
- } catch (error) {
7794
- catalogError(
7795
- "multicast_auth",
7796
- "$.multicast.auth",
7797
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
7798
- );
7799
- }
8008
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
8009
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
7800
8010
  validateArchive(catalog);
7801
8011
  return catalog;
7802
8012
  }
7803
8013
 
7804
8014
  // src/no-modules.ts
7805
- import { catalogFecInterleaveMs, computeFecTimeout } from "@blockcast/mmt-fec";
8015
+ import { catalogFecInterleaveMs, fecBlockBudgetMs as fecBlockBudgetMs2, fecBlockDeadlineMs } from "@blockcast/mmt-fec";
7806
8016
 
7807
8017
  // src/fec-state.ts
7808
8018
  var FEC_INACTIVE_REASONS = Object.freeze([
@@ -7819,13 +8029,13 @@ var INACTIVE = Object.freeze({
7819
8029
  function recordOf2(value) {
7820
8030
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7821
8031
  }
7822
- function isPositiveSafeInteger(value) {
8032
+ function isPositiveSafeInteger2(value) {
7823
8033
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
7824
8034
  }
7825
8035
  function catalogDeclaresFec(fec) {
7826
8036
  const block = recordOf2(fec);
7827
- if (block === void 0 || block["algorithm"] === "none") return false;
7828
- return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
8037
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
8038
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
7829
8039
  }
7830
8040
  function requireBoolean(value, field) {
7831
8041
  if (typeof value !== "boolean") {
@@ -7853,6 +8063,385 @@ function resolveFecState(evidence) {
7853
8063
  return INACTIVE["reliable-moq"];
7854
8064
  }
7855
8065
 
8066
+ // src/mmtp-fec-session.ts
8067
+ import { deriveFecRetentionBlocks, fecBlockBudgetMs } from "@blockcast/mmt-fec";
8068
+ var PATH_BITS = { moq: 1, multicast: 2 };
8069
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8070
+ var MmtpFecSession = class {
8071
+ #decoder;
8072
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
8073
+ #blocks = /* @__PURE__ */ new Map();
8074
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
8075
+ #settled = /* @__PURE__ */ new Set();
8076
+ /**
8077
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
8078
+ * received on, or 0 for one the session recovered.
8079
+ */
8080
+ #have = /* @__PURE__ */ new Map();
8081
+ #newest;
8082
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
8083
+ #prunedAt;
8084
+ #repairPacketId;
8085
+ #stats = {
8086
+ sourceSymbols: 0,
8087
+ repairSymbols: 0,
8088
+ blocksClean: 0,
8089
+ blocksRecovered: 0,
8090
+ blocksFailed: 0,
8091
+ blocksReleased: 0,
8092
+ packetsRecovered: 0,
8093
+ packetsLost: 0,
8094
+ dropped: {},
8095
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
8096
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
8097
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
8098
+ };
8099
+ /**
8100
+ * @throws when the catalog block lacks or misstates a field the session
8101
+ * needs: the block profile, K, T, `interleaveDepthMs` or
8102
+ * `reorderToleranceMs`. None is defaulted.
8103
+ */
8104
+ constructor(config) {
8105
+ const fec = config?.fec;
8106
+ if (!fec || typeof fec !== "object") {
8107
+ throw new Error("MmtpFecSession: the catalog fec block is required");
8108
+ }
8109
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
8110
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
8111
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
8112
+ }
8113
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
8114
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8115
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8116
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8117
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
8118
+ this.retentionBlocks = deriveFecRetentionBlocks(
8119
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
8120
+ interleaveDepthMs
8121
+ );
8122
+ if (typeof config.Decoder !== "function") {
8123
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8124
+ }
8125
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
8126
+ try {
8127
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
8128
+ } catch (error) {
8129
+ decoder.free();
8130
+ throw error;
8131
+ }
8132
+ this.#decoder = decoder;
8133
+ }
8134
+ /** True once release() ran. */
8135
+ get released() {
8136
+ return this.#decoder === null;
8137
+ }
8138
+ get stats() {
8139
+ return {
8140
+ ...this.#stats,
8141
+ dropped: { ...this.#stats.dropped },
8142
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
8143
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
8144
+ mixedPath: { ...this.#stats.mixedPath }
8145
+ };
8146
+ }
8147
+ /**
8148
+ * Feeds one received source packet: the MMTP packet without its four-byte
8149
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
8150
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
8151
+ * was received; a caller that only subscribes over MoQT can leave it out.
8152
+ *
8153
+ * @returns the protected packets of this packet's block that it recovered,
8154
+ * in SS_ID order, for the caller to feed to its parser with
8155
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
8156
+ */
8157
+ addSource(ssId, packet, path = "moq") {
8158
+ const decoder = this.#decoder;
8159
+ if (!decoder) return this.#drop("source:released");
8160
+ const pathBit = PATH_BITS[path];
8161
+ if (!pathBit) return this.#drop("source:unknown-path");
8162
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
8163
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
8164
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
8165
+ this.#have.set(ssId, pathBit);
8166
+ this.#stats.sourceSymbols++;
8167
+ this.#stats.sourceSymbolsByPath[path]++;
8168
+ this.#noteNewest(ssId);
8169
+ const start = this.#blockStartOf(ssId);
8170
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
8171
+ if (block) {
8172
+ block.received++;
8173
+ block.paths |= pathBit;
8174
+ }
8175
+ let output;
8176
+ try {
8177
+ output = decoder.add_source(ssId, packet, 0);
8178
+ } catch {
8179
+ this.#drop("source:decoder-refused");
8180
+ output = void 0;
8181
+ }
8182
+ const recovered = [];
8183
+ if (start !== void 0 && block) {
8184
+ if (output) {
8185
+ recovered.push(...this.#settleDecoded(start, block, output));
8186
+ } else if (block.received >= block.ssbLength) {
8187
+ this.#settleClean(start);
8188
+ }
8189
+ }
8190
+ this.#retireBehindHorizon();
8191
+ return recovered;
8192
+ }
8193
+ /**
8194
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
8195
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
8196
+ * repair packet fixes its packet ID and a packet of any other is refused.
8197
+ * `path` is where it was received, as for addSource().
8198
+ *
8199
+ * @returns the protected packets this repair symbol recovered, as for
8200
+ * addSource().
8201
+ */
8202
+ addRepair(packet, path = "moq") {
8203
+ const decoder = this.#decoder;
8204
+ if (!decoder) return this.#drop("repair:released");
8205
+ const pathBit = PATH_BITS[path];
8206
+ if (!pathBit) return this.#drop("repair:unknown-path");
8207
+ let header;
8208
+ try {
8209
+ header = parseMMTPHeader(packet);
8210
+ } catch {
8211
+ return this.#drop("repair:malformed");
8212
+ }
8213
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
8214
+ if (!frame) return this.#drop("repair:malformed");
8215
+ if (this.#repairPacketId === void 0) {
8216
+ this.#repairPacketId = frame.packetId;
8217
+ } else if (frame.packetId !== this.#repairPacketId) {
8218
+ return this.#drop("repair:foreign-packet-id");
8219
+ }
8220
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
8221
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
8222
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
8223
+ return this.#drop("repair:rs-block-length");
8224
+ }
8225
+ const start = frame.ssStart;
8226
+ let block = this.#blocks.get(start);
8227
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
8228
+ if (block?.rsIds.has(frame.rsId)) return this.#drop("repair:duplicate");
8229
+ if (!block) {
8230
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
8231
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
8232
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
8233
+ this.#countHeld(start, block);
8234
+ this.#blocks.set(start, block);
8235
+ }
8236
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
8237
+ if (block.received >= block.ssbLength) {
8238
+ this.#settleClean(start);
8239
+ this.#retireBehindHorizon();
8240
+ return [];
8241
+ }
8242
+ let output;
8243
+ try {
8244
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
8245
+ } catch {
8246
+ return this.#drop("repair:decoder-refused");
8247
+ }
8248
+ block.rsIds.add(frame.rsId);
8249
+ this.#stats.repairSymbols++;
8250
+ this.#stats.repairSymbolsByPath[path]++;
8251
+ block.paths |= pathBit;
8252
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
8253
+ this.#retireBehindHorizon();
8254
+ return recovered;
8255
+ }
8256
+ /**
8257
+ * Frees the decoder and every block. Blocks still unsettled are counted as
8258
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
8259
+ * returns whether this call released anything.
8260
+ */
8261
+ release() {
8262
+ const decoder = this.#decoder;
8263
+ if (!decoder) return false;
8264
+ this.#decoder = null;
8265
+ this.#stats.blocksReleased += this.#blocks.size;
8266
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
8267
+ this.#blocks.clear();
8268
+ this.#settled.clear();
8269
+ this.#have.clear();
8270
+ decoder.free();
8271
+ return true;
8272
+ }
8273
+ #drop(reason) {
8274
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
8275
+ return [];
8276
+ }
8277
+ #noteNewest(ssId) {
8278
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
8279
+ }
8280
+ #blockStartOf(ssId) {
8281
+ for (const [start, block] of this.#blocks) {
8282
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
8283
+ }
8284
+ return void 0;
8285
+ }
8286
+ /** Counts the sources of a new block the parser already has, and their paths. */
8287
+ #countHeld(start, block) {
8288
+ for (let i = 0; i < block.ssbLength; i++) {
8289
+ const pathBit = this.#have.get(serial32Add(start, i));
8290
+ if (pathBit === void 0) continue;
8291
+ block.received++;
8292
+ block.paths |= pathBit;
8293
+ }
8294
+ }
8295
+ #noteMixed(block, outcome) {
8296
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
8297
+ }
8298
+ /** The decoder's own rule: more than its retention behind, counted from below. */
8299
+ #behindHorizon(start) {
8300
+ const newest = this.#newest;
8301
+ if (newest === void 0) return false;
8302
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
8303
+ }
8304
+ #settle(start) {
8305
+ this.#blocks.delete(start);
8306
+ this.#settled.add(start);
8307
+ }
8308
+ #settleClean(start) {
8309
+ const block = this.#blocks.get(start);
8310
+ if (!block) return;
8311
+ this.#settle(start);
8312
+ this.#stats.blocksClean++;
8313
+ this.#noteMixed(block, "clean");
8314
+ try {
8315
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
8316
+ } catch {
8317
+ }
8318
+ }
8319
+ /**
8320
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
8321
+ * concatenated: split by T, trim by each symbol's length field, and hand
8322
+ * back the packets the parser does not have yet.
8323
+ */
8324
+ #settleDecoded(start, block, output) {
8325
+ this.#settle(start);
8326
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
8327
+ this.#stats.blocksFailed++;
8328
+ this.#stats.packetsLost += block.ssbLength - block.received;
8329
+ this.#noteMixed(block, "failed");
8330
+ this.#drop("block:decoded-length");
8331
+ return [];
8332
+ }
8333
+ const recovered = [];
8334
+ let refused = 0;
8335
+ for (let i = 0; i < block.ssbLength; i++) {
8336
+ const ssId = serial32Add(start, i);
8337
+ if (this.#have.has(ssId)) continue;
8338
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
8339
+ const packet = trimSsbg1SourceSymbol(symbol);
8340
+ if (!packet) {
8341
+ refused++;
8342
+ continue;
8343
+ }
8344
+ this.#have.set(ssId, 0);
8345
+ recovered.push(packet.slice());
8346
+ }
8347
+ if (refused > 0) {
8348
+ this.#stats.blocksFailed++;
8349
+ this.#stats.packetsLost += refused;
8350
+ this.#noteMixed(block, "failed");
8351
+ this.#drop("block:bad-ssbg1-symbol");
8352
+ } else if (recovered.length === 0) {
8353
+ this.#stats.blocksClean++;
8354
+ this.#noteMixed(block, "clean");
8355
+ } else {
8356
+ this.#stats.blocksRecovered++;
8357
+ this.#noteMixed(block, "recovered");
8358
+ }
8359
+ this.#stats.packetsRecovered += recovered.length;
8360
+ return recovered;
8361
+ }
8362
+ /**
8363
+ * Retires every block, and every SS_ID the session remembers, that the
8364
+ * newest SS_ID has moved past the retention. An unsettled block retired
8365
+ * here is a failure: more of its sources were lost than its repair could
8366
+ * restore, or its repair never arrived.
8367
+ */
8368
+ #retireBehindHorizon() {
8369
+ const decoder = this.#decoder;
8370
+ const newest = this.#newest;
8371
+ if (!decoder || newest === void 0) return;
8372
+ try {
8373
+ decoder.cleanup_by_ss_start(newest);
8374
+ } catch {
8375
+ }
8376
+ for (const [start, block] of this.#blocks) {
8377
+ if (!this.#behindHorizon(start)) continue;
8378
+ this.#settle(start);
8379
+ this.#stats.blocksFailed++;
8380
+ this.#stats.packetsLost += block.ssbLength - block.received;
8381
+ this.#noteMixed(block, "failed");
8382
+ }
8383
+ const prunedAt = this.#prunedAt;
8384
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
8385
+ this.#prunedAt = newest;
8386
+ for (const ssId of this.#have.keys()) {
8387
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
8388
+ }
8389
+ for (const start of this.#settled) {
8390
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
8391
+ }
8392
+ }
8393
+ };
8394
+ function requirePositiveInteger(value, path) {
8395
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
8396
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
8397
+ }
8398
+ return value;
8399
+ }
8400
+ function requireNumber(value, path) {
8401
+ if (typeof value !== "number") {
8402
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
8403
+ }
8404
+ return value;
8405
+ }
8406
+
8407
+ // src/catalog-network-source.ts
8408
+ function normalizePort(value) {
8409
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
8410
+ return Number.isInteger(n) && n > 0 && n <= 65535 ? n : void 0;
8411
+ }
8412
+ function catalogAmtNetworkSource(networkSource) {
8413
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8414
+ for (const raw of entries) {
8415
+ if (!raw || typeof raw !== "object") continue;
8416
+ const ns = raw;
8417
+ if (ns.type !== "amt") continue;
8418
+ if (ns.discovery === "driad") continue;
8419
+ const relay = typeof ns.relay === "string" ? ns.relay.trim() : "";
8420
+ if (!relay) continue;
8421
+ return { relay, port: normalizePort(ns.port) ?? DEFAULT_AMT_RELAY_PORT };
8422
+ }
8423
+ return void 0;
8424
+ }
8425
+ function intIn(value, min, max) {
8426
+ return Number.isInteger(value) && value >= min && value <= max;
8427
+ }
8428
+ function catalogAtsc3NetworkSource(networkSource) {
8429
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8430
+ for (const raw of entries) {
8431
+ if (!raw || typeof raw !== "object") continue;
8432
+ const ns = raw;
8433
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
8434
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
8435
+ return {
8436
+ frequency: ns.frequency,
8437
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
8438
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
8439
+ ...slsUri ? { slsUri } : {}
8440
+ };
8441
+ }
8442
+ return void 0;
8443
+ }
8444
+
7856
8445
  // src/mmtp-to-cmaf.ts
7857
8446
  function box(type, ...children2) {
7858
8447
  let size = 8;
@@ -7895,8 +8484,8 @@ function u32(v) {
7895
8484
  }
7896
8485
  var KEYFRAME_FLAGS = 33554432;
7897
8486
  var DELTA_FLAGS = 16842752;
7898
- var UINT32_MAX = 4294967295;
7899
- var MAX_TRACK_ID = UINT32_MAX - 1;
8487
+ var UINT32_MAX2 = 4294967295;
8488
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
7900
8489
  var INT32_MIN = -2147483648;
7901
8490
  var INT32_MAX = 2147483647;
7902
8491
  function assertTrackId(trackId, label) {
@@ -7905,8 +8494,8 @@ function assertTrackId(trackId, label) {
7905
8494
  }
7906
8495
  }
7907
8496
  function assertTimescale(timescale, label) {
7908
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
7909
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
8497
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
8498
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
7910
8499
  }
7911
8500
  }
7912
8501
  function assertCompositionTimeOffsets(samples) {
@@ -8952,7 +9541,7 @@ var SOURCE_AUTH_OBJECT_ENTRY_LENGTH = 52;
8952
9541
  var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
8953
9542
  var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
8954
9543
  var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
8955
- var SOURCE_AUTH_SCOPE_LENGTH2 = 32;
9544
+ var SOURCE_AUTH_SCOPE_LENGTH = 32;
8956
9545
  var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
8957
9546
  function requireBytes(name, value, length) {
8958
9547
  if (value.byteLength !== length) {
@@ -9029,7 +9618,7 @@ function sourceAuthSignaturePreimage(authScope, groupId, objectCount, root) {
9029
9618
  throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
9030
9619
  }
9031
9620
  requireU64("groupId", groupId);
9032
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH2);
9621
+ requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
9033
9622
  requireBytes("root", root, 32);
9034
9623
  const preimage = new Uint8Array(100);
9035
9624
  const view2 = new DataView(preimage.buffer);
@@ -9080,6 +9669,20 @@ function decodeSourceAuthManifestFrame(frame) {
9080
9669
  }
9081
9670
 
9082
9671
  // ../mmt-manifest-verify/dist/verifier.js
9672
+ function manifestKeyFor(keys, epoch, kid) {
9673
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length)
9674
+ return void 0;
9675
+ if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
9676
+ return void 0;
9677
+ let signer;
9678
+ for (const key of keys) {
9679
+ if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
9680
+ signer = key;
9681
+ }
9682
+ if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
9683
+ return void 0;
9684
+ return signer.publicKey;
9685
+ }
9083
9686
  function manifestBindingId(trackName, sourceSymbolFormat) {
9084
9687
  return JSON.stringify([trackName, sourceSymbolFormat]);
9085
9688
  }
@@ -9156,11 +9759,12 @@ var ManifestVerifier = class {
9156
9759
  }
9157
9760
  if (context.authScope.byteLength !== 32)
9158
9761
  throw new Error("manifest authScope must be 32 bytes");
9159
- if (context.publicKey.byteLength !== 32)
9160
- throw new Error("manifest publicKey must be 32 bytes");
9161
- for (const key of context.acceptedPublicKeys ?? []) {
9162
- if (key.byteLength !== 32)
9163
- throw new Error("manifest acceptedPublicKeys must contain 32-byte keys");
9762
+ for (const key of context.keys) {
9763
+ if (key.publicKey.byteLength !== 32)
9764
+ throw new Error("manifest keys must carry 32-byte public keys");
9765
+ }
9766
+ if (manifestKeyFor(context.keys, context.keyEpoch) === void 0) {
9767
+ throw new Error(`manifest keys hold no key set signing keyEpoch ${context.keyEpoch}`);
9164
9768
  }
9165
9769
  for (const [name, value] of Object.entries({
9166
9770
  broadcastNamespaceId: context.broadcastNamespaceId,
@@ -9405,7 +10009,7 @@ var ManifestVerifier = class {
9405
10009
  }
9406
10010
  }
9407
10011
  #verifyAcceptedSignature(track, message, signature) {
9408
- const keys = track.context.acceptedPublicKeys ?? [track.context.publicKey];
10012
+ const keys = [manifestKeyFor(track.context.keys, track.context.keyEpoch)];
9409
10013
  const pending = [];
9410
10014
  let hadSynchronousError = false;
9411
10015
  for (const key of keys) {
@@ -9540,59 +10144,140 @@ var ManifestVerifier = class {
9540
10144
  }
9541
10145
  };
9542
10146
 
9543
- // src/manifest-auth-plan.ts
9544
- function createManifestAuthPlan(catalog, options) {
9545
- const resolved = resolveMulticastAuthCatalog(catalog, options.playerMode);
9546
- if (!resolved || resolved.mode === "off") return void 0;
9547
- const verifier = new ManifestVerifier({
9548
- manifestAuth: {
9549
- mode: resolved.mode,
9550
- onMissingManifest: options.onMissingManifest ?? (resolved.mode === "enforce" ? "stall" : "fallback-shadow")
9551
- },
9552
- verifySignature: options.verifySignature,
9553
- ...options.onFailure === void 0 ? {} : { onFailure: options.onFailure }
9554
- });
9555
- const byManifestTrack = /* @__PURE__ */ new Map();
9556
- const bindings = resolved.tracks.map((binding) => {
9557
- const bindingId = manifestBindingId(binding.mediaTrack, binding.sourceSymbolFormat);
9558
- const planned = {
9559
- bindingId,
9560
- mediaTrack: binding.mediaTrack,
9561
- manifestTrack: binding.manifestTrack,
9562
- sourceSymbolFormat: binding.sourceSymbolFormat
9563
- };
9564
- verifier.registerTrack({
9565
- ...options.contextFor(binding, resolved),
9566
- bindingId,
9567
- trackName: binding.mediaTrack,
9568
- sourceSymbolFormat: binding.sourceSymbolFormat,
9569
- authScope: binding.authScope,
9570
- publicKey: resolved.acceptedPublicKeys[0],
9571
- acceptedPublicKeys: resolved.acceptedPublicKeys
10147
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10148
+ var BCPV2_HEADER_LENGTH = 68;
10149
+ var BCPV2_SIGNATURE_LENGTH = 64;
10150
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10151
+ var text = new TextEncoder();
10152
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10153
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10154
+
10155
+ // src/multicast-auth-catalog.ts
10156
+ var RAW_ED25519_KEY_LENGTH = 32;
10157
+ var DEFAULT_MAX_AUTH_DELAY_MS = 200;
10158
+ var DEFAULT_MANIFEST_TIMER_MS = 20;
10159
+ var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10160
+ function encodeBase64Url(bytes) {
10161
+ let output = "";
10162
+ for (let i = 0; i < bytes.length; i += 3) {
10163
+ const b0 = bytes[i];
10164
+ const b1 = bytes[i + 1];
10165
+ const b2 = bytes[i + 2];
10166
+ output += BASE64URL_ALPHABET[b0 >> 2];
10167
+ output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
10168
+ if (b1 === void 0) break;
10169
+ output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
10170
+ if (b2 === void 0) break;
10171
+ output += BASE64URL_ALPHABET[b2 & 63];
10172
+ }
10173
+ return output;
10174
+ }
10175
+ var BASE64URL_DECODE_TABLE = (() => {
10176
+ const table = new Int8Array(128).fill(-1);
10177
+ for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
10178
+ table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
10179
+ }
10180
+ return table;
10181
+ })();
10182
+ function decodeBase64Url(text2) {
10183
+ if (text2.length % 4 === 1) {
10184
+ throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
10185
+ }
10186
+ const bytes = [];
10187
+ let buffer = 0;
10188
+ let bits = 0;
10189
+ for (let i = 0; i < text2.length; i++) {
10190
+ const code = text2.charCodeAt(i);
10191
+ const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
10192
+ if (value === void 0 || value < 0) {
10193
+ throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
10194
+ }
10195
+ buffer = buffer << 6 | value;
10196
+ bits += 6;
10197
+ if (bits >= 8) {
10198
+ bits -= 8;
10199
+ bytes.push(buffer >> bits & 255);
10200
+ }
10201
+ }
10202
+ const decoded = Uint8Array.from(bytes);
10203
+ if (encodeBase64Url(decoded) !== text2) {
10204
+ throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
10205
+ }
10206
+ return decoded;
10207
+ }
10208
+ function decodeEd25519PublicKey(publicKey) {
10209
+ const bytes = decodeBase64Url(publicKey);
10210
+ if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
10211
+ throw new Error(
10212
+ `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
10213
+ );
10214
+ }
10215
+ return bytes;
10216
+ }
10217
+ function resolveMulticastAuthCatalog(catalog, options = {}) {
10218
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
10219
+ throw new Error("[multicast-auth-catalog] catalog must be an object");
10220
+ }
10221
+ const issues = multicastCatalogIssues(catalog, options);
10222
+ const fatal = issues.find((issue) => issue.endpointIndex === void 0);
10223
+ if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
10224
+ const multicast = catalog["multicast"];
10225
+ const auth = multicast?.["auth"];
10226
+ if (auth === void 0) {
10227
+ if (options.requireAuth) {
10228
+ throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
10229
+ }
10230
+ return void 0;
10231
+ }
10232
+ const ignored = new Set(issues.map((issue) => issue.endpointIndex));
10233
+ const endpoints = multicast["endpoints"] ?? [];
10234
+ const flows = [];
10235
+ endpoints.forEach((endpoint, endpointIndex) => {
10236
+ if (ignored.has(endpointIndex)) return;
10237
+ const flowAuth = endpoint["auth"];
10238
+ flows.push({
10239
+ endpointIndex,
10240
+ source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
10241
+ groupAddress: endpoint["groupAddress"],
10242
+ port: endpoint["port"],
10243
+ bandwidth: endpoint["bandwidth"],
10244
+ manifestPort: flowAuth.manifestPort,
10245
+ streamId: flowAuth.streamId,
10246
+ maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
10247
+ manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
10248
+ ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
10249
+ tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
10250
+ name,
10251
+ packetId
10252
+ }))
9572
10253
  });
9573
- byManifestTrack.set(binding.manifestTrack, planned);
9574
- return planned;
9575
10254
  });
9576
- let disposed = false;
9577
10255
  return {
9578
- verifier,
9579
- mode: resolved.mode,
9580
- bindings,
10256
+ keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
10257
+ minEpoch: auth.minEpoch,
10258
+ flows
10259
+ };
10260
+ }
10261
+ function multicastAuthKeyFor(resolved, kid, epoch) {
10262
+ return manifestKeyFor(resolved.keys, epoch, kid);
10263
+ }
10264
+
10265
+ // src/manifest-auth-plan.ts
10266
+ function createManifestAuthPlan(catalog, options = {}) {
10267
+ const resolved = resolveMulticastAuthCatalog(catalog, options);
10268
+ if (!resolved) return void 0;
10269
+ const byManifestTrack = /* @__PURE__ */ new Map();
10270
+ for (const flow of resolved.flows) {
10271
+ if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
10272
+ }
10273
+ return {
10274
+ keys: resolved.keys,
10275
+ minEpoch: resolved.minEpoch,
10276
+ flows: resolved.flows,
9581
10277
  manifestTracks: [...byManifestTrack.keys()],
9582
- bindingIdFor(mediaTrack, sourceSymbolFormat) {
9583
- const bindingId = manifestBindingId(mediaTrack, sourceSymbolFormat);
9584
- return bindings.some((binding) => binding.bindingId === bindingId) ? bindingId : void 0;
9585
- },
9586
- ingestManifestPayload(manifestTrack, payload) {
9587
- const binding = byManifestTrack.get(manifestTrack);
9588
- if (!binding) throw new Error(`unknown manifest subscription track ${manifestTrack}`);
9589
- verifier.ingestManifestFrame(binding.bindingId, payload);
9590
- },
9591
- dispose() {
9592
- if (disposed) return;
9593
- disposed = true;
9594
- verifier.dispose();
9595
- }
10278
+ keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
10279
+ flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
10280
+ flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
9596
10281
  };
9597
10282
  }
9598
10283
  export {
@@ -9600,14 +10285,19 @@ export {
9600
10285
  FEC_INACTIVE_REASONS,
9601
10286
  ManifestVerifier,
9602
10287
  MmtpContainerParser,
10288
+ MmtpFecSession,
9603
10289
  MmtpToCmaf,
10290
+ catalogAmtNetworkSource,
10291
+ catalogAtsc3NetworkSource,
9604
10292
  catalogDeclaresFec,
9605
10293
  catalogFecInterleaveMs,
9606
- computeFecTimeout,
9607
10294
  createManifestAuthPlan,
9608
10295
  createWasmMmtpContainerParser,
9609
10296
  createWebCryptoEd25519Verifier,
9610
10297
  datagramMfuReassembly,
10298
+ fecBlockBudgetMs2 as fecBlockBudgetMs,
10299
+ fecBlockDeadlineMs,
10300
+ isFmp4InitSegment,
9611
10301
  manifestBindingId,
9612
10302
  mmtpFrameReorderWindowFrames,
9613
10303
  reliableMoqMfuReassembly,