@blockcast/mmt-container 0.4.0 → 0.4.1-main.47aa22331187

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 (210) 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 +1839 -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 +121 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +421 -66
  33. package/dist/fec-manager.js.map +3 -3
  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/index.d.ts +5 -5
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +8 -8
  45. package/dist/index.js.map +2 -2
  46. package/dist/iso-block-locator.d.ts +39 -1
  47. package/dist/iso-block-locator.d.ts.map +1 -1
  48. package/dist/iso-block-locator.js +109 -17
  49. package/dist/iso-block-locator.js.map +3 -3
  50. package/dist/manifest-auth-plan.d.ts +26 -25
  51. package/dist/manifest-auth-plan.d.ts.map +1 -1
  52. package/dist/manifest-auth-plan.js +331 -1171
  53. package/dist/manifest-auth-plan.js.map +4 -4
  54. package/dist/mfu-reassembler.js +21 -13
  55. package/dist/mfu-reassembler.js.map +2 -2
  56. package/dist/mmtp-container-parser.d.ts.map +1 -1
  57. package/dist/mmtp-container-parser.js +93 -22
  58. package/dist/mmtp-container-parser.js.map +2 -2
  59. package/dist/mmtp-container-parser.no-modules.js +1137 -317
  60. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  61. package/dist/mmtp-decode-pipeline.js +93 -22
  62. package/dist/mmtp-decode-pipeline.js.map +2 -2
  63. package/dist/mmtp-fec-session.d.ts +159 -0
  64. package/dist/mmtp-fec-session.d.ts.map +1 -0
  65. package/dist/mmtp-fec-session.js +531 -0
  66. package/dist/mmtp-fec-session.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +39 -6
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +184 -27
  70. package/dist/mmtp-router.js.map +2 -2
  71. package/dist/multicast-auth-catalog.d.ts +86 -92
  72. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  73. package/dist/multicast-auth-catalog.js +347 -132
  74. package/dist/multicast-auth-catalog.js.map +4 -4
  75. package/dist/multicast-input.d.ts +31 -8
  76. package/dist/multicast-input.d.ts.map +1 -1
  77. package/dist/multicast-input.js +299 -35
  78. package/dist/multicast-input.js.map +3 -3
  79. package/dist/multicast-manager.d.ts +94 -5
  80. package/dist/multicast-manager.d.ts.map +1 -1
  81. package/dist/multicast-manager.js +877 -357
  82. package/dist/multicast-manager.js.map +4 -4
  83. package/dist/multicast-transport.d.ts +12 -2
  84. package/dist/multicast-transport.d.ts.map +1 -1
  85. package/dist/multicast-transport.js +108 -238
  86. package/dist/multicast-transport.js.map +4 -4
  87. package/dist/multicast-unwrap.js +21 -13
  88. package/dist/multicast-unwrap.js.map +2 -2
  89. package/dist/no-modules.d.ts +4 -1
  90. package/dist/no-modules.d.ts.map +1 -1
  91. package/dist/no-modules.js +1086 -301
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/phase14-catalog-override.d.ts +1 -1
  94. package/dist/phase14-catalog-override.d.ts.map +1 -1
  95. package/dist/phase14-catalog-override.js +2 -2
  96. package/dist/phase14-catalog-override.js.map +2 -2
  97. package/dist/repair-fetch.d.ts +81 -6
  98. package/dist/repair-fetch.d.ts.map +1 -1
  99. package/dist/repair-fetch.js +156 -31
  100. package/dist/repair-fetch.js.map +3 -3
  101. package/dist/repair-layers.d.ts +2 -0
  102. package/dist/repair-layers.d.ts.map +1 -1
  103. package/dist/repair-layers.js +19 -2
  104. package/dist/repair-layers.js.map +2 -2
  105. package/dist/sample-combiner.d.ts +7 -1
  106. package/dist/sample-combiner.d.ts.map +1 -1
  107. package/dist/sample-combiner.js +14 -2
  108. package/dist/sample-combiner.js.map +2 -2
  109. package/dist/signaling.d.ts +2 -2
  110. package/dist/signaling.d.ts.map +1 -1
  111. package/dist/signaling.js +3 -3
  112. package/dist/signaling.js.map +2 -2
  113. package/dist/source-auth.js +2710 -7
  114. package/dist/source-auth.js.map +4 -4
  115. package/dist/switching-set-alignment.d.ts +1 -1
  116. package/dist/switching-set-alignment.js.map +1 -1
  117. package/dist/timestamp-codec.js +21 -13
  118. package/dist/timestamp-codec.js.map +2 -2
  119. package/dist/wasm-mfu-reassembler.js.map +1 -1
  120. package/dist/wasm-mmtp-container-parser.js +93 -22
  121. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  122. package/package.json +6 -9
  123. package/schemas/catalog.schema.json +133 -38
  124. package/src/align.ts +52 -21
  125. package/src/carp-catalog.ts +188 -68
  126. package/src/catalog-fec-params.ts +28 -3
  127. package/src/catalog-network-source.ts +49 -7
  128. package/src/catalog-validator.ts +4 -11
  129. package/src/cmcd-producer.ts +17 -0
  130. package/src/fec-manager.ts +452 -63
  131. package/src/fec-state.ts +11 -4
  132. package/src/fec-worker-setup.ts +30 -2
  133. package/src/index.ts +27 -10
  134. package/src/iso-block-locator.ts +110 -7
  135. package/src/manifest-auth-plan.ts +39 -91
  136. package/src/mmtp-container-parser.ts +75 -7
  137. package/src/mmtp-fec-session.ts +533 -0
  138. package/src/mmtp-router.ts +166 -7
  139. package/src/multicast-auth-catalog.ts +131 -238
  140. package/src/multicast-input.ts +148 -124
  141. package/src/multicast-manager.ts +267 -21
  142. package/src/multicast-transport.ts +17 -3
  143. package/src/no-modules.ts +7 -1
  144. package/src/phase14-catalog-override.ts +3 -3
  145. package/src/repair-fetch.ts +283 -39
  146. package/src/repair-layers.ts +22 -2
  147. package/src/sample-combiner.ts +15 -2
  148. package/src/signaling.ts +2 -2
  149. package/src/switching-set-alignment.ts +1 -1
  150. package/test-vectors/align.json +108 -32
  151. package/test-vectors/bc-provenance-v2.json +1526 -0
  152. package/test-vectors/catalog/README.md +71 -4
  153. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  154. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  155. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  156. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  157. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  158. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  159. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  160. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  161. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  162. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  163. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  164. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  165. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  166. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  167. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  168. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  169. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  170. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  171. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  172. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  173. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  174. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  177. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  178. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  179. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  180. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  181. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  182. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  183. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  184. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  185. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  186. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  187. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  188. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  189. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  190. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  191. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  192. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  193. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  194. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  195. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  196. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  197. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  198. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  199. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  200. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  201. package/test-vectors/catalog/section-codes.json +31 -1
  202. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  203. package/test-vectors/catalog-validation.json +101 -5
  204. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  205. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  206. package/dist/fec-codec.d.ts +0 -32
  207. package/dist/fec-codec.d.ts.map +0 -1
  208. package/dist/fec-codec.js +0 -47
  209. package/dist/fec-codec.js.map +0 -7
  210. package/src/fec-codec.ts +0 -61
@@ -150,26 +150,30 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
150
150
  const authLength = view2.getUint16(2, false);
151
151
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
152
152
  }
153
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
153
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
154
154
  if (declaredEnd > payload.length)
155
155
  return null;
156
156
  if (options?.skipFecId) {
157
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
157
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
158
158
  }
159
+ const overlay = options?.overlayDeclared === true && rapFlag;
159
160
  if (fecType === 1) {
160
- const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
161
+ const fecStart = payload.length - sourceFecTrailerSize(overlay);
161
162
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
162
163
  return null;
163
164
  }
164
- return { hasFecId: true };
165
+ return { hasFecId: true, hasOverlayFecId: overlay };
165
166
  }
166
- if (fecType !== 0)
167
+ if (fecType !== 0 || overlay)
167
168
  return null;
168
169
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
169
- return { hasFecId: false };
170
+ return { hasFecId: false, hasOverlayFecId: false };
170
171
  }
171
172
  return null;
172
173
  }
174
+ function sourceFecTrailerSize(overlay) {
175
+ return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
176
+ }
173
177
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
174
178
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
175
179
  return {
@@ -222,15 +226,16 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
222
226
  if ("rejection" in layoutResult)
223
227
  return layoutResult;
224
228
  const { layout } = layoutResult;
225
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
229
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
226
230
  if (!trailerLayout) {
227
231
  if (!options?.skipFecId && header.fecType === 1) {
228
232
  const observed = payload.length - layout.dataEnd;
229
- if (observed !== SOURCE_FEC_PAYLOAD_ID_SIZE) {
233
+ const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
234
+ if (observed !== expected) {
230
235
  return {
231
236
  rejection: {
232
237
  gate: "source-fec-payload-id-width-mismatch",
233
- detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${SOURCE_FEC_PAYLOAD_ID_SIZE} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
238
+ detail: `producer wrote a ${observed}-byte Source FEC Payload ID, ISO/IEC 23008-1 \xA7C.5.2 requires ${expected} (payload=${payload.length}, declaredEnd=${layout.dataEnd})`
234
239
  }
235
240
  };
236
241
  }
@@ -257,10 +262,13 @@ function extractPlannedMfu(mmtpPacket, result) {
257
262
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
258
263
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
259
264
  const data = payload.subarray(mfuOffset, dataEnd);
260
- const fecPayloadId = trailerLayout.hasFecId ? {
261
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, SOURCE_FEC_PAYLOAD_ID_SIZE).getUint32(0, false)
262
- } : null;
263
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
265
+ const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
266
+ const ssIdAt = (offset) => ({
267
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
268
+ });
269
+ const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
270
+ const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
271
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
264
272
  }
265
273
  function sourceFecPayloadIdOf(mmtpPacket, header) {
266
274
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -281,12 +289,86 @@ function sourceFecPayloadIdOf(mmtpPacket, header) {
281
289
  ssId: (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0
282
290
  };
283
291
  }
292
+ var REPAIR_FEC_PID_SIZE = 13;
293
+ function readRepairFecPayloadIdFields(mmtpPacket, parsedHeader) {
294
+ let header;
295
+ if (parsedHeader) {
296
+ header = parsedHeader;
297
+ } else {
298
+ try {
299
+ header = parseMMTPHeader(mmtpPacket);
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
304
+ if (header.packetType !== PACKET_TYPE_REPAIR || header.fecType !== 2)
305
+ return null;
306
+ const off = header.headerLength;
307
+ if (mmtpPacket.length < off + REPAIR_FEC_PID_SIZE)
308
+ return null;
309
+ const ssStart = (mmtpPacket[off] << 24 | mmtpPacket[off + 1] << 16 | mmtpPacket[off + 2] << 8 | mmtpPacket[off + 3]) >>> 0;
310
+ const rsbLength = mmtpPacket[off + 4] << 16 | mmtpPacket[off + 5] << 8 | mmtpPacket[off + 6];
311
+ const rsId = mmtpPacket[off + 7] << 16 | mmtpPacket[off + 8] << 8 | mmtpPacket[off + 9];
312
+ const ssbLength = mmtpPacket[off + 10] << 16 | mmtpPacket[off + 11] << 8 | mmtpPacket[off + 12];
313
+ return {
314
+ packetId: header.packetId,
315
+ ssStart,
316
+ rsbLength,
317
+ rsId,
318
+ ssbLength,
319
+ dataOffset: off + REPAIR_FEC_PID_SIZE
320
+ };
321
+ }
322
+ function parseMoqRepairFrameWithHeader(frame, header) {
323
+ return moqRepairFrameFrom(frame, readRepairFecPayloadIdFields(frame, header));
324
+ }
325
+ function moqRepairFrameFrom(frame, repairId) {
326
+ if (!repairId)
327
+ return null;
328
+ const symbolData = frame.subarray(repairId.dataOffset);
329
+ if (repairId.rsbLength === 0 || repairId.ssbLength === 0 || repairId.rsId >= repairId.rsbLength || symbolData.length === 0)
330
+ return null;
331
+ return {
332
+ packetId: repairId.packetId,
333
+ ssStart: repairId.ssStart,
334
+ rsbLength: repairId.rsbLength,
335
+ rsId: repairId.rsId,
336
+ ssbLength: repairId.ssbLength,
337
+ symbolData
338
+ };
339
+ }
340
+
341
+ // ../mmt-base/dist/net-constants.js
342
+ var DEFAULT_AMT_RELAY_PORT = 2268;
284
343
 
285
344
  // ../mmt-base/dist/ntp-short.js
286
345
  var NTP_SHORT_BITS = 32;
287
346
  var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
288
347
  var NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1);
289
348
 
349
+ // ../mmt-base/dist/serial-number.js
350
+ var SERIAL32_SPAN = 4294967296;
351
+ var SERIAL32_HALF = 2147483648;
352
+ function assertUint32(value, name) {
353
+ if (!Number.isInteger(value) || value < 0 || value >= SERIAL32_SPAN) {
354
+ throw new RangeError(`${name} must be a uint32 (got ${value})`);
355
+ }
356
+ }
357
+ function serial32Add(s, n) {
358
+ assertUint32(s, "s");
359
+ if (!Number.isInteger(n) || n <= -SERIAL32_HALF || n >= SERIAL32_HALF) {
360
+ throw new RangeError(`serial addend must lie in (-2^31, 2^31) (got ${n})`);
361
+ }
362
+ return (s + n + SERIAL32_SPAN) % SERIAL32_SPAN;
363
+ }
364
+ function serial32Distance(from, to) {
365
+ return to - from >>> 0;
366
+ }
367
+ function serial32Precedes(a, b) {
368
+ const distance = serial32Distance(a, b);
369
+ return distance !== 0 && distance < SERIAL32_HALF;
370
+ }
371
+
290
372
  // ../mmt-base/dist/fec-block-profile.js
291
373
  var FEC_BLOCK_PROFILES = Object.freeze([
292
374
  "iso-ssbg1-v1"
@@ -302,6 +384,35 @@ function parseFecBlockProfile(value, where) {
302
384
  }
303
385
  throw new Error(`${where} must be "iso-ssbg1-v1" (got ${JSON.stringify(value)})`);
304
386
  }
387
+ var SSBG1_LENGTH_FIELD_BYTES = 2;
388
+ function ssbg1MaxPacketLength(symbolSize) {
389
+ return symbolSize - SSBG1_LENGTH_FIELD_BYTES;
390
+ }
391
+ function ssbg1FitsSymbol(packetLength, symbolSize) {
392
+ return Number.isSafeInteger(packetLength) && packetLength >= 0 && packetLength <= ssbg1MaxPacketLength(symbolSize) && packetLength <= 65535;
393
+ }
394
+ function trimSsbg1SourceSymbol(symbol) {
395
+ if (symbol.byteLength < SSBG1_LENGTH_FIELD_BYTES)
396
+ return null;
397
+ const length = symbol[0] << 8 | symbol[1];
398
+ const end = SSBG1_LENGTH_FIELD_BYTES + length;
399
+ if (end > symbol.byteLength)
400
+ return null;
401
+ for (let i = end; i < symbol.byteLength; i++) {
402
+ if (symbol[i] !== 0)
403
+ return null;
404
+ }
405
+ return symbol.subarray(SSBG1_LENGTH_FIELD_BYTES, end);
406
+ }
407
+ function isoBlockContains(ssStart, ssbLength, ssId) {
408
+ return serial32Distance(ssStart, ssId) < ssbLength;
409
+ }
410
+ function isoBlocksBehindLowerBound(a, b, kMax) {
411
+ if (!Number.isSafeInteger(kMax) || kMax <= 0) {
412
+ throw new Error(`iso-ssbg1-v1 block horizon needs a positive maximum K (got ${kMax})`);
413
+ }
414
+ return serial32Precedes(a, b) ? Math.floor(serial32Distance(a, b) / kMax) : 0;
415
+ }
305
416
 
306
417
  // ../mmt-base/dist/catalog-fec-source.js
307
418
  var ALL_ROLES = Object.freeze(["video", "audio"]);
@@ -315,6 +426,269 @@ function isoBlockSpanUsable(fec) {
315
426
  const ms = block["interleaveDepthMs"];
316
427
  return ms === void 0 || typeof ms === "number" && Number.isSafeInteger(ms) && ms >= 0;
317
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
+ }
318
692
 
319
693
  // src/mfu-reassembler.ts
320
694
  function fragmentProvenance(fragment) {
@@ -3161,8 +3535,14 @@ var SampleCombiner = class {
3161
3535
  /**
3162
3536
  * Add one reassembled data unit. Returns the combined sample once every
3163
3537
  * constituent data unit has arrived and totals the authored size.
3538
+ *
3539
+ * `sampleSize` is the authored size the host resolves for the sample as the
3540
+ * data unit completes. It stands in only when no size was registered, which
3541
+ * happens when the data unit's FI=0/FI=1 reached the reassembler without the
3542
+ * host's own FT=2 parse: an FEC-recovered first fragment completed by source
3543
+ * fragments, or one decoded before its source copy arrived.
3164
3544
  */
3165
- addMfu(mfu) {
3545
+ addMfu(mfu, sampleSize) {
3166
3546
  if (mfu.movieFragmentSequenceNumber === void 0 || mfu.sampleNumber === void 0) {
3167
3547
  this.#stats.passthroughSamples++;
3168
3548
  return fromPassthrough(mfu);
@@ -3178,7 +3558,7 @@ var SampleCombiner = class {
3178
3558
  return null;
3179
3559
  }
3180
3560
  const dataLen = mfu.data.byteLength;
3181
- const authoredSize = this.#authoredSizes.get(key);
3561
+ const authoredSize = this.#authoredSizes.get(key) ?? sampleSize;
3182
3562
  if (offset === 0 && !this.#pending.has(key)) {
3183
3563
  const passesThrough = authoredSize === void 0 ? !this.#requireAuthoredSize : dataLen === authoredSize;
3184
3564
  if (passesThrough) {
@@ -3472,6 +3852,12 @@ if (void 0) {
3472
3852
  const out = c.addMfu(mfu(1, 9, 17, 5, [6, 7, 8, 9, 10], 1001n, false));
3473
3853
  expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
3474
3854
  });
3855
+ test("a size handed with the data unit completes a sample no head registered", () => {
3856
+ const c = combiner({ requireAuthoredSize: true });
3857
+ const out = c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5);
3858
+ expect(out?.data).toEqual(new Uint8Array([1, 2, 3, 4, 5]));
3859
+ expect(c.addMfu(mfu(1, 9, 17, 0, [1, 2, 3, 4, 5], 1000n, true), 5)).toBeNull();
3860
+ });
3475
3861
  test("duplicate offset is rejected", () => {
3476
3862
  const c = combiner();
3477
3863
  c.registerAuthoredSize(void 0, 1, 9, 17, 10);
@@ -5439,6 +5825,7 @@ function isFmp4Box(data) {
5439
5825
  const type = String.fromCharCode(data[4], data[5], data[6], data[7]);
5440
5826
  return FMPU_BOX_TYPES.has(type);
5441
5827
  }
5828
+ var MAX_AWAITING_TIMING_HEADS = 8;
5442
5829
  var MmtpContainerParser = class _MmtpContainerParser {
5443
5830
  constructor(config) {
5444
5831
  this.#tracks = /* @__PURE__ */ new Map();
@@ -5497,6 +5884,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5497
5884
  * reordering into the parser. */
5498
5885
  this.#reliableMoqStartupGate = /* @__PURE__ */ new Map();
5499
5886
  this.#disposed = false;
5887
+ this.#replayingAwaitingTiming = false;
5500
5888
  this.#fedObjects = 0;
5501
5889
  this.#reassemblerFragmentsFed = 0;
5502
5890
  this.#reassemblerDataUnitsReturned = 0;
@@ -5589,6 +5977,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5589
5977
  #reorderStats;
5590
5978
  #reliableMoqStartupGate;
5591
5979
  #disposed;
5980
+ #replayingAwaitingTiming;
5592
5981
  #fedObjects;
5593
5982
  #reassemblerFragmentsFed;
5594
5983
  #reassemblerDataUnitsReturned;
@@ -5838,7 +6227,8 @@ var MmtpContainerParser = class _MmtpContainerParser {
5838
6227
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
5839
6228
  */
5840
6229
  #drop(reason) {
5841
- this.#countOutcome(`drop:${reason}`);
6230
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason);
6231
+ else this.#countOutcome(`drop:${reason}`);
5842
6232
  return null;
5843
6233
  }
5844
6234
  get reorderDiagnostics() {
@@ -5861,6 +6251,12 @@ var MmtpContainerParser = class _MmtpContainerParser {
5861
6251
  for (const combiner of this.#sampleCombiners.values()) {
5862
6252
  combiner.cleanupTimeouts(timeoutMs);
5863
6253
  }
6254
+ const now = Date.now();
6255
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
6256
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0].arrivedAt > timeoutMs) {
6257
+ awaitingTiming.shift();
6258
+ }
6259
+ }
5864
6260
  }
5865
6261
  /**
5866
6262
  * Phase 1 of two-phase parsing. Returns structured header info for FEC feeding.
@@ -5941,7 +6337,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5941
6337
  byteLength: packet.byteLength
5942
6338
  };
5943
6339
  }
5944
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
6340
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
5945
6341
  const rawSymbol = packet.subarray(0, packet.length - 4);
5946
6342
  try {
5947
6343
  this.#sourceSymbolCb(info.packetId, info.fecPayloadId.ssId, rawSymbol);
@@ -5989,6 +6385,7 @@ var MmtpContainerParser = class _MmtpContainerParser {
5989
6385
  }
5990
6386
  return this.#drop("fragment-timing-refused");
5991
6387
  }
6388
+ this.#replayAwaitingTiming(streamKey, resolver2);
5992
6389
  return {
5993
6390
  kind: "fragment",
5994
6391
  packet: info,
@@ -6012,7 +6409,18 @@ var MmtpContainerParser = class _MmtpContainerParser {
6012
6409
  mfuDuHeader.movieFragmentSequenceNumber,
6013
6410
  mfuDuHeader.sampleNumber
6014
6411
  );
6015
- if (!headTiming) return this.#drop("mfu-sample-timing-missing");
6412
+ if (!headTiming) {
6413
+ this.#awaitTiming(streamKey, {
6414
+ packet,
6415
+ options,
6416
+ parsed,
6417
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
6418
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
6419
+ sampleNumber: mfuDuHeader.sampleNumber,
6420
+ arrivedAt: Date.now()
6421
+ });
6422
+ return this.#drop("mfu-sample-timing-missing");
6423
+ }
6016
6424
  const offset = mfuDuHeader.offset;
6017
6425
  if (!Number.isSafeInteger(offset) || offset < 0 || offset >= headTiming.size)
6018
6426
  return this.#drop("mfu-offset-out-of-range");
@@ -6088,16 +6496,17 @@ var MmtpContainerParser = class _MmtpContainerParser {
6088
6496
  const sampleNumber = assembled.sampleNumber;
6089
6497
  if (movieFragmentSequenceNumber === void 0 || sampleNumber === void 0)
6090
6498
  return this.#drop("assembled-identity-missing");
6091
- if (!resolver.sampleTiming(
6499
+ const assembledTiming = resolver.sampleTiming(
6092
6500
  assembled.mpuSequenceNumber,
6093
6501
  movieFragmentSequenceNumber,
6094
6502
  sampleNumber
6095
- )) return this.#drop("assembled-timing-missing");
6503
+ );
6504
+ if (!assembledTiming) return this.#drop("assembled-timing-missing");
6096
6505
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
6097
6506
  return this.#drop("assembled-mpu-mismatch");
6098
6507
  let combined;
6099
6508
  try {
6100
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled);
6509
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size);
6101
6510
  } catch (error) {
6102
6511
  if (!(error instanceof SampleCombineError)) throw error;
6103
6512
  console.warn(
@@ -6406,9 +6815,37 @@ var MmtpContainerParser = class _MmtpContainerParser {
6406
6815
  if (existing) return existing.resolver;
6407
6816
  if (!create) return null;
6408
6817
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples);
6409
- this.#timingStreams.set(streamKey, { packetId, resolver });
6818
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] });
6410
6819
  return resolver;
6411
6820
  }
6821
+ #awaitTiming(streamKey, head) {
6822
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming;
6823
+ if (!awaitingTiming) return;
6824
+ awaitingTiming.push(head);
6825
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift();
6826
+ }
6827
+ /**
6828
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
6829
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
6830
+ * FEC path routes a source symbol that already arrived a second time.
6831
+ */
6832
+ #replayAwaitingTiming(streamKey, resolver) {
6833
+ const state = this.#timingStreams.get(streamKey);
6834
+ if (!state || state.awaitingTiming.length === 0) return;
6835
+ const ready = state.awaitingTiming.filter((head) => resolver.sampleTiming(
6836
+ head.mpuSequenceNumber,
6837
+ head.movieFragmentSequenceNumber,
6838
+ head.sampleNumber
6839
+ ));
6840
+ if (ready.length === 0) return;
6841
+ state.awaitingTiming = state.awaitingTiming.filter((head) => !ready.includes(head));
6842
+ this.#replayingAwaitingTiming = true;
6843
+ try {
6844
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed);
6845
+ } finally {
6846
+ this.#replayingAwaitingTiming = false;
6847
+ }
6848
+ }
6412
6849
  #dropTimingStream(streamKey) {
6413
6850
  const state = this.#timingStreams.get(streamKey);
6414
6851
  if (!state) return;
@@ -6898,197 +7335,6 @@ function createWasmMmtpContainerParser(config) {
6898
7335
  });
6899
7336
  }
6900
7337
 
6901
- // src/multicast-auth-catalog.ts
6902
- var RAW_ED25519_KEY_LENGTH = 32;
6903
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
6904
- var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
6905
- function encodeBase64Url(bytes) {
6906
- let output = "";
6907
- for (let i = 0; i < bytes.length; i += 3) {
6908
- const b0 = bytes[i];
6909
- const b1 = bytes[i + 1];
6910
- const b2 = bytes[i + 2];
6911
- output += BASE64URL_ALPHABET[b0 >> 2];
6912
- output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
6913
- if (b1 === void 0) break;
6914
- output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
6915
- if (b2 === void 0) break;
6916
- output += BASE64URL_ALPHABET[b2 & 63];
6917
- }
6918
- return output;
6919
- }
6920
- var BASE64URL_DECODE_TABLE = (() => {
6921
- const table = new Int8Array(128).fill(-1);
6922
- for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
6923
- table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
6924
- }
6925
- return table;
6926
- })();
6927
- function decodeBase64Url(text) {
6928
- if (text.length % 4 === 1) {
6929
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
6930
- }
6931
- const bytes = [];
6932
- let buffer = 0;
6933
- let bits = 0;
6934
- for (let i = 0; i < text.length; i++) {
6935
- const code = text.charCodeAt(i);
6936
- const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
6937
- if (value === void 0 || value < 0) {
6938
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
6939
- }
6940
- buffer = buffer << 6 | value;
6941
- bits += 6;
6942
- if (bits >= 8) {
6943
- bits -= 8;
6944
- bytes.push(buffer >> bits & 255);
6945
- }
6946
- }
6947
- const decoded = Uint8Array.from(bytes);
6948
- if (encodeBase64Url(decoded) !== text) {
6949
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
6950
- }
6951
- return decoded;
6952
- }
6953
- function decodeAuthScope(authScope) {
6954
- const bytes = decodeBase64Url(authScope);
6955
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH) {
6956
- throw new Error(
6957
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH} raw bytes, got ${bytes.byteLength}`
6958
- );
6959
- }
6960
- return bytes;
6961
- }
6962
- function decodeEd25519PublicKey(publicKey) {
6963
- const bytes = decodeBase64Url(publicKey);
6964
- if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
6965
- throw new Error(
6966
- `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
6967
- );
6968
- }
6969
- return bytes;
6970
- }
6971
- function isNonEmptyString(value) {
6972
- return typeof value === "string" && value.length > 0;
6973
- }
6974
- function isValidAuthScopeField(value) {
6975
- if (!isNonEmptyString(value)) return false;
6976
- try {
6977
- decodeAuthScope(value);
6978
- return true;
6979
- } catch {
6980
- return false;
6981
- }
6982
- }
6983
- function isValidPublicKeyField(value) {
6984
- if (!isNonEmptyString(value)) return false;
6985
- try {
6986
- decodeEd25519PublicKey(value);
6987
- return true;
6988
- } catch {
6989
- return false;
6990
- }
6991
- }
6992
- function hasOnlyKeys(object, allowed) {
6993
- const allowedKeys = new Set(allowed);
6994
- return Object.keys(object).every((key) => allowedKeys.has(key));
6995
- }
6996
- function isMulticastAuthTrackConfig(obj) {
6997
- if (typeof obj !== "object" || obj === null) return false;
6998
- const o = obj;
6999
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
7000
- }
7001
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
7002
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
7003
- function hasUniqueMulticastAuthTrackBindings(tracks) {
7004
- const bindings = tracks.flatMap((track) => {
7005
- if (typeof track !== "object" || track === null) return [];
7006
- const value = track;
7007
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
7008
- return [];
7009
- }
7010
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
7011
- });
7012
- return new Set(bindings).size === bindings.length;
7013
- }
7014
- function isMulticastAuthConfig(obj) {
7015
- if (typeof obj !== "object" || obj === null) return false;
7016
- const o = obj;
7017
- if (o["scheme"] !== "bc-provenance") return false;
7018
- if (o["hash"] !== "blake3") return false;
7019
- if (o["sig"] !== "ed25519") return false;
7020
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
7021
- if (!isValidPublicKeyField(o["publicKey"])) return false;
7022
- if (!isNonEmptyString(o["keyId"])) return false;
7023
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
7024
- if (o["previousKey"] === o["publicKey"]) return false;
7025
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
7026
- if (o["enforcement"] !== void 0) {
7027
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
7028
- }
7029
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
7030
- const tracks = o["tracks"];
7031
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
7032
- const typedTracks = tracks;
7033
- const scopes = typedTracks.map((t) => t.authScope);
7034
- if (new Set(scopes).size !== scopes.length) return false;
7035
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
7036
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
7037
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
7038
- return true;
7039
- }
7040
- function resolveMulticastAuthMode(playerMode, auth) {
7041
- if (playerMode !== void 0) return playerMode;
7042
- if (auth === void 0) return "off";
7043
- return auth.enforcement ?? "shadow";
7044
- }
7045
- function resolveMulticastAuthCatalog(catalog, playerMode) {
7046
- if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
7047
- throw new Error("[multicast-auth-catalog] catalog must be an object");
7048
- }
7049
- const root = catalog;
7050
- const rawAuth = root["multicast.auth"];
7051
- if (rawAuth === void 0) {
7052
- if (playerMode === "enforce") {
7053
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
7054
- }
7055
- return void 0;
7056
- }
7057
- if (!isMulticastAuthConfig(rawAuth)) {
7058
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
7059
- }
7060
- const rawTracks = root["tracks"];
7061
- if (!Array.isArray(rawTracks)) {
7062
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
7063
- }
7064
- const catalogTrackNames = new Set(
7065
- rawTracks.flatMap(
7066
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
7067
- )
7068
- );
7069
- for (const track of rawAuth.tracks) {
7070
- if (!catalogTrackNames.has(track.mediaTrack)) {
7071
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
7072
- }
7073
- if (!catalogTrackNames.has(track.manifestTrack)) {
7074
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
7075
- }
7076
- }
7077
- return {
7078
- keyId: rawAuth.keyId,
7079
- acceptedPublicKeys: [
7080
- decodeEd25519PublicKey(rawAuth.publicKey),
7081
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
7082
- ],
7083
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
7084
- compaction: rawAuth.compaction,
7085
- tracks: rawAuth.tracks.map((track) => ({
7086
- ...track,
7087
- authScope: decodeAuthScope(track.authScope)
7088
- }))
7089
- };
7090
- }
7091
-
7092
7338
  // src/repair-layers.ts
7093
7339
  var REPAIR_PRIORITY_MIN = 192;
7094
7340
  var REPAIR_PRIORITY_MAX = 255;
@@ -7096,6 +7342,7 @@ var DEFAULT_REPAIR_PRIORITY = 240;
7096
7342
  var MAX_RAPTORQ_SOURCE_SYMBOLS = 56403;
7097
7343
  var MAX_REPAIR_SYMBOLS = 16777215;
7098
7344
  var MAX_ENCODING_SYMBOL_ID = 16777215;
7345
+ var MAX_REED_SOLOMON_BLOCK_SYMBOLS = 255;
7099
7346
  var RepairContractError = class extends Error {
7100
7347
  constructor(code, path, message) {
7101
7348
  super(`[repair-layers:${code}] ${path}: ${message}`);
@@ -7278,11 +7525,12 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7278
7525
  if (layered && !positiveInteger(source.sourceSymbols)) {
7279
7526
  fail("track_fec", `${source.path}.sourceSymbols`, "layered or overlay repair needs a positive integer sourceSymbols on the source");
7280
7527
  }
7281
- if (layered && source.algorithm !== "raptorq") {
7528
+ const reedSolomon = source.algorithm === "reed-solomon";
7529
+ if (layered && source.algorithm !== "raptorq" && !reedSolomon) {
7282
7530
  fail(
7283
7531
  "track_fec",
7284
7532
  `${source.path}.algorithm`,
7285
- "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)"
7286
7534
  );
7287
7535
  }
7288
7536
  let layerZeroPriority = DEFAULT_REPAIR_PRIORITY;
@@ -7341,6 +7589,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7341
7589
  `overlay sourceSymbols + repairSymbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7342
7590
  );
7343
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
+ }
7344
7599
  overlays.push({ repairTrackName: d.name, scope: "keyframe", sourceSymbols, repairSymbols, priority: d.priority });
7345
7600
  }
7346
7601
  let offset = layerZeroSymbols;
@@ -7385,6 +7640,13 @@ function assembleRepairLayers(source, descriptors, fail = throwRepairContractErr
7385
7640
  `sourceSymbols + total base repair symbols - 1 exceeds the 24-bit ESI space (${MAX_ENCODING_SYMBOL_ID})`
7386
7641
  );
7387
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
+ }
7388
7650
  return { sourceTrackName: source.name, baseLayers, overlays, totalBaseRepairSymbols };
7389
7651
  }
7390
7652
 
@@ -7472,13 +7734,22 @@ var CmsfCatalogValidationError = class extends Error {
7472
7734
  function catalogError(code, path, message) {
7473
7735
  throw new CmsfCatalogValidationError(code, path, message);
7474
7736
  }
7475
- function validateCmsfMmtpCatalog(value) {
7737
+ function validateNetworkSourceRelays(sources, path) {
7738
+ if (!Array.isArray(sources)) return;
7739
+ sources.forEach((source, i) => {
7740
+ const s = source;
7741
+ if (s?.["type"] === "amt" && s["discovery"] === "driad" && s["relay"] !== void 0) {
7742
+ catalogError("multicast_network_source", `${path}[${i}].relay`, 'relay must be omitted with discovery "driad"');
7743
+ }
7744
+ });
7745
+ }
7746
+ function validateCmsfMmtpCatalog(value, options = {}) {
7476
7747
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
7477
7748
  catalogError("catalog_object", "$", "catalog must be an object");
7478
7749
  }
7479
7750
  const catalog = value;
7480
7751
  const rawVersion = catalog["version"];
7481
- const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") ? 1 : NaN : rawVersion;
7752
+ const normalizedVersion = typeof rawVersion === "string" ? Number.isFinite(Number(rawVersion)) ? Number(rawVersion) : rawVersion.startsWith("draft-ietf-moq-catalogformat") || rawVersion === "draft-01" ? 1 : NaN : rawVersion;
7482
7753
  if (!Number.isInteger(normalizedVersion) || normalizedVersion <= 0) {
7483
7754
  catalogError("catalog_version", "$.version", "version must be a positive integer or a recognized format tag");
7484
7755
  }
@@ -7493,6 +7764,22 @@ function validateCmsfMmtpCatalog(value) {
7493
7764
  "commonTrackFields is retired; every track carries its own fields"
7494
7765
  );
7495
7766
  }
7767
+ const initDataList = catalog["initDataList"];
7768
+ if (initDataList !== void 0) {
7769
+ if (!Array.isArray(initDataList)) {
7770
+ catalogError("catalog_init_data_list", "$.initDataList", "initDataList must be an array");
7771
+ }
7772
+ initDataList.forEach((entry, i) => {
7773
+ const e = entry;
7774
+ const entryPath = `$.initDataList[${i}]`;
7775
+ 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) {
7776
+ catalogError("catalog_init_data_list", entryPath, "entry needs a non-empty string id and type");
7777
+ }
7778
+ if (e["type"] === "inline" && (typeof e["data"] !== "string" || e["data"].length === 0)) {
7779
+ catalogError("catalog_init_data_list", `${entryPath}.data`, 'an "inline" entry needs non-empty data');
7780
+ }
7781
+ });
7782
+ }
7496
7783
  const tracks = catalog["tracks"];
7497
7784
  const trackRecords = [];
7498
7785
  const positiveInteger2 = (input) => Number.isSafeInteger(input) && input > 0;
@@ -7544,6 +7831,14 @@ function validateCmsfMmtpCatalog(value) {
7544
7831
  if (keyframeIntervalMs !== void 0 && !positiveNumber(keyframeIntervalMs) || keyframeIntervalTicks !== void 0 && !positiveInteger2(keyframeIntervalTicks)) {
7545
7832
  catalogError("track_keyframe_interval", path, "keyframe interval fields must be positive numbers");
7546
7833
  }
7834
+ const anchor = track["presentationAnchorTicks"];
7835
+ if (anchor !== void 0 && !Number.isSafeInteger(anchor)) {
7836
+ catalogError("track_presentation_anchor", `${path}.presentationAnchorTicks`, "must be a safe integer");
7837
+ }
7838
+ const initRef = track["initRef"];
7839
+ if (initRef !== void 0 && (typeof initRef !== "string" || initRef.length === 0)) {
7840
+ catalogError("track_init_ref", `${path}.initRef`, "must be a non-empty string");
7841
+ }
7547
7842
  if (packaging === "fec-repair") {
7548
7843
  rejectRepairTrackGeometry(path, track, catalogError);
7549
7844
  validateRepairTrackFields(describeRepairTrack(name, path, track), catalogError);
@@ -7551,9 +7846,8 @@ function validateCmsfMmtpCatalog(value) {
7551
7846
  rejectRepairFieldsOnMediaTrack(path, track, catalogError);
7552
7847
  }
7553
7848
  if (packaging === "mmtp") {
7554
- const mmtpMode = track["mmtpMode"];
7555
- if (mmtpMode !== "mpu" && mmtpMode !== "mfu") {
7556
- catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mpu or mfu");
7849
+ if (track["mmtpMode"] !== "mfu") {
7850
+ catalogError("track_mmtp_mode", `${path}.mmtpMode`, "must be mfu");
7557
7851
  }
7558
7852
  if (!positiveInteger2(timescale)) {
7559
7853
  catalogError("track_timescale", `${path}.timescale`, "must be a positive integer");
@@ -7576,8 +7870,8 @@ function validateCmsfMmtpCatalog(value) {
7576
7870
  }
7577
7871
  const config = fec;
7578
7872
  const algorithm = config["algorithm"];
7579
- if (algorithm !== "none" && algorithm !== "raptorq" && algorithm !== "reed-solomon") {
7580
- catalogError("track_fec", `${path}.fec.algorithm`, "algorithm is not supported");
7873
+ if (typeof algorithm !== "string" || algorithm.length === 0) {
7874
+ catalogError("track_fec", `${path}.fec.algorithm`, "must be a non-empty string");
7581
7875
  }
7582
7876
  if ("interleaveDepth" in config || "interleaveMs" in config) {
7583
7877
  catalogError("track_fec", `${path}.fec`, "interleaveDepthMs is the only supported interleave field");
@@ -7606,6 +7900,9 @@ function validateCmsfMmtpCatalog(value) {
7606
7900
  }
7607
7901
  }
7608
7902
  readFecBlockProfile(config["blockProfile"], `${path}.fec.blockProfile`, algorithm !== "none", catalogError);
7903
+ if (algorithm !== "none" && config["symbolSize"] < ISO_SSBG1_MIN_SYMBOL_SIZE) {
7904
+ catalogError("track_fec", `${path}.fec.symbolSize`, "iso-ssbg1-v1 symbolSize must be at least 14");
7905
+ }
7609
7906
  }
7610
7907
  }
7611
7908
  const repairDescriptors = trackRecords.flatMap(
@@ -7655,19 +7952,34 @@ function validateCmsfMmtpCatalog(value) {
7655
7952
  const timescale = BigInt(track["timescale"]);
7656
7953
  const durationTicks = track["groupDurationTicks"];
7657
7954
  const ticks = durationTicks !== void 0 ? BigInt(durationTicks) : BigInt(track["groupDurationMs"]) * timescale / 1000n;
7658
- const anchor = switchingSets.get(altGroup);
7659
- if (anchor && ticks * anchor.timescale !== anchor.ticks * timescale) {
7660
- catalogError("track_switching_set", `$.tracks[${index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
7955
+ const framerate = track["framerate"];
7956
+ const intraOnly = positiveNumber(framerate) && Math.abs(Number(ticks) * framerate - Number(timescale)) <= Number(timescale) * 1e-3;
7957
+ const members = switchingSets.get(altGroup) ?? [];
7958
+ members.push({ index, name: track["name"], ticks, timescale, intraOnly });
7959
+ switchingSets.set(altGroup, members);
7960
+ }
7961
+ for (const [altGroup, members] of switchingSets) {
7962
+ const anchor = members.find((member) => !member.intraOnly) ?? members[0];
7963
+ for (const member of members) {
7964
+ if (member === anchor || member.ticks * anchor.timescale === anchor.ticks * member.timescale) continue;
7965
+ const nests = member.intraOnly && !anchor.intraOnly && anchor.ticks * member.timescale % (member.ticks * anchor.timescale) === 0n;
7966
+ if (!nests) {
7967
+ catalogError("track_switching_set", `$.tracks[${member.index}]`, `group duration does not match ${JSON.stringify(anchor.name)} in altGroup ${altGroup}`);
7968
+ }
7661
7969
  }
7662
- if (!anchor) switchingSets.set(altGroup, { name: track["name"], ticks, timescale });
7663
7970
  }
7664
7971
  const multicast = catalog["multicast"];
7665
7972
  if (typeof multicast === "object" && multicast !== null && !Array.isArray(multicast)) {
7973
+ validateNetworkSourceRelays(multicast["networkSource"], "$.multicast.networkSource");
7666
7974
  const endpoints = multicast["endpoints"];
7667
7975
  if (Array.isArray(endpoints)) {
7668
7976
  for (let endpointIndex = 0; endpointIndex < endpoints.length; endpointIndex++) {
7669
7977
  const endpoint = endpoints[endpointIndex];
7670
7978
  if (typeof endpoint !== "object" || endpoint === null || Array.isArray(endpoint)) continue;
7979
+ validateNetworkSourceRelays(
7980
+ endpoint["networkSource"],
7981
+ `$.multicast.endpoints[${endpointIndex}].networkSource`
7982
+ );
7671
7983
  if ("relayAddress" in endpoint) {
7672
7984
  catalogError(
7673
7985
  "multicast_relay_address",
@@ -7707,21 +8019,14 @@ function validateCmsfMmtpCatalog(value) {
7707
8019
  }
7708
8020
  }
7709
8021
  }
7710
- try {
7711
- resolveMulticastAuthCatalog(catalog);
7712
- } catch (error) {
7713
- catalogError(
7714
- "multicast_auth",
7715
- "$.multicast.auth",
7716
- error instanceof Error ? error.message : "invalid multicast.auth v2 block"
7717
- );
7718
- }
8022
+ const [multicastIssue] = multicastCatalogIssues(catalog, options);
8023
+ if (multicastIssue) catalogError(multicastIssue.code, multicastIssue.path, multicastIssue.message);
7719
8024
  validateArchive(catalog);
7720
8025
  return catalog;
7721
8026
  }
7722
8027
 
7723
8028
  // src/no-modules.ts
7724
- import { catalogFecInterleaveMs, computeFecTimeout } from "@blockcast/mmt-fec";
8029
+ import { catalogFecInterleaveMs, fecBlockBudgetMs as fecBlockBudgetMs2, fecBlockDeadlineMs } from "@blockcast/mmt-fec";
7725
8030
 
7726
8031
  // src/fec-state.ts
7727
8032
  var FEC_INACTIVE_REASONS = Object.freeze([
@@ -7738,13 +8043,13 @@ var INACTIVE = Object.freeze({
7738
8043
  function recordOf2(value) {
7739
8044
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7740
8045
  }
7741
- function isPositiveSafeInteger(value) {
8046
+ function isPositiveSafeInteger2(value) {
7742
8047
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
7743
8048
  }
7744
8049
  function catalogDeclaresFec(fec) {
7745
8050
  const block = recordOf2(fec);
7746
- if (block === void 0 || block["algorithm"] === "none") return false;
7747
- return isPositiveSafeInteger(block["sourceSymbols"]) && isPositiveSafeInteger(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block);
8051
+ if (block === void 0 || block["algorithm"] === "none" || fecAlgorithmUnimplemented(block["algorithm"])) return false;
8052
+ return isPositiveSafeInteger2(block["sourceSymbols"]) && isPositiveSafeInteger2(block["symbolSize"]) && isFecBlockProfile(block["blockProfile"]) && isoBlockSpanUsable(block) && !catalogFecDeclaresUnconfigurableInstance(block);
7748
8053
  }
7749
8054
  function requireBoolean(value, field) {
7750
8055
  if (typeof value !== "boolean") {
@@ -7772,6 +8077,385 @@ function resolveFecState(evidence) {
7772
8077
  return INACTIVE["reliable-moq"];
7773
8078
  }
7774
8079
 
8080
+ // src/mmtp-fec-session.ts
8081
+ import { deriveFecRetentionBlocks, fecBlockBudgetMs } from "@blockcast/mmt-fec";
8082
+ var PATH_BITS = { moq: 1, multicast: 2 };
8083
+ var MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast;
8084
+ var MmtpFecSession = class {
8085
+ #decoder;
8086
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
8087
+ #blocks = /* @__PURE__ */ new Map();
8088
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
8089
+ #settled = /* @__PURE__ */ new Set();
8090
+ /**
8091
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
8092
+ * received on, or 0 for one the session recovered.
8093
+ */
8094
+ #have = /* @__PURE__ */ new Map();
8095
+ #newest;
8096
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
8097
+ #prunedAt;
8098
+ #repairPacketId;
8099
+ #stats = {
8100
+ sourceSymbols: 0,
8101
+ repairSymbols: 0,
8102
+ blocksClean: 0,
8103
+ blocksRecovered: 0,
8104
+ blocksFailed: 0,
8105
+ blocksReleased: 0,
8106
+ packetsRecovered: 0,
8107
+ packetsLost: 0,
8108
+ dropped: {},
8109
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
8110
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
8111
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 }
8112
+ };
8113
+ /**
8114
+ * @throws when the catalog block lacks or misstates a field the session
8115
+ * needs: the block profile, K, T, `interleaveDepthMs` or
8116
+ * `reorderToleranceMs`. None is defaulted.
8117
+ */
8118
+ constructor(config) {
8119
+ const fec = config?.fec;
8120
+ if (!fec || typeof fec !== "object") {
8121
+ throw new Error("MmtpFecSession: the catalog fec block is required");
8122
+ }
8123
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, "fec.blockProfile");
8124
+ if (fec.algorithm !== void 0 && fec.algorithm !== "raptorq" && fec.algorithm !== "reed-solomon") {
8125
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`);
8126
+ }
8127
+ this.algorithm = fec.algorithm === "reed-solomon" ? "reed-solomon" : "raptorq";
8128
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, "fec.sourceSymbols");
8129
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, "fec.symbolSize");
8130
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, "fec.interleaveDepthMs");
8131
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, "fec.reorderToleranceMs");
8132
+ this.retentionBlocks = deriveFecRetentionBlocks(
8133
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
8134
+ interleaveDepthMs
8135
+ );
8136
+ if (typeof config.Decoder !== "function") {
8137
+ throw new Error("MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required");
8138
+ }
8139
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm);
8140
+ try {
8141
+ decoder.configure_params(this.sourceSymbols, this.symbolSize);
8142
+ } catch (error) {
8143
+ decoder.free();
8144
+ throw error;
8145
+ }
8146
+ this.#decoder = decoder;
8147
+ }
8148
+ /** True once release() ran. */
8149
+ get released() {
8150
+ return this.#decoder === null;
8151
+ }
8152
+ get stats() {
8153
+ return {
8154
+ ...this.#stats,
8155
+ dropped: { ...this.#stats.dropped },
8156
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
8157
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
8158
+ mixedPath: { ...this.#stats.mixedPath }
8159
+ };
8160
+ }
8161
+ /**
8162
+ * Feeds one received source packet: the MMTP packet without its four-byte
8163
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
8164
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
8165
+ * was received; a caller that only subscribes over MoQT can leave it out.
8166
+ *
8167
+ * @returns the protected packets of this packet's block that it recovered,
8168
+ * in SS_ID order, for the caller to feed to its parser with
8169
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
8170
+ */
8171
+ addSource(ssId, packet, path = "moq") {
8172
+ const decoder = this.#decoder;
8173
+ if (!decoder) return this.#drop("source:released");
8174
+ const pathBit = PATH_BITS[path];
8175
+ if (!pathBit) return this.#drop("source:unknown-path");
8176
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 4294967295) return this.#drop("source:bad-ss-id");
8177
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop("source:exceeds-symbol");
8178
+ if (this.#have.has(ssId)) return this.#drop("source:duplicate");
8179
+ this.#have.set(ssId, pathBit);
8180
+ this.#stats.sourceSymbols++;
8181
+ this.#stats.sourceSymbolsByPath[path]++;
8182
+ this.#noteNewest(ssId);
8183
+ const start = this.#blockStartOf(ssId);
8184
+ const block = start === void 0 ? void 0 : this.#blocks.get(start);
8185
+ if (block) {
8186
+ block.received++;
8187
+ block.paths |= pathBit;
8188
+ }
8189
+ let output;
8190
+ try {
8191
+ output = decoder.add_source(ssId, packet, 0);
8192
+ } catch {
8193
+ this.#drop("source:decoder-refused");
8194
+ output = void 0;
8195
+ }
8196
+ const recovered = [];
8197
+ if (start !== void 0 && block) {
8198
+ if (output) {
8199
+ recovered.push(...this.#settleDecoded(start, block, output));
8200
+ } else if (block.received >= block.ssbLength) {
8201
+ this.#settleClean(start);
8202
+ }
8203
+ }
8204
+ this.#retireBehindHorizon();
8205
+ return recovered;
8206
+ }
8207
+ /**
8208
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
8209
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
8210
+ * repair packet fixes its packet ID and a packet of any other is refused.
8211
+ * `path` is where it was received, as for addSource().
8212
+ *
8213
+ * @returns the protected packets this repair symbol recovered, as for
8214
+ * addSource().
8215
+ */
8216
+ addRepair(packet, path = "moq") {
8217
+ const decoder = this.#decoder;
8218
+ if (!decoder) return this.#drop("repair:released");
8219
+ const pathBit = PATH_BITS[path];
8220
+ if (!pathBit) return this.#drop("repair:unknown-path");
8221
+ let header;
8222
+ try {
8223
+ header = parseMMTPHeader(packet);
8224
+ } catch {
8225
+ return this.#drop("repair:malformed");
8226
+ }
8227
+ const frame = parseMoqRepairFrameWithHeader(packet, header);
8228
+ if (!frame) return this.#drop("repair:malformed");
8229
+ if (this.#repairPacketId === void 0) {
8230
+ this.#repairPacketId = frame.packetId;
8231
+ } else if (frame.packetId !== this.#repairPacketId) {
8232
+ return this.#drop("repair:foreign-packet-id");
8233
+ }
8234
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop("repair:symbol-size");
8235
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop("repair:ssb-length");
8236
+ if (this.algorithm === "reed-solomon" && frame.ssbLength + frame.rsbLength > 255) {
8237
+ return this.#drop("repair:rs-block-length");
8238
+ }
8239
+ const start = frame.ssStart;
8240
+ let block = this.#blocks.get(start);
8241
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop("repair:conflicting-ssb-length");
8242
+ if (block?.rsIds.has(frame.rsId)) return this.#drop("repair:duplicate");
8243
+ if (!block) {
8244
+ if (this.#settled.has(start)) return this.#drop("repair:block-settled");
8245
+ if (this.#behindHorizon(start)) return this.#drop("repair:behind-horizon");
8246
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: /* @__PURE__ */ new Set() };
8247
+ this.#countHeld(start, block);
8248
+ this.#blocks.set(start, block);
8249
+ }
8250
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1));
8251
+ if (block.received >= block.ssbLength) {
8252
+ this.#settleClean(start);
8253
+ this.#retireBehindHorizon();
8254
+ return [];
8255
+ }
8256
+ let output;
8257
+ try {
8258
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0);
8259
+ } catch {
8260
+ return this.#drop("repair:decoder-refused");
8261
+ }
8262
+ block.rsIds.add(frame.rsId);
8263
+ this.#stats.repairSymbols++;
8264
+ this.#stats.repairSymbolsByPath[path]++;
8265
+ block.paths |= pathBit;
8266
+ const recovered = output ? this.#settleDecoded(start, block, output) : [];
8267
+ this.#retireBehindHorizon();
8268
+ return recovered;
8269
+ }
8270
+ /**
8271
+ * Frees the decoder and every block. Blocks still unsettled are counted as
8272
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
8273
+ * returns whether this call released anything.
8274
+ */
8275
+ release() {
8276
+ const decoder = this.#decoder;
8277
+ if (!decoder) return false;
8278
+ this.#decoder = null;
8279
+ this.#stats.blocksReleased += this.#blocks.size;
8280
+ for (const block of this.#blocks.values()) this.#noteMixed(block, "released");
8281
+ this.#blocks.clear();
8282
+ this.#settled.clear();
8283
+ this.#have.clear();
8284
+ decoder.free();
8285
+ return true;
8286
+ }
8287
+ #drop(reason) {
8288
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1;
8289
+ return [];
8290
+ }
8291
+ #noteNewest(ssId) {
8292
+ if (this.#newest === void 0 || serial32Precedes(this.#newest, ssId)) this.#newest = ssId;
8293
+ }
8294
+ #blockStartOf(ssId) {
8295
+ for (const [start, block] of this.#blocks) {
8296
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start;
8297
+ }
8298
+ return void 0;
8299
+ }
8300
+ /** Counts the sources of a new block the parser already has, and their paths. */
8301
+ #countHeld(start, block) {
8302
+ for (let i = 0; i < block.ssbLength; i++) {
8303
+ const pathBit = this.#have.get(serial32Add(start, i));
8304
+ if (pathBit === void 0) continue;
8305
+ block.received++;
8306
+ block.paths |= pathBit;
8307
+ }
8308
+ }
8309
+ #noteMixed(block, outcome) {
8310
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++;
8311
+ }
8312
+ /** The decoder's own rule: more than its retention behind, counted from below. */
8313
+ #behindHorizon(start) {
8314
+ const newest = this.#newest;
8315
+ if (newest === void 0) return false;
8316
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks;
8317
+ }
8318
+ #settle(start) {
8319
+ this.#blocks.delete(start);
8320
+ this.#settled.add(start);
8321
+ }
8322
+ #settleClean(start) {
8323
+ const block = this.#blocks.get(start);
8324
+ if (!block) return;
8325
+ this.#settle(start);
8326
+ this.#stats.blocksClean++;
8327
+ this.#noteMixed(block, "clean");
8328
+ try {
8329
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start));
8330
+ } catch {
8331
+ }
8332
+ }
8333
+ /**
8334
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
8335
+ * concatenated: split by T, trim by each symbol's length field, and hand
8336
+ * back the packets the parser does not have yet.
8337
+ */
8338
+ #settleDecoded(start, block, output) {
8339
+ this.#settle(start);
8340
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
8341
+ this.#stats.blocksFailed++;
8342
+ this.#stats.packetsLost += block.ssbLength - block.received;
8343
+ this.#noteMixed(block, "failed");
8344
+ this.#drop("block:decoded-length");
8345
+ return [];
8346
+ }
8347
+ const recovered = [];
8348
+ let refused = 0;
8349
+ for (let i = 0; i < block.ssbLength; i++) {
8350
+ const ssId = serial32Add(start, i);
8351
+ if (this.#have.has(ssId)) continue;
8352
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize);
8353
+ const packet = trimSsbg1SourceSymbol(symbol);
8354
+ if (!packet) {
8355
+ refused++;
8356
+ continue;
8357
+ }
8358
+ this.#have.set(ssId, 0);
8359
+ recovered.push(packet.slice());
8360
+ }
8361
+ if (refused > 0) {
8362
+ this.#stats.blocksFailed++;
8363
+ this.#stats.packetsLost += refused;
8364
+ this.#noteMixed(block, "failed");
8365
+ this.#drop("block:bad-ssbg1-symbol");
8366
+ } else if (recovered.length === 0) {
8367
+ this.#stats.blocksClean++;
8368
+ this.#noteMixed(block, "clean");
8369
+ } else {
8370
+ this.#stats.blocksRecovered++;
8371
+ this.#noteMixed(block, "recovered");
8372
+ }
8373
+ this.#stats.packetsRecovered += recovered.length;
8374
+ return recovered;
8375
+ }
8376
+ /**
8377
+ * Retires every block, and every SS_ID the session remembers, that the
8378
+ * newest SS_ID has moved past the retention. An unsettled block retired
8379
+ * here is a failure: more of its sources were lost than its repair could
8380
+ * restore, or its repair never arrived.
8381
+ */
8382
+ #retireBehindHorizon() {
8383
+ const decoder = this.#decoder;
8384
+ const newest = this.#newest;
8385
+ if (!decoder || newest === void 0) return;
8386
+ try {
8387
+ decoder.cleanup_by_ss_start(newest);
8388
+ } catch {
8389
+ }
8390
+ for (const [start, block] of this.#blocks) {
8391
+ if (!this.#behindHorizon(start)) continue;
8392
+ this.#settle(start);
8393
+ this.#stats.blocksFailed++;
8394
+ this.#stats.packetsLost += block.ssbLength - block.received;
8395
+ this.#noteMixed(block, "failed");
8396
+ }
8397
+ const prunedAt = this.#prunedAt;
8398
+ if (prunedAt !== void 0 && serial32Distance(prunedAt, newest) < this.sourceSymbols) return;
8399
+ this.#prunedAt = newest;
8400
+ for (const ssId of this.#have.keys()) {
8401
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId);
8402
+ }
8403
+ for (const start of this.#settled) {
8404
+ if (this.#behindHorizon(start)) this.#settled.delete(start);
8405
+ }
8406
+ }
8407
+ };
8408
+ function requirePositiveInteger(value, path) {
8409
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
8410
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`);
8411
+ }
8412
+ return value;
8413
+ }
8414
+ function requireNumber(value, path) {
8415
+ if (typeof value !== "number") {
8416
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`);
8417
+ }
8418
+ return value;
8419
+ }
8420
+
8421
+ // src/catalog-network-source.ts
8422
+ function normalizePort(value) {
8423
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
8424
+ return Number.isInteger(n) && n > 0 && n <= 65535 ? n : void 0;
8425
+ }
8426
+ function catalogAmtNetworkSource(networkSource) {
8427
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8428
+ for (const raw of entries) {
8429
+ if (!raw || typeof raw !== "object") continue;
8430
+ const ns = raw;
8431
+ if (ns.type !== "amt") continue;
8432
+ if (ns.discovery === "driad") continue;
8433
+ const relay = typeof ns.relay === "string" ? ns.relay.trim() : "";
8434
+ if (!relay) continue;
8435
+ return { relay, port: normalizePort(ns.port) ?? DEFAULT_AMT_RELAY_PORT };
8436
+ }
8437
+ return void 0;
8438
+ }
8439
+ function intIn(value, min, max) {
8440
+ return Number.isInteger(value) && value >= min && value <= max;
8441
+ }
8442
+ function catalogAtsc3NetworkSource(networkSource) {
8443
+ const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
8444
+ for (const raw of entries) {
8445
+ if (!raw || typeof raw !== "object") continue;
8446
+ const ns = raw;
8447
+ if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
8448
+ const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
8449
+ return {
8450
+ frequency: ns.frequency,
8451
+ ...intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {},
8452
+ ...intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {},
8453
+ ...slsUri ? { slsUri } : {}
8454
+ };
8455
+ }
8456
+ return void 0;
8457
+ }
8458
+
7775
8459
  // src/mmtp-to-cmaf.ts
7776
8460
  function box(type, ...children2) {
7777
8461
  let size = 8;
@@ -7814,8 +8498,8 @@ function u32(v) {
7814
8498
  }
7815
8499
  var KEYFRAME_FLAGS = 33554432;
7816
8500
  var DELTA_FLAGS = 16842752;
7817
- var UINT32_MAX = 4294967295;
7818
- var MAX_TRACK_ID = UINT32_MAX - 1;
8501
+ var UINT32_MAX2 = 4294967295;
8502
+ var MAX_TRACK_ID = UINT32_MAX2 - 1;
7819
8503
  var INT32_MIN = -2147483648;
7820
8504
  var INT32_MAX = 2147483647;
7821
8505
  function assertTrackId(trackId, label) {
@@ -7824,8 +8508,8 @@ function assertTrackId(trackId, label) {
7824
8508
  }
7825
8509
  }
7826
8510
  function assertTimescale(timescale, label) {
7827
- if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX) {
7828
- throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX}, got ${timescale}`);
8511
+ if (!Number.isInteger(timescale) || timescale <= 0 || timescale > UINT32_MAX2) {
8512
+ throw new RangeError(`${label} must be an integer in 1..${UINT32_MAX2}, got ${timescale}`);
7829
8513
  }
7830
8514
  }
7831
8515
  function assertCompositionTimeOffsets(samples) {
@@ -8871,7 +9555,7 @@ var SOURCE_AUTH_OBJECT_ENTRY_LENGTH = 52;
8871
9555
  var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
8872
9556
  var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
8873
9557
  var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
8874
- var SOURCE_AUTH_SCOPE_LENGTH2 = 32;
9558
+ var SOURCE_AUTH_SCOPE_LENGTH = 32;
8875
9559
  var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
8876
9560
  function requireBytes(name, value, length) {
8877
9561
  if (value.byteLength !== length) {
@@ -8948,7 +9632,7 @@ function sourceAuthSignaturePreimage(authScope, groupId, objectCount, root) {
8948
9632
  throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
8949
9633
  }
8950
9634
  requireU64("groupId", groupId);
8951
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH2);
9635
+ requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
8952
9636
  requireBytes("root", root, 32);
8953
9637
  const preimage = new Uint8Array(100);
8954
9638
  const view2 = new DataView(preimage.buffer);
@@ -8999,6 +9683,20 @@ function decodeSourceAuthManifestFrame(frame) {
8999
9683
  }
9000
9684
 
9001
9685
  // ../mmt-manifest-verify/dist/verifier.js
9686
+ function manifestKeyFor(keys, epoch, kid) {
9687
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length)
9688
+ return void 0;
9689
+ if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
9690
+ return void 0;
9691
+ let signer;
9692
+ for (const key of keys) {
9693
+ if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
9694
+ signer = key;
9695
+ }
9696
+ if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
9697
+ return void 0;
9698
+ return signer.publicKey;
9699
+ }
9002
9700
  function manifestBindingId(trackName, sourceSymbolFormat) {
9003
9701
  return JSON.stringify([trackName, sourceSymbolFormat]);
9004
9702
  }
@@ -9075,11 +9773,12 @@ var ManifestVerifier = class {
9075
9773
  }
9076
9774
  if (context.authScope.byteLength !== 32)
9077
9775
  throw new Error("manifest authScope must be 32 bytes");
9078
- if (context.publicKey.byteLength !== 32)
9079
- throw new Error("manifest publicKey must be 32 bytes");
9080
- for (const key of context.acceptedPublicKeys ?? []) {
9081
- if (key.byteLength !== 32)
9082
- throw new Error("manifest acceptedPublicKeys must contain 32-byte keys");
9776
+ for (const key of context.keys) {
9777
+ if (key.publicKey.byteLength !== 32)
9778
+ throw new Error("manifest keys must carry 32-byte public keys");
9779
+ }
9780
+ if (manifestKeyFor(context.keys, context.keyEpoch) === void 0) {
9781
+ throw new Error(`manifest keys hold no key set signing keyEpoch ${context.keyEpoch}`);
9083
9782
  }
9084
9783
  for (const [name, value] of Object.entries({
9085
9784
  broadcastNamespaceId: context.broadcastNamespaceId,
@@ -9324,7 +10023,7 @@ var ManifestVerifier = class {
9324
10023
  }
9325
10024
  }
9326
10025
  #verifyAcceptedSignature(track, message, signature) {
9327
- const keys = track.context.acceptedPublicKeys ?? [track.context.publicKey];
10026
+ const keys = [manifestKeyFor(track.context.keys, track.context.keyEpoch)];
9328
10027
  const pending = [];
9329
10028
  let hadSynchronousError = false;
9330
10029
  for (const key of keys) {
@@ -9459,59 +10158,140 @@ var ManifestVerifier = class {
9459
10158
  }
9460
10159
  };
9461
10160
 
9462
- // src/manifest-auth-plan.ts
9463
- function createManifestAuthPlan(catalog, options) {
9464
- const resolved = resolveMulticastAuthCatalog(catalog, options.playerMode);
9465
- if (!resolved || resolved.mode === "off") return void 0;
9466
- const verifier = new ManifestVerifier({
9467
- manifestAuth: {
9468
- mode: resolved.mode,
9469
- onMissingManifest: options.onMissingManifest ?? (resolved.mode === "enforce" ? "stall" : "fallback-shadow")
9470
- },
9471
- verifySignature: options.verifySignature,
9472
- ...options.onFailure === void 0 ? {} : { onFailure: options.onFailure }
9473
- });
9474
- const byManifestTrack = /* @__PURE__ */ new Map();
9475
- const bindings = resolved.tracks.map((binding) => {
9476
- const bindingId = manifestBindingId(binding.mediaTrack, binding.sourceSymbolFormat);
9477
- const planned = {
9478
- bindingId,
9479
- mediaTrack: binding.mediaTrack,
9480
- manifestTrack: binding.manifestTrack,
9481
- sourceSymbolFormat: binding.sourceSymbolFormat
9482
- };
9483
- verifier.registerTrack({
9484
- ...options.contextFor(binding, resolved),
9485
- bindingId,
9486
- trackName: binding.mediaTrack,
9487
- sourceSymbolFormat: binding.sourceSymbolFormat,
9488
- authScope: binding.authScope,
9489
- publicKey: resolved.acceptedPublicKeys[0],
9490
- acceptedPublicKeys: resolved.acceptedPublicKeys
10161
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
10162
+ var BCPV2_HEADER_LENGTH = 68;
10163
+ var BCPV2_SIGNATURE_LENGTH = 64;
10164
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
10165
+ var text = new TextEncoder();
10166
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
10167
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
10168
+
10169
+ // src/multicast-auth-catalog.ts
10170
+ var RAW_ED25519_KEY_LENGTH = 32;
10171
+ var DEFAULT_MAX_AUTH_DELAY_MS = 200;
10172
+ var DEFAULT_MANIFEST_TIMER_MS = 20;
10173
+ var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
10174
+ function encodeBase64Url(bytes) {
10175
+ let output = "";
10176
+ for (let i = 0; i < bytes.length; i += 3) {
10177
+ const b0 = bytes[i];
10178
+ const b1 = bytes[i + 1];
10179
+ const b2 = bytes[i + 2];
10180
+ output += BASE64URL_ALPHABET[b0 >> 2];
10181
+ output += BASE64URL_ALPHABET[(b0 & 3) << 4 | (b1 === void 0 ? 0 : b1 >> 4)];
10182
+ if (b1 === void 0) break;
10183
+ output += BASE64URL_ALPHABET[(b1 & 15) << 2 | (b2 === void 0 ? 0 : b2 >> 6)];
10184
+ if (b2 === void 0) break;
10185
+ output += BASE64URL_ALPHABET[b2 & 63];
10186
+ }
10187
+ return output;
10188
+ }
10189
+ var BASE64URL_DECODE_TABLE = (() => {
10190
+ const table = new Int8Array(128).fill(-1);
10191
+ for (let i = 0; i < BASE64URL_ALPHABET.length; i++) {
10192
+ table[BASE64URL_ALPHABET.charCodeAt(i)] = i;
10193
+ }
10194
+ return table;
10195
+ })();
10196
+ function decodeBase64Url(text2) {
10197
+ if (text2.length % 4 === 1) {
10198
+ throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
10199
+ }
10200
+ const bytes = [];
10201
+ let buffer = 0;
10202
+ let bits = 0;
10203
+ for (let i = 0; i < text2.length; i++) {
10204
+ const code = text2.charCodeAt(i);
10205
+ const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
10206
+ if (value === void 0 || value < 0) {
10207
+ throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
10208
+ }
10209
+ buffer = buffer << 6 | value;
10210
+ bits += 6;
10211
+ if (bits >= 8) {
10212
+ bits -= 8;
10213
+ bytes.push(buffer >> bits & 255);
10214
+ }
10215
+ }
10216
+ const decoded = Uint8Array.from(bytes);
10217
+ if (encodeBase64Url(decoded) !== text2) {
10218
+ throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
10219
+ }
10220
+ return decoded;
10221
+ }
10222
+ function decodeEd25519PublicKey(publicKey) {
10223
+ const bytes = decodeBase64Url(publicKey);
10224
+ if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
10225
+ throw new Error(
10226
+ `[multicast-auth-catalog] public key must decode to ${RAW_ED25519_KEY_LENGTH} raw bytes, got ${bytes.byteLength}`
10227
+ );
10228
+ }
10229
+ return bytes;
10230
+ }
10231
+ function resolveMulticastAuthCatalog(catalog, options = {}) {
10232
+ if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
10233
+ throw new Error("[multicast-auth-catalog] catalog must be an object");
10234
+ }
10235
+ const issues = multicastCatalogIssues(catalog, options);
10236
+ const fatal = issues.find((issue) => issue.endpointIndex === void 0);
10237
+ if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
10238
+ const multicast = catalog["multicast"];
10239
+ const auth = multicast?.["auth"];
10240
+ if (auth === void 0) {
10241
+ if (options.requireAuth) {
10242
+ throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
10243
+ }
10244
+ return void 0;
10245
+ }
10246
+ const ignored = new Set(issues.map((issue) => issue.endpointIndex));
10247
+ const endpoints = multicast["endpoints"] ?? [];
10248
+ const flows = [];
10249
+ endpoints.forEach((endpoint, endpointIndex) => {
10250
+ if (ignored.has(endpointIndex)) return;
10251
+ const flowAuth = endpoint["auth"];
10252
+ flows.push({
10253
+ endpointIndex,
10254
+ source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
10255
+ groupAddress: endpoint["groupAddress"],
10256
+ port: endpoint["port"],
10257
+ bandwidth: endpoint["bandwidth"],
10258
+ manifestPort: flowAuth.manifestPort,
10259
+ streamId: flowAuth.streamId,
10260
+ maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
10261
+ manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
10262
+ ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
10263
+ tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
10264
+ name,
10265
+ packetId
10266
+ }))
9491
10267
  });
9492
- byManifestTrack.set(binding.manifestTrack, planned);
9493
- return planned;
9494
10268
  });
9495
- let disposed = false;
9496
10269
  return {
9497
- verifier,
9498
- mode: resolved.mode,
9499
- bindings,
10270
+ keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
10271
+ minEpoch: auth.minEpoch,
10272
+ flows
10273
+ };
10274
+ }
10275
+ function multicastAuthKeyFor(resolved, kid, epoch) {
10276
+ return manifestKeyFor(resolved.keys, epoch, kid);
10277
+ }
10278
+
10279
+ // src/manifest-auth-plan.ts
10280
+ function createManifestAuthPlan(catalog, options = {}) {
10281
+ const resolved = resolveMulticastAuthCatalog(catalog, options);
10282
+ if (!resolved) return void 0;
10283
+ const byManifestTrack = /* @__PURE__ */ new Map();
10284
+ for (const flow of resolved.flows) {
10285
+ if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
10286
+ }
10287
+ return {
10288
+ keys: resolved.keys,
10289
+ minEpoch: resolved.minEpoch,
10290
+ flows: resolved.flows,
9500
10291
  manifestTracks: [...byManifestTrack.keys()],
9501
- bindingIdFor(mediaTrack, sourceSymbolFormat) {
9502
- const bindingId = manifestBindingId(mediaTrack, sourceSymbolFormat);
9503
- return bindings.some((binding) => binding.bindingId === bindingId) ? bindingId : void 0;
9504
- },
9505
- ingestManifestPayload(manifestTrack, payload) {
9506
- const binding = byManifestTrack.get(manifestTrack);
9507
- if (!binding) throw new Error(`unknown manifest subscription track ${manifestTrack}`);
9508
- verifier.ingestManifestFrame(binding.bindingId, payload);
9509
- },
9510
- dispose() {
9511
- if (disposed) return;
9512
- disposed = true;
9513
- verifier.dispose();
9514
- }
10292
+ keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
10293
+ flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
10294
+ flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
9515
10295
  };
9516
10296
  }
9517
10297
  export {
@@ -9519,14 +10299,19 @@ export {
9519
10299
  FEC_INACTIVE_REASONS,
9520
10300
  ManifestVerifier,
9521
10301
  MmtpContainerParser,
10302
+ MmtpFecSession,
9522
10303
  MmtpToCmaf,
10304
+ catalogAmtNetworkSource,
10305
+ catalogAtsc3NetworkSource,
9523
10306
  catalogDeclaresFec,
9524
10307
  catalogFecInterleaveMs,
9525
- computeFecTimeout,
9526
10308
  createManifestAuthPlan,
9527
10309
  createWasmMmtpContainerParser,
9528
10310
  createWebCryptoEd25519Verifier,
9529
10311
  datagramMfuReassembly,
10312
+ fecBlockBudgetMs2 as fecBlockBudgetMs,
10313
+ fecBlockDeadlineMs,
10314
+ isFmp4InitSegment,
9530
10315
  manifestBindingId,
9531
10316
  mmtpFrameReorderWindowFrames,
9532
10317
  reliableMoqMfuReassembly,