@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
@@ -1034,8 +1034,23 @@ function isFmp4Box(data: Uint8Array): boolean {
1034
1034
  interface TimingStreamState {
1035
1035
  packetId: number
1036
1036
  resolver: IsoBmffTimingResolver
1037
+ /** FI=0/FI=1 heads that arrived before their sample's FT=1, oldest first. */
1038
+ awaitingTiming: AwaitingTimingHead[]
1037
1039
  }
1038
1040
 
1041
+ /** A head refused for missing timing, kept to be fed again when its FT=1 lands. */
1042
+ interface AwaitingTimingHead {
1043
+ packet: Uint8Array
1044
+ options: ParseHeaderOptions | undefined
1045
+ parsed: ParsedMmtpPacket
1046
+ mpuSequenceNumber: number
1047
+ movieFragmentSequenceNumber: number
1048
+ sampleNumber: number
1049
+ arrivedAt: number
1050
+ }
1051
+
1052
+ const MAX_AWAITING_TIMING_HEADS = 8
1053
+
1039
1054
  // ── MmtpContainerParser ─────────────────────────────────────────────
1040
1055
 
1041
1056
  export class MmtpContainerParser {
@@ -1098,6 +1113,7 @@ export class MmtpContainerParser {
1098
1113
  * reordering into the parser. */
1099
1114
  #reliableMoqStartupGate = new Map<string, number>()
1100
1115
  #disposed = false
1116
+ #replayingAwaitingTiming = false
1101
1117
  #fedObjects = 0
1102
1118
  #reassemblerFragmentsFed = 0
1103
1119
  #reassemblerDataUnitsReturned = 0
@@ -1446,7 +1462,10 @@ export class MmtpContainerParser {
1446
1462
  * a single failure bucket. Returns null so call sites stay `return this.#drop(...)`.
1447
1463
  */
1448
1464
  #drop(reason: MmtpFeedDropReason): null {
1449
- this.#countOutcome(`drop:${reason}`)
1465
+ // A replayed head was counted when it was fed; what befalls it now is a
1466
+ // side effect of the FT=1 that released it.
1467
+ if (this.#replayingAwaitingTiming) this.#countDeferredOutcome(reason)
1468
+ else this.#countOutcome(`drop:${reason}`)
1450
1469
  return null
1451
1470
  }
1452
1471
 
@@ -1471,6 +1490,12 @@ export class MmtpContainerParser {
1471
1490
  for (const combiner of this.#sampleCombiners.values()) {
1472
1491
  combiner.cleanupTimeouts(timeoutMs)
1473
1492
  }
1493
+ const now = Date.now()
1494
+ for (const { awaitingTiming } of this.#timingStreams.values()) {
1495
+ while (awaitingTiming.length > 0 && now - awaitingTiming[0]!.arrivedAt > timeoutMs) {
1496
+ awaitingTiming.shift()
1497
+ }
1498
+ }
1474
1499
  }
1475
1500
 
1476
1501
  /**
@@ -1587,7 +1612,7 @@ export class MmtpContainerParser {
1587
1612
  // Fire onSourceSymbol BEFORE MFU extraction so the consumer-side FEC
1588
1613
  // pipeline (e.g. FecWorkerClient.feedSource) starts as early as possible.
1589
1614
  // Source-only: parseHeader already gates fecPayloadId on !isRepair.
1590
- if (info.fecPayloadId !== null && this.#sourceSymbolCb) {
1615
+ if (info.fecPayloadId !== null && this.#sourceSymbolCb && !this.#replayingAwaitingTiming) {
1591
1616
  // Strip the 4-byte fec_payload_id trailer per ISO 23008-1 §C.5.2.
1592
1617
  // Symbol-size zero-padding is the consumer's responsibility — FEC
1593
1618
  // symbol size is a FEC-config concern, not a parser concern.
@@ -1654,6 +1679,7 @@ export class MmtpContainerParser {
1654
1679
  }
1655
1680
  return this.#drop('fragment-timing-refused')
1656
1681
  }
1682
+ this.#replayAwaitingTiming(streamKey, resolver)
1657
1683
  return {
1658
1684
  kind: 'fragment',
1659
1685
  packet: info,
@@ -1679,7 +1705,18 @@ export class MmtpContainerParser {
1679
1705
  mfuDuHeader.movieFragmentSequenceNumber,
1680
1706
  mfuDuHeader.sampleNumber,
1681
1707
  )
1682
- if (!headTiming) return this.#drop('mfu-sample-timing-missing')
1708
+ if (!headTiming) {
1709
+ this.#awaitTiming(streamKey, {
1710
+ packet,
1711
+ options,
1712
+ parsed,
1713
+ mpuSequenceNumber: mpu.mpuSequenceNumber,
1714
+ movieFragmentSequenceNumber: mfuDuHeader.movieFragmentSequenceNumber,
1715
+ sampleNumber: mfuDuHeader.sampleNumber,
1716
+ arrivedAt: Date.now(),
1717
+ })
1718
+ return this.#drop('mfu-sample-timing-missing')
1719
+ }
1683
1720
  // A data unit's authored base offset is its position within the sample
1684
1721
  // (moqcast #37): 0 for a whole-sample DU, nonzero for one subsample DU
1685
1722
  // among siblings. Sizes below are therefore relative to that base, not
@@ -1781,11 +1818,12 @@ export class MmtpContainerParser {
1781
1818
  // a sample this stream declared, so it must be dropped outright -- letting
1782
1819
  // it buffer would occupy a combiner slot and could evict a legitimate
1783
1820
  // partitioned sample waiting on a sibling.
1784
- if (!resolver.sampleTiming(
1821
+ const assembledTiming = resolver.sampleTiming(
1785
1822
  assembled.mpuSequenceNumber,
1786
1823
  movieFragmentSequenceNumber,
1787
1824
  sampleNumber,
1788
- )) return this.#drop('assembled-timing-missing')
1825
+ )
1826
+ if (!assembledTiming) return this.#drop('assembled-timing-missing')
1789
1827
  if (assembled.mpuSequenceNumber !== mpu.mpuSequenceNumber)
1790
1828
  return this.#drop('assembled-mpu-mismatch')
1791
1829
 
@@ -1795,7 +1833,7 @@ export class MmtpContainerParser {
1795
1833
  // unpartitioned sample passes straight through with no buffering.
1796
1834
  let combined: CombinedSample | null
1797
1835
  try {
1798
- combined = this.#sampleCombinerFor(streamKey).addMfu(assembled)
1836
+ combined = this.#sampleCombinerFor(streamKey).addMfu(assembled, assembledTiming.size)
1799
1837
  } catch (error) {
1800
1838
  if (!(error instanceof SampleCombineError)) throw error
1801
1839
  console.warn(
@@ -2150,10 +2188,40 @@ export class MmtpContainerParser {
2150
2188
  if (existing) return existing.resolver
2151
2189
  if (!create) return null
2152
2190
  const resolver = new IsoBmffTimingResolver(this.#maxPendingTimingSamples)
2153
- this.#timingStreams.set(streamKey, { packetId, resolver })
2191
+ this.#timingStreams.set(streamKey, { packetId, resolver, awaitingTiming: [] })
2154
2192
  return resolver
2155
2193
  }
2156
2194
 
2195
+ #awaitTiming(streamKey: string, head: AwaitingTimingHead): void {
2196
+ const awaitingTiming = this.#timingStreams.get(streamKey)?.awaitingTiming
2197
+ if (!awaitingTiming) return
2198
+ awaitingTiming.push(head)
2199
+ if (awaitingTiming.length > MAX_AWAITING_TIMING_HEADS) awaitingTiming.shift()
2200
+ }
2201
+
2202
+ /**
2203
+ * Feed again the heads whose timing the FT=1 just admitted declares. That
2204
+ * FT=1 can be an FEC recovery landing after its sample's FI=1, and neither
2205
+ * FEC path routes a source symbol that already arrived a second time.
2206
+ */
2207
+ #replayAwaitingTiming(streamKey: string, resolver: IsoBmffTimingResolver): void {
2208
+ const state = this.#timingStreams.get(streamKey)
2209
+ if (!state || state.awaitingTiming.length === 0) return
2210
+ const ready = state.awaitingTiming.filter(head => resolver.sampleTiming(
2211
+ head.mpuSequenceNumber,
2212
+ head.movieFragmentSequenceNumber,
2213
+ head.sampleNumber,
2214
+ ))
2215
+ if (ready.length === 0) return
2216
+ state.awaitingTiming = state.awaitingTiming.filter(head => !ready.includes(head))
2217
+ this.#replayingAwaitingTiming = true
2218
+ try {
2219
+ for (const head of ready) this.#feed(head.packet, head.options, head.parsed)
2220
+ } finally {
2221
+ this.#replayingAwaitingTiming = false
2222
+ }
2223
+ }
2224
+
2157
2225
  #dropTimingStream(streamKey: string): void {
2158
2226
  const state = this.#timingStreams.get(streamKey)
2159
2227
  if (!state) return
@@ -0,0 +1,533 @@
1
+ /**
2
+ * In-band AL-FEC for one MMTP asset received over a MoQT subscription: the
3
+ * asset's source packets on its own track, its repair packets on the repair
4
+ * track the catalog names (`fec.repairTrack`). The same asset's packets can also
5
+ * arrive on the multicast group (native SSM or AMT) carrying it: the caller
6
+ * states each symbol's path, and a block fed on both -- multicast source
7
+ * symbols repaired from the MoQT repair track, say -- is counted as mixed-path
8
+ * under `stats.mixedPath`, never inferred. Built for a player that owns
9
+ * its own MMTP parser and wants nothing else of the multicast stack
10
+ * (MulticastManager, MmtpRouter, FECManager): the Shaka MSF MMTP packaging.
11
+ *
12
+ * The session is clock-free, like the reliable-MoQ reassembly policy it sits
13
+ * beside. A block is settled only by wire evidence: clean once every source
14
+ * the repair's SSB_length states has arrived, recovered when the decoder
15
+ * completes it, failed once the newest SS_ID has moved it past the decoder's
16
+ * retention. No timer and no arrival time decides a block's fate, so a repair
17
+ * that is merely late on its own subscription is never counted as a loss.
18
+ * The retention is derived from the catalog's `fecBlockBudgetMs`, and a
19
+ * catalog missing either input throws rather than defaulting.
20
+ *
21
+ * Every repair packet that cannot be used is counted under the reason it was
22
+ * refused, and every block ends under exactly one outcome, so a stream whose
23
+ * FEC is doing nothing can be told apart from one with nothing to repair.
24
+ */
25
+
26
+ import {
27
+ isoBlockContains,
28
+ isoBlocksBehindLowerBound,
29
+ parseFecBlockProfile,
30
+ parseMMTPHeader,
31
+ parseMoqRepairFrameWithHeader,
32
+ serial32Add,
33
+ serial32Distance,
34
+ serial32Precedes,
35
+ ssbg1FitsSymbol,
36
+ trimSsbg1SourceSymbol,
37
+ type FecBlockProfile,
38
+ } from '@blockcast/mmt-base'
39
+ import { deriveFecRetentionBlocks, fecBlockBudgetMs } from '@blockcast/mmt-fec'
40
+
41
+ /** The mmt-wasm `MmtFecDecoder` members the session drives. */
42
+ export interface MmtpFecSessionDecoder {
43
+ configure_params(k: number, symbolSize: number): void
44
+ add_source(ssId: number, data: Uint8Array, timestamp: number): Uint8Array | null | undefined
45
+ add_repair(
46
+ ssStart: number,
47
+ ssbLength: number,
48
+ rsId: number,
49
+ data: Uint8Array,
50
+ timestamp: number,
51
+ ): Uint8Array | null | undefined
52
+ cleanup_by_ss_start(current: number): Uint32Array
53
+ cleanup_blocks_detailed(ssStarts: Uint32Array): unknown
54
+ free(): void
55
+ }
56
+
57
+ /** `wasm_bindgen.MmtFecDecoder`, or a constructor of the same shape. */
58
+ export type MmtpFecSessionDecoderConstructor = new (
59
+ interleaveDepth: number,
60
+ blockProfile: string,
61
+ algorithm?: string,
62
+ ) => MmtpFecSessionDecoder
63
+
64
+ /** The catalog `fec` fields the session reads. */
65
+ export interface MmtpFecSessionCatalogFec {
66
+ /** `raptorq` (the default when absent) or `reed-solomon`. */
67
+ algorithm?: unknown
68
+ blockProfile?: unknown
69
+ sourceSymbols?: unknown
70
+ symbolSize?: unknown
71
+ interleaveDepthMs?: unknown
72
+ reorderToleranceMs?: unknown
73
+ }
74
+
75
+ export interface MmtpFecSessionConfig {
76
+ /** The source track's catalog `fec` block. */
77
+ fec: MmtpFecSessionCatalogFec
78
+ /** Builds the RaptorQ decoder, normally `wasm_bindgen.MmtFecDecoder`. */
79
+ Decoder: MmtpFecSessionDecoderConstructor
80
+ }
81
+
82
+ /**
83
+ * The path a symbol arrived on: its MoQT subscription, or the multicast
84
+ * group (native SSM or AMT) carrying the same asset. The caller states it;
85
+ * the session never infers it.
86
+ */
87
+ export type MmtpFecSessionPath = 'moq' | 'multicast'
88
+
89
+ /** A count per path. */
90
+ export interface MmtpFecSessionPathCounts {
91
+ moq: number
92
+ multicast: number
93
+ }
94
+
95
+ /** How the settled blocks that were fed on both paths ended. */
96
+ export interface MmtpFecSessionMixedPathStats {
97
+ clean: number
98
+ recovered: number
99
+ failed: number
100
+ released: number
101
+ }
102
+
103
+ /** How the session's blocks and packets ended so far. */
104
+ export interface MmtpFecSessionStats {
105
+ /** Source symbols fed, counting each SS_ID once. */
106
+ sourceSymbols: number
107
+ /** Repair symbols accepted for decoding. */
108
+ repairSymbols: number
109
+ /** Blocks whose every source arrived. */
110
+ blocksClean: number
111
+ /** Blocks with loss that the decoder completed. */
112
+ blocksRecovered: number
113
+ /** Blocks with loss the decoder could not complete before retiring them. */
114
+ blocksFailed: number
115
+ /** Blocks still unsettled when the session was released. */
116
+ blocksReleased: number
117
+ /** Source packets the session recovered and handed back. */
118
+ packetsRecovered: number
119
+ /** Source packets of failed blocks that never arrived and were not recovered. */
120
+ packetsLost: number
121
+ /**
122
+ * Packets the session could not use, keyed by reason. Two reasons are not
123
+ * loss and belong in no loss tally. `repair:block-settled` counts the
124
+ * repair symbols of a block that had already settled, which on a healthy
125
+ * stream is every repair symbol of a block after the first.
126
+ * `source:decoder-refused` counts source packets the decoder threw on:
127
+ * they were delivered to the parser, only unprotected.
128
+ */
129
+ dropped: Record<string, number>
130
+ /** `sourceSymbols`, by the path each arrived on. */
131
+ sourceSymbolsByPath: MmtpFecSessionPathCounts
132
+ /** `repairSymbols`, by the path each arrived on. */
133
+ repairSymbolsByPath: MmtpFecSessionPathCounts
134
+ /**
135
+ * Blocks whose symbols the session used arrived on both paths -- for
136
+ * instance multicast source symbols and MoQT repair -- by how each ended.
137
+ * Each is also counted under its outcome above. A symbol the session
138
+ * refused, and a repair that arrived after its block was already clean,
139
+ * contributed nothing to its block and do not make it mixed.
140
+ */
141
+ mixedPath: MmtpFecSessionMixedPathStats
142
+ }
143
+
144
+ interface BlockState {
145
+ ssbLength: number
146
+ received: number
147
+ /** The paths of the symbols used for this block, as PATH_BITS. */
148
+ paths: number
149
+ /** RS_IDs of the repair symbols the decoder accepted for this block. */
150
+ rsIds: Set<number>
151
+ }
152
+
153
+ const PATH_BITS: Record<MmtpFecSessionPath, number> = { moq: 1, multicast: 2 }
154
+ const MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast
155
+
156
+ /**
157
+ * One asset's in-band FEC state. See the file comment.
158
+ */
159
+ export class MmtpFecSession {
160
+ readonly blockProfile: FecBlockProfile
161
+ readonly algorithm: 'raptorq' | 'reed-solomon'
162
+ readonly sourceSymbols: number
163
+ readonly symbolSize: number
164
+ /** The decoder's retention, in blocks, derived from the catalog budget. */
165
+ readonly retentionBlocks: number
166
+
167
+ #decoder: MmtpFecSessionDecoder | null
168
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
169
+ #blocks = new Map<number, BlockState>()
170
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
171
+ #settled = new Set<number>()
172
+ /**
173
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
174
+ * received on, or 0 for one the session recovered.
175
+ */
176
+ #have = new Map<number, number>()
177
+ #newest: number | undefined
178
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
179
+ #prunedAt: number | undefined
180
+ #repairPacketId: number | undefined
181
+ #stats: MmtpFecSessionStats = {
182
+ sourceSymbols: 0,
183
+ repairSymbols: 0,
184
+ blocksClean: 0,
185
+ blocksRecovered: 0,
186
+ blocksFailed: 0,
187
+ blocksReleased: 0,
188
+ packetsRecovered: 0,
189
+ packetsLost: 0,
190
+ dropped: {},
191
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
192
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
193
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
194
+ }
195
+
196
+ /**
197
+ * @throws when the catalog block lacks or misstates a field the session
198
+ * needs: the block profile, K, T, `interleaveDepthMs` or
199
+ * `reorderToleranceMs`. None is defaulted.
200
+ */
201
+ constructor(config: MmtpFecSessionConfig) {
202
+ const fec = config?.fec
203
+ if (!fec || typeof fec !== 'object') {
204
+ throw new Error('MmtpFecSession: the catalog fec block is required')
205
+ }
206
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, 'fec.blockProfile')
207
+ if (fec.algorithm !== undefined && fec.algorithm !== 'raptorq' && fec.algorithm !== 'reed-solomon') {
208
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`)
209
+ }
210
+ this.algorithm = fec.algorithm === 'reed-solomon' ? 'reed-solomon' : 'raptorq'
211
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, 'fec.sourceSymbols')
212
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, 'fec.symbolSize')
213
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, 'fec.interleaveDepthMs')
214
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, 'fec.reorderToleranceMs')
215
+ this.retentionBlocks = deriveFecRetentionBlocks(
216
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
217
+ interleaveDepthMs,
218
+ )
219
+ if (typeof config.Decoder !== 'function') {
220
+ throw new Error('MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required')
221
+ }
222
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm)
223
+ try {
224
+ decoder.configure_params(this.sourceSymbols, this.symbolSize)
225
+ } catch (error) {
226
+ decoder.free()
227
+ throw error
228
+ }
229
+ this.#decoder = decoder
230
+ }
231
+
232
+ /** True once release() ran. */
233
+ get released(): boolean {
234
+ return this.#decoder === null
235
+ }
236
+
237
+ get stats(): MmtpFecSessionStats {
238
+ return {
239
+ ...this.#stats,
240
+ dropped: { ...this.#stats.dropped },
241
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
242
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
243
+ mixedPath: { ...this.#stats.mixedPath },
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Feeds one received source packet: the MMTP packet without its four-byte
249
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
250
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
251
+ * was received; a caller that only subscribes over MoQT can leave it out.
252
+ *
253
+ * @returns the protected packets of this packet's block that it recovered,
254
+ * in SS_ID order, for the caller to feed to its parser with
255
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
256
+ */
257
+ addSource(ssId: number, packet: Uint8Array, path: MmtpFecSessionPath = 'moq'): Uint8Array[] {
258
+ const decoder = this.#decoder
259
+ if (!decoder) return this.#drop('source:released')
260
+ const pathBit = PATH_BITS[path]
261
+ if (!pathBit) return this.#drop('source:unknown-path')
262
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 0xffff_ffff) return this.#drop('source:bad-ss-id')
263
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop('source:exceeds-symbol')
264
+ if (this.#have.has(ssId)) return this.#drop('source:duplicate')
265
+ this.#have.set(ssId, pathBit)
266
+ this.#stats.sourceSymbols++
267
+ this.#stats.sourceSymbolsByPath[path]++
268
+ this.#noteNewest(ssId)
269
+
270
+ const start = this.#blockStartOf(ssId)
271
+ const block = start === undefined ? undefined : this.#blocks.get(start)
272
+ if (block) {
273
+ block.received++
274
+ block.paths |= pathBit
275
+ }
276
+
277
+ let output: Uint8Array | null | undefined
278
+ try {
279
+ output = decoder.add_source(ssId, packet, 0)
280
+ } catch {
281
+ // The packet itself reached the parser; only its protection is lost.
282
+ this.#drop('source:decoder-refused')
283
+ output = undefined
284
+ }
285
+ const recovered: Uint8Array[] = []
286
+ if (start !== undefined && block) {
287
+ if (output) {
288
+ recovered.push(...this.#settleDecoded(start, block, output))
289
+ } else if (block.received >= block.ssbLength) {
290
+ this.#settleClean(start)
291
+ }
292
+ }
293
+ this.#retireBehindHorizon()
294
+ return recovered
295
+ }
296
+
297
+ /**
298
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
299
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
300
+ * repair packet fixes its packet ID and a packet of any other is refused.
301
+ * `path` is where it was received, as for addSource().
302
+ *
303
+ * @returns the protected packets this repair symbol recovered, as for
304
+ * addSource().
305
+ */
306
+ addRepair(packet: Uint8Array, path: MmtpFecSessionPath = 'moq'): Uint8Array[] {
307
+ const decoder = this.#decoder
308
+ if (!decoder) return this.#drop('repair:released')
309
+ const pathBit = PATH_BITS[path]
310
+ if (!pathBit) return this.#drop('repair:unknown-path')
311
+ let header
312
+ try {
313
+ header = parseMMTPHeader(packet)
314
+ } catch {
315
+ return this.#drop('repair:malformed')
316
+ }
317
+ const frame = parseMoqRepairFrameWithHeader(packet, header)
318
+ if (!frame) return this.#drop('repair:malformed')
319
+ if (this.#repairPacketId === undefined) {
320
+ this.#repairPacketId = frame.packetId
321
+ } else if (frame.packetId !== this.#repairPacketId) {
322
+ return this.#drop('repair:foreign-packet-id')
323
+ }
324
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop('repair:symbol-size')
325
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop('repair:ssb-length')
326
+ // fec-01 4.5: a reed-solomon block holds at most 255 symbols. Discarded
327
+ // before any block bookkeeping, so the block state is unchanged.
328
+ if (this.algorithm === 'reed-solomon' && frame.ssbLength + frame.rsbLength > 255) {
329
+ return this.#drop('repair:rs-block-length')
330
+ }
331
+
332
+ const start = frame.ssStart
333
+ let block = this.#blocks.get(start)
334
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop('repair:conflicting-ssb-length')
335
+ // One repair symbol per (SS_Start, RS_ID), whichever path delivers it
336
+ // first: a second copy never reaches the decoder, the counts or the paths.
337
+ if (block?.rsIds.has(frame.rsId)) return this.#drop('repair:duplicate')
338
+ if (!block) {
339
+ if (this.#settled.has(start)) return this.#drop('repair:block-settled')
340
+ if (this.#behindHorizon(start)) return this.#drop('repair:behind-horizon')
341
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: new Set() }
342
+ this.#countHeld(start, block)
343
+ this.#blocks.set(start, block)
344
+ }
345
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1))
346
+ if (block.received >= block.ssbLength) {
347
+ this.#settleClean(start)
348
+ this.#retireBehindHorizon()
349
+ return []
350
+ }
351
+
352
+ let output: Uint8Array | null | undefined
353
+ try {
354
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0)
355
+ } catch {
356
+ return this.#drop('repair:decoder-refused')
357
+ }
358
+ block.rsIds.add(frame.rsId)
359
+ this.#stats.repairSymbols++
360
+ this.#stats.repairSymbolsByPath[path]++
361
+ block.paths |= pathBit
362
+ const recovered = output ? this.#settleDecoded(start, block, output) : []
363
+ this.#retireBehindHorizon()
364
+ return recovered
365
+ }
366
+
367
+ /**
368
+ * Frees the decoder and every block. Blocks still unsettled are counted as
369
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
370
+ * returns whether this call released anything.
371
+ */
372
+ release(): boolean {
373
+ const decoder = this.#decoder
374
+ if (!decoder) return false
375
+ this.#decoder = null
376
+ this.#stats.blocksReleased += this.#blocks.size
377
+ for (const block of this.#blocks.values()) this.#noteMixed(block, 'released')
378
+ this.#blocks.clear()
379
+ this.#settled.clear()
380
+ this.#have.clear()
381
+ decoder.free()
382
+ return true
383
+ }
384
+
385
+ #drop(reason: string): Uint8Array[] {
386
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1
387
+ return []
388
+ }
389
+
390
+ #noteNewest(ssId: number): void {
391
+ if (this.#newest === undefined || serial32Precedes(this.#newest, ssId)) this.#newest = ssId
392
+ }
393
+
394
+ #blockStartOf(ssId: number): number | undefined {
395
+ for (const [start, block] of this.#blocks) {
396
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start
397
+ }
398
+ return undefined
399
+ }
400
+
401
+ /** Counts the sources of a new block the parser already has, and their paths. */
402
+ #countHeld(start: number, block: BlockState): void {
403
+ for (let i = 0; i < block.ssbLength; i++) {
404
+ const pathBit = this.#have.get(serial32Add(start, i))
405
+ if (pathBit === undefined) continue
406
+ block.received++
407
+ block.paths |= pathBit
408
+ }
409
+ }
410
+
411
+ #noteMixed(block: BlockState, outcome: keyof MmtpFecSessionMixedPathStats): void {
412
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++
413
+ }
414
+
415
+ /** The decoder's own rule: more than its retention behind, counted from below. */
416
+ #behindHorizon(start: number): boolean {
417
+ const newest = this.#newest
418
+ if (newest === undefined) return false
419
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks
420
+ }
421
+
422
+ #settle(start: number): void {
423
+ this.#blocks.delete(start)
424
+ this.#settled.add(start)
425
+ }
426
+
427
+ #settleClean(start: number): void {
428
+ const block = this.#blocks.get(start)
429
+ if (!block) return
430
+ this.#settle(start)
431
+ this.#stats.blocksClean++
432
+ this.#noteMixed(block, 'clean')
433
+ try {
434
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start))
435
+ } catch {
436
+ // The decoder retires the block by its own horizon instead.
437
+ }
438
+ }
439
+
440
+ /**
441
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
442
+ * concatenated: split by T, trim by each symbol's length field, and hand
443
+ * back the packets the parser does not have yet.
444
+ */
445
+ #settleDecoded(start: number, block: BlockState, output: Uint8Array): Uint8Array[] {
446
+ this.#settle(start)
447
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
448
+ this.#stats.blocksFailed++
449
+ this.#stats.packetsLost += block.ssbLength - block.received
450
+ this.#noteMixed(block, 'failed')
451
+ this.#drop('block:decoded-length')
452
+ return []
453
+ }
454
+ const recovered: Uint8Array[] = []
455
+ let refused = 0
456
+ for (let i = 0; i < block.ssbLength; i++) {
457
+ const ssId = serial32Add(start, i)
458
+ if (this.#have.has(ssId)) continue
459
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize)
460
+ const packet = trimSsbg1SourceSymbol(symbol)
461
+ if (!packet) {
462
+ refused++
463
+ continue
464
+ }
465
+ this.#have.set(ssId, 0)
466
+ recovered.push(packet.slice())
467
+ }
468
+ if (refused > 0) {
469
+ this.#stats.blocksFailed++
470
+ this.#stats.packetsLost += refused
471
+ this.#noteMixed(block, 'failed')
472
+ this.#drop('block:bad-ssbg1-symbol')
473
+ } else if (recovered.length === 0) {
474
+ this.#stats.blocksClean++
475
+ this.#noteMixed(block, 'clean')
476
+ } else {
477
+ this.#stats.blocksRecovered++
478
+ this.#noteMixed(block, 'recovered')
479
+ }
480
+ this.#stats.packetsRecovered += recovered.length
481
+ return recovered
482
+ }
483
+
484
+ /**
485
+ * Retires every block, and every SS_ID the session remembers, that the
486
+ * newest SS_ID has moved past the retention. An unsettled block retired
487
+ * here is a failure: more of its sources were lost than its repair could
488
+ * restore, or its repair never arrived.
489
+ */
490
+ #retireBehindHorizon(): void {
491
+ const decoder = this.#decoder
492
+ const newest = this.#newest
493
+ if (!decoder || newest === undefined) return
494
+ try {
495
+ decoder.cleanup_by_ss_start(newest)
496
+ } catch {
497
+ // Block fate below does not depend on the decoder's own sweep.
498
+ }
499
+ for (const [start, block] of this.#blocks) {
500
+ if (!this.#behindHorizon(start)) continue
501
+ this.#settle(start)
502
+ this.#stats.blocksFailed++
503
+ this.#stats.packetsLost += block.ssbLength - block.received
504
+ this.#noteMixed(block, 'failed')
505
+ }
506
+ // What is remembered only needs pruning once a block's worth of SS_IDs
507
+ // has gone by, not on every packet.
508
+ const prunedAt = this.#prunedAt
509
+ // #newest only moves forward, so the distance is how far it has moved.
510
+ if (prunedAt !== undefined && serial32Distance(prunedAt, newest) < this.sourceSymbols) return
511
+ this.#prunedAt = newest
512
+ for (const ssId of this.#have.keys()) {
513
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId)
514
+ }
515
+ for (const start of this.#settled) {
516
+ if (this.#behindHorizon(start)) this.#settled.delete(start)
517
+ }
518
+ }
519
+ }
520
+
521
+ function requirePositiveInteger(value: unknown, path: string): number {
522
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
523
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`)
524
+ }
525
+ return value
526
+ }
527
+
528
+ function requireNumber(value: unknown, path: string): number {
529
+ if (typeof value !== 'number') {
530
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`)
531
+ }
532
+ return value
533
+ }