@blockcast/mmt-container 0.4.0 → 0.4.1-main.2e0aa69d293d

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 (220) hide show
  1. package/README.md +37 -21
  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 +5070 -908
  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 +13 -1
  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 +115 -235
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +113 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +464 -66
  33. package/dist/fec-manager.js.map +4 -4
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/held-layer-admission.d.ts +58 -0
  43. package/dist/held-layer-admission.d.ts.map +1 -0
  44. package/dist/held-layer-admission.js +105 -0
  45. package/dist/held-layer-admission.js.map +7 -0
  46. package/dist/index.d.ts +5 -5
  47. package/dist/index.d.ts.map +1 -1
  48. package/dist/index.js +8 -8
  49. package/dist/index.js.map +2 -2
  50. package/dist/iso-block-locator.d.ts +39 -1
  51. package/dist/iso-block-locator.d.ts.map +1 -1
  52. package/dist/iso-block-locator.js +109 -17
  53. package/dist/iso-block-locator.js.map +3 -3
  54. package/dist/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 +3692 -1213
  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 +192 -0
  64. package/dist/mmtp-fec-session.d.ts.map +1 -0
  65. package/dist/mmtp-fec-session.js +640 -0
  66. package/dist/mmtp-fec-session.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +101 -32
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +422 -189
  70. package/dist/mmtp-router.js.map +2 -2
  71. package/dist/multicast-auth-catalog.d.ts +94 -92
  72. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  73. package/dist/multicast-auth-catalog.js +746 -131
  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 +140 -12
  80. package/dist/multicast-manager.d.ts.map +1 -1
  81. package/dist/multicast-manager.js +4104 -605
  82. package/dist/multicast-manager.js.map +4 -4
  83. package/dist/multicast-transport.d.ts +16 -3
  84. package/dist/multicast-transport.d.ts.map +1 -1
  85. package/dist/multicast-transport.js +127 -240
  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 +5 -3
  90. package/dist/no-modules.d.ts.map +1 -1
  91. package/dist/no-modules.js +3643 -1197
  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 +90 -6
  98. package/dist/repair-fetch.d.ts.map +1 -1
  99. package/dist/repair-fetch.js +160 -32
  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/switching-set-alignment.d.ts +1 -1
  114. package/dist/switching-set-alignment.js.map +1 -1
  115. package/dist/timestamp-codec.js +21 -13
  116. package/dist/timestamp-codec.js.map +2 -2
  117. package/dist/wasm-mfu-reassembler.js.map +1 -1
  118. package/dist/wasm-mmtp-container-parser.js +93 -22
  119. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  120. package/package.json +6 -18
  121. package/schemas/catalog.schema.json +133 -38
  122. package/src/align.ts +52 -21
  123. package/src/carp-catalog.ts +188 -68
  124. package/src/catalog-fec-params.ts +28 -3
  125. package/src/catalog-network-source.ts +49 -7
  126. package/src/catalog-validator.ts +4 -11
  127. package/src/cmcd-producer.ts +23 -1
  128. package/src/fec-manager.ts +378 -63
  129. package/src/fec-state.ts +11 -4
  130. package/src/fec-worker-setup.ts +30 -2
  131. package/src/held-layer-admission.ts +161 -0
  132. package/src/index.ts +32 -19
  133. package/src/iso-block-locator.ts +110 -7
  134. package/src/mmtp-container-parser.ts +75 -7
  135. package/src/mmtp-fec-session.ts +606 -0
  136. package/src/mmtp-router.ts +453 -236
  137. package/src/multicast-auth-catalog.ts +196 -231
  138. package/src/multicast-input.ts +148 -124
  139. package/src/multicast-manager.ts +447 -53
  140. package/src/multicast-transport.ts +23 -5
  141. package/src/no-modules.ts +8 -7
  142. package/src/phase14-catalog-override.ts +3 -3
  143. package/src/repair-fetch.ts +306 -42
  144. package/src/repair-layers.ts +22 -2
  145. package/src/sample-combiner.ts +15 -2
  146. package/src/signaling.ts +2 -2
  147. package/src/switching-set-alignment.ts +1 -1
  148. package/test-vectors/align.json +108 -32
  149. package/test-vectors/bc-provenance-v2.json +1526 -0
  150. package/test-vectors/catalog/README.md +71 -4
  151. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  152. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  153. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  154. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  156. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  157. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  158. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  159. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  160. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  161. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  162. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  163. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  164. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  165. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  166. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  167. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  168. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  169. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  170. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  171. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  172. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  174. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  177. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  178. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  179. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  180. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  181. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  182. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  183. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  184. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  185. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  186. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  187. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  188. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  189. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  190. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  191. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  192. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  193. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  194. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  195. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  196. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  197. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  198. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  199. package/test-vectors/catalog/section-codes.json +31 -1
  200. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  201. package/test-vectors/catalog-validation.json +101 -5
  202. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  203. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  204. package/dist/fec-codec.d.ts +0 -32
  205. package/dist/fec-codec.d.ts.map +0 -1
  206. package/dist/fec-codec.js +0 -47
  207. package/dist/fec-codec.js.map +0 -7
  208. package/dist/manifest-auth-plan.d.ts +0 -30
  209. package/dist/manifest-auth-plan.d.ts.map +0 -1
  210. package/dist/manifest-auth-plan.js +0 -1266
  211. package/dist/manifest-auth-plan.js.map +0 -7
  212. package/dist/source-auth.d.ts +0 -2
  213. package/dist/source-auth.d.ts.map +0 -1
  214. package/dist/source-auth.js +0 -1209
  215. package/dist/source-auth.js.map +0 -7
  216. package/src/fec-codec.ts +0 -61
  217. package/src/manifest-auth-plan.ts +0 -107
  218. package/src/source-auth.ts +0 -1
  219. package/test-vectors/generate-source-auth-fixture.mjs +0 -114
  220. package/test-vectors/source-auth-v1.json +0 -61
@@ -0,0 +1,606 @@
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 runs the fec-01 6.3.9 held-layer check (layer 0, B_0 =
22
+ * catalog `fec.repairSymbols`) through the same HeldLayerAdmission FECManager
23
+ * uses. A packet below B_0 at or after the anchor fails the session closed:
24
+ * `stats.failClosed` reports why, and every later repair is refused.
25
+ *
26
+ * Every repair packet that cannot be used is counted under the reason it was
27
+ * refused, and every block ends under exactly one outcome, so a stream whose
28
+ * FEC is doing nothing can be told apart from one with nothing to repair.
29
+ */
30
+
31
+ import {
32
+ isoBlockContains,
33
+ isoBlocksBehindLowerBound,
34
+ parseFecBlockProfile,
35
+ parseMMTPHeader,
36
+ parseMoqRepairFrameWithHeader,
37
+ serial32Add,
38
+ serial32Distance,
39
+ serial32Precedes,
40
+ ssbg1FitsSymbol,
41
+ trimSsbg1SourceSymbol,
42
+ type FecBlockProfile,
43
+ } from '@blockcast/mmt-base'
44
+ import { deriveFecRetentionBlocks, fecBlockBudgetMs } from '@blockcast/mmt-fec'
45
+ import {
46
+ HeldLayerAdmission,
47
+ heldLayerAnchorHorizon,
48
+ type FecFailClosedReason,
49
+ type HeldLayerInput,
50
+ } from './held-layer-admission.js'
51
+
52
+ export type { FecFailClosedReason, HeldLayerInput } from './held-layer-admission.js'
53
+
54
+ /** The mmt-wasm `MmtFecDecoder` members the session drives. */
55
+ export interface MmtpFecSessionDecoder {
56
+ configure_params(k: number, symbolSize: number): void
57
+ add_source(ssId: number, data: Uint8Array, timestamp: number): Uint8Array | null | undefined
58
+ add_repair(
59
+ ssStart: number,
60
+ ssbLength: number,
61
+ rsId: number,
62
+ data: Uint8Array,
63
+ timestamp: number,
64
+ ): Uint8Array | null | undefined
65
+ cleanup_by_ss_start(current: number): Uint32Array
66
+ cleanup_blocks_detailed(ssStarts: Uint32Array): unknown
67
+ free(): void
68
+ }
69
+
70
+ /** `wasm_bindgen.MmtFecDecoder`, or a constructor of the same shape. */
71
+ export type MmtpFecSessionDecoderConstructor = new (
72
+ interleaveDepth: number,
73
+ blockProfile: string,
74
+ algorithm?: string,
75
+ ) => MmtpFecSessionDecoder
76
+
77
+ /** The catalog `fec` fields the session reads. */
78
+ export interface MmtpFecSessionCatalogFec {
79
+ /** `raptorq` (the default when absent) or `reed-solomon`. */
80
+ algorithm?: unknown
81
+ blockProfile?: unknown
82
+ sourceSymbols?: unknown
83
+ /** P_0: layer 0's repair symbols per block, the fec-01 6.3.9 total B_0. */
84
+ repairSymbols?: unknown
85
+ /** Layer 0's repair track; names it for addRepair()'s `repairTrackName`. */
86
+ repairTrack?: unknown
87
+ symbolSize?: unknown
88
+ interleaveDepthMs?: unknown
89
+ reorderToleranceMs?: unknown
90
+ }
91
+
92
+ export interface MmtpFecSessionConfig {
93
+ /** The source track's catalog `fec` block. */
94
+ fec: MmtpFecSessionCatalogFec
95
+ /** Builds the RaptorQ decoder, normally `wasm_bindgen.MmtFecDecoder`. */
96
+ Decoder: MmtpFecSessionDecoderConstructor
97
+ /**
98
+ * The source's repair layers as the catalog resolves them
99
+ * (`TrackFecParams.repairLayers`), for a caller that subscribes more than
100
+ * layer 0. Absent: layer 0 alone, B_0 = `fec.repairSymbols`.
101
+ */
102
+ repairLayers?: readonly HeldLayerInput[]
103
+ /** The layers the caller holds (fec-01 6.3.9). Absent: [0]. */
104
+ heldLayers?: readonly number[]
105
+ }
106
+
107
+ /**
108
+ * The path a symbol arrived on: its MoQT subscription, or the multicast
109
+ * group (native SSM or AMT) carrying the same asset. The caller states it;
110
+ * the session never infers it.
111
+ */
112
+ export type MmtpFecSessionPath = 'moq' | 'multicast'
113
+
114
+ /** A count per path. */
115
+ export interface MmtpFecSessionPathCounts {
116
+ moq: number
117
+ multicast: number
118
+ }
119
+
120
+ /** How the settled blocks that were fed on both paths ended. */
121
+ export interface MmtpFecSessionMixedPathStats {
122
+ clean: number
123
+ recovered: number
124
+ failed: number
125
+ released: number
126
+ }
127
+
128
+ /** How the session's blocks and packets ended so far. */
129
+ export interface MmtpFecSessionStats {
130
+ /** Source symbols fed, counting each SS_ID once. */
131
+ sourceSymbols: number
132
+ /** Repair symbols accepted for decoding. */
133
+ repairSymbols: number
134
+ /** Blocks whose every source arrived. */
135
+ blocksClean: number
136
+ /** Blocks with loss that the decoder completed. */
137
+ blocksRecovered: number
138
+ /** Blocks with loss the decoder could not complete before retiring them. */
139
+ blocksFailed: number
140
+ /** Blocks still unsettled when the session was released. */
141
+ blocksReleased: number
142
+ /** Source packets the session recovered and handed back. */
143
+ packetsRecovered: number
144
+ /** Source packets of failed blocks that never arrived and were not recovered. */
145
+ packetsLost: number
146
+ /**
147
+ * Packets the session could not use, keyed by reason. Two reasons are not
148
+ * loss and belong in no loss tally. `repair:block-settled` counts the
149
+ * repair symbols of a block that had already settled, which on a healthy
150
+ * stream is every repair symbol of a block after the first.
151
+ * `source:decoder-refused` counts source packets the decoder threw on:
152
+ * they were delivered to the parser, only unprotected.
153
+ */
154
+ dropped: Record<string, number>
155
+ /** `sourceSymbols`, by the path each arrived on. */
156
+ sourceSymbolsByPath: MmtpFecSessionPathCounts
157
+ /** `repairSymbols`, by the path each arrived on. */
158
+ repairSymbolsByPath: MmtpFecSessionPathCounts
159
+ /**
160
+ * Blocks whose symbols the session used arrived on both paths -- for
161
+ * instance multicast source symbols and MoQT repair -- by how each ended.
162
+ * Each is also counted under its outcome above. A symbol the session
163
+ * refused, and a repair that arrived after its block was already clean,
164
+ * contributed nothing to its block and do not make it mixed.
165
+ */
166
+ mixedPath: MmtpFecSessionMixedPathStats
167
+ /**
168
+ * fec-01 6.3.9: null until a repair packet at or after the anchor (the
169
+ * earliest block, in SS_Start serial order, whose repair carried
170
+ * RSB_length >= B_0) states an RSB_length below B_0; then why. Terminal:
171
+ * every later repair is refused under `repair:fail-closed` (the packet that
172
+ * failed it is counted there too), and block state stays as it was. Sources
173
+ * are still taken and can still complete a block from repair admitted
174
+ * before the failure.
175
+ */
176
+ failClosed: FecFailClosedReason | null
177
+ }
178
+
179
+ interface BlockState {
180
+ ssbLength: number
181
+ received: number
182
+ /** The paths of the symbols used for this block, as PATH_BITS. */
183
+ paths: number
184
+ /** RS_IDs of the repair symbols the decoder accepted for this block. */
185
+ rsIds: Set<number>
186
+ }
187
+
188
+ const PATH_BITS: Record<MmtpFecSessionPath, number> = { moq: 1, multicast: 2 }
189
+ const MIXED_PATHS = PATH_BITS.moq | PATH_BITS.multicast
190
+
191
+ /**
192
+ * One asset's in-band FEC state. See the file comment.
193
+ */
194
+ export class MmtpFecSession {
195
+ readonly blockProfile: FecBlockProfile
196
+ readonly algorithm: 'raptorq' | 'reed-solomon'
197
+ readonly sourceSymbols: number
198
+ /** P_0 = B_0, the held total every repair packet is checked against. */
199
+ readonly repairSymbols: number
200
+ readonly symbolSize: number
201
+ /** The decoder's retention, in blocks, derived from the catalog budget. */
202
+ readonly retentionBlocks: number
203
+
204
+ #decoder: MmtpFecSessionDecoder | null
205
+ /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
206
+ #blocks = new Map<number, BlockState>()
207
+ /** SS_Starts of settled blocks, so a later repair for one is refused. */
208
+ #settled = new Set<number>()
209
+ /**
210
+ * SS_IDs whose packet the parser has, with the PATH_BITS of the path it was
211
+ * received on, or 0 for one the session recovered.
212
+ */
213
+ #have = new Map<number, number>()
214
+ #newest: number | undefined
215
+ /** The newest SS_ID when the remembered SS_IDs were last pruned. */
216
+ #prunedAt: number | undefined
217
+ #repairPacketId: number | undefined
218
+ #newestSource: number | undefined
219
+ #heldLayers: HeldLayerAdmission
220
+ #anchorHorizon: number
221
+ #stats: MmtpFecSessionStats = {
222
+ sourceSymbols: 0,
223
+ repairSymbols: 0,
224
+ blocksClean: 0,
225
+ blocksRecovered: 0,
226
+ blocksFailed: 0,
227
+ blocksReleased: 0,
228
+ packetsRecovered: 0,
229
+ packetsLost: 0,
230
+ dropped: {},
231
+ sourceSymbolsByPath: { moq: 0, multicast: 0 },
232
+ repairSymbolsByPath: { moq: 0, multicast: 0 },
233
+ mixedPath: { clean: 0, recovered: 0, failed: 0, released: 0 },
234
+ failClosed: null,
235
+ }
236
+
237
+ /**
238
+ * @throws when the catalog block lacks or misstates a field the session
239
+ * needs: the block profile, K, P_0 (`repairSymbols`), T, `interleaveDepthMs` or
240
+ * `reorderToleranceMs`. None is defaulted.
241
+ */
242
+ constructor(config: MmtpFecSessionConfig) {
243
+ const fec = config?.fec
244
+ if (!fec || typeof fec !== 'object') {
245
+ throw new Error('MmtpFecSession: the catalog fec block is required')
246
+ }
247
+ this.blockProfile = parseFecBlockProfile(fec.blockProfile, 'fec.blockProfile')
248
+ if (fec.algorithm !== undefined && fec.algorithm !== 'raptorq' && fec.algorithm !== 'reed-solomon') {
249
+ throw new Error(`MmtpFecSession: fec.algorithm ${JSON.stringify(fec.algorithm)} is not implemented`)
250
+ }
251
+ this.algorithm = fec.algorithm === 'reed-solomon' ? 'reed-solomon' : 'raptorq'
252
+ this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, 'fec.sourceSymbols')
253
+ this.repairSymbols = requirePositiveInteger(fec.repairSymbols, 'fec.repairSymbols')
254
+ this.symbolSize = requirePositiveInteger(fec.symbolSize, 'fec.symbolSize')
255
+ const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, 'fec.interleaveDepthMs')
256
+ const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, 'fec.reorderToleranceMs')
257
+ this.retentionBlocks = deriveFecRetentionBlocks(
258
+ fecBlockBudgetMs(interleaveDepthMs, reorderToleranceMs),
259
+ interleaveDepthMs,
260
+ )
261
+ this.#heldLayers = new HeldLayerAdmission(
262
+ config.repairLayers ?? [
263
+ {
264
+ layer: 0,
265
+ repairTrackName: typeof fec.repairTrack === 'string' ? fec.repairTrack : '',
266
+ rsIdOffset: 0,
267
+ repairSymbols: this.repairSymbols,
268
+ },
269
+ ],
270
+ config.heldLayers,
271
+ )
272
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols)
273
+ if (typeof config.Decoder !== 'function') {
274
+ throw new Error('MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required')
275
+ }
276
+ const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm)
277
+ try {
278
+ decoder.configure_params(this.sourceSymbols, this.symbolSize)
279
+ } catch (error) {
280
+ decoder.free()
281
+ throw error
282
+ }
283
+ this.#decoder = decoder
284
+ }
285
+
286
+ /** True once release() ran. */
287
+ get released(): boolean {
288
+ return this.#decoder === null
289
+ }
290
+
291
+ get stats(): MmtpFecSessionStats {
292
+ return {
293
+ ...this.#stats,
294
+ dropped: { ...this.#stats.dropped },
295
+ sourceSymbolsByPath: { ...this.#stats.sourceSymbolsByPath },
296
+ repairSymbolsByPath: { ...this.#stats.repairSymbolsByPath },
297
+ mixedPath: { ...this.#stats.mixedPath },
298
+ failClosed: this.#stats.failClosed && { ...this.#stats.failClosed },
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Feeds one received source packet: the MMTP packet without its four-byte
304
+ * Source FEC Payload ID, under the SS_ID that ID stated. This is what
305
+ * MmtpContainerParser's onSourceSymbol() hands over. `path` is where it
306
+ * was received; a caller that only subscribes over MoQT can leave it out.
307
+ *
308
+ * @returns the protected packets of this packet's block that it recovered,
309
+ * in SS_ID order, for the caller to feed to its parser with
310
+ * `{skipFecPayloadId: true, recovered: true}`. Usually empty.
311
+ */
312
+ addSource(ssId: number, packet: Uint8Array, path: MmtpFecSessionPath = 'moq'): Uint8Array[] {
313
+ const decoder = this.#decoder
314
+ if (!decoder) return this.#drop('source:released')
315
+ const pathBit = PATH_BITS[path]
316
+ if (!pathBit) return this.#drop('source:unknown-path')
317
+ if (!Number.isInteger(ssId) || ssId < 0 || ssId > 0xffff_ffff) return this.#drop('source:bad-ss-id')
318
+ if (!ssbg1FitsSymbol(packet.byteLength, this.symbolSize)) return this.#drop('source:exceeds-symbol')
319
+ if (this.#have.has(ssId)) return this.#drop('source:duplicate')
320
+ this.#have.set(ssId, pathBit)
321
+ this.#stats.sourceSymbols++
322
+ this.#stats.sourceSymbolsByPath[path]++
323
+ this.#noteNewest(ssId)
324
+ if (this.#newestSource === undefined || serial32Precedes(this.#newestSource, ssId)) this.#newestSource = ssId
325
+
326
+ const start = this.#blockStartOf(ssId)
327
+ const block = start === undefined ? undefined : this.#blocks.get(start)
328
+ if (block) {
329
+ block.received++
330
+ block.paths |= pathBit
331
+ }
332
+
333
+ let output: Uint8Array | null | undefined
334
+ try {
335
+ output = decoder.add_source(ssId, packet, 0)
336
+ } catch {
337
+ // The packet itself reached the parser; only its protection is lost.
338
+ this.#drop('source:decoder-refused')
339
+ output = undefined
340
+ }
341
+ const recovered: Uint8Array[] = []
342
+ if (start !== undefined && block) {
343
+ if (output) {
344
+ recovered.push(...this.#settleDecoded(start, block, output))
345
+ } else if (block.received >= block.ssbLength) {
346
+ this.#settleClean(start)
347
+ }
348
+ }
349
+ this.#retireBehindHorizon()
350
+ return recovered
351
+ }
352
+
353
+ /**
354
+ * Feeds one object of the repair track: a whole MMTP repair packet (ISO/IEC
355
+ * 23008-1 C.5.3). A repair track carries one repair flow, so the first
356
+ * repair packet fixes its packet ID and a packet of any other is refused.
357
+ * `path` is where it was received, as for addSource(). `repairTrackName`
358
+ * is the repair track it was received on, for the 6.3.9 own-track rule; a
359
+ * track the layers do not list is refused as `repair:unlisted-track`.
360
+ *
361
+ * @returns the protected packets this repair symbol recovered, as for
362
+ * addSource().
363
+ */
364
+ addRepair(packet: Uint8Array, path: MmtpFecSessionPath = 'moq', repairTrackName?: string): Uint8Array[] {
365
+ const decoder = this.#decoder
366
+ if (!decoder) return this.#drop('repair:released')
367
+ if (this.#stats.failClosed) return this.#drop('repair:fail-closed')
368
+ const pathBit = PATH_BITS[path]
369
+ if (!pathBit) return this.#drop('repair:unknown-path')
370
+ let header
371
+ try {
372
+ header = parseMMTPHeader(packet)
373
+ } catch {
374
+ return this.#drop('repair:malformed')
375
+ }
376
+ const frame = parseMoqRepairFrameWithHeader(packet, header)
377
+ if (!frame) return this.#drop('repair:malformed')
378
+ if (this.#repairPacketId === undefined) {
379
+ this.#repairPacketId = frame.packetId
380
+ } else if (frame.packetId !== this.#repairPacketId) {
381
+ return this.#drop('repair:foreign-packet-id')
382
+ }
383
+ if (frame.symbolData.byteLength !== this.symbolSize) return this.#drop('repair:symbol-size')
384
+ if (frame.ssbLength > this.sourceSymbols) return this.#drop('repair:ssb-length')
385
+ // fec-01 4.5: a reed-solomon block holds at most 255 symbols. Discarded
386
+ // before any block bookkeeping, so the block state is unchanged.
387
+ if (this.algorithm === 'reed-solomon' && frame.ssbLength + frame.rsbLength > 255) {
388
+ return this.#drop('repair:rs-block-length')
389
+ }
390
+ // fec-01 6.3.9, after the 4.5 discards and the size check, before a block
391
+ // is placed. Without a track name only the anchored rule (b) applies.
392
+ const verdict = this.#heldLayers.admit(
393
+ repairTrackName,
394
+ frame.ssStart,
395
+ frame.rsbLength,
396
+ this.#anchorHorizon,
397
+ this.#newestSource,
398
+ )
399
+ if (verdict === 'discard') return this.#drop('repair:unlisted-track')
400
+ if (verdict !== undefined) {
401
+ this.#stats.failClosed = verdict
402
+ return this.#drop('repair:fail-closed')
403
+ }
404
+
405
+ const start = frame.ssStart
406
+ let block = this.#blocks.get(start)
407
+ if (block && block.ssbLength !== frame.ssbLength) return this.#drop('repair:conflicting-ssb-length')
408
+ // One repair symbol per (SS_Start, RS_ID), whichever path delivers it
409
+ // first: a second copy never reaches the decoder, the counts or the paths.
410
+ if (block?.rsIds.has(frame.rsId)) return this.#drop('repair:duplicate')
411
+ if (!block) {
412
+ if (this.#settled.has(start)) return this.#drop('repair:block-settled')
413
+ if (this.#behindHorizon(start)) return this.#drop('repair:behind-horizon')
414
+ block = { ssbLength: frame.ssbLength, received: 0, paths: 0, rsIds: new Set() }
415
+ this.#countHeld(start, block)
416
+ this.#blocks.set(start, block)
417
+ }
418
+ this.#noteNewest(serial32Add(start, frame.ssbLength - 1))
419
+ if (block.received >= block.ssbLength) {
420
+ this.#settleClean(start)
421
+ this.#retireBehindHorizon()
422
+ return []
423
+ }
424
+
425
+ let output: Uint8Array | null | undefined
426
+ try {
427
+ output = decoder.add_repair(start, frame.ssbLength, frame.rsId, frame.symbolData, 0)
428
+ } catch {
429
+ return this.#drop('repair:decoder-refused')
430
+ }
431
+ block.rsIds.add(frame.rsId)
432
+ this.#stats.repairSymbols++
433
+ this.#stats.repairSymbolsByPath[path]++
434
+ block.paths |= pathBit
435
+ const recovered = output ? this.#settleDecoded(start, block, output) : []
436
+ this.#retireBehindHorizon()
437
+ return recovered
438
+ }
439
+
440
+ /**
441
+ * Frees the decoder and every block. Blocks still unsettled are counted as
442
+ * released, not failed: nothing proved them unrecoverable. Idempotent;
443
+ * returns whether this call released anything.
444
+ */
445
+ release(): boolean {
446
+ const decoder = this.#decoder
447
+ if (!decoder) return false
448
+ this.#decoder = null
449
+ this.#stats.blocksReleased += this.#blocks.size
450
+ for (const block of this.#blocks.values()) this.#noteMixed(block, 'released')
451
+ this.#blocks.clear()
452
+ this.#settled.clear()
453
+ this.#have.clear()
454
+ decoder.free()
455
+ return true
456
+ }
457
+
458
+ #drop(reason: string): Uint8Array[] {
459
+ this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1
460
+ return []
461
+ }
462
+
463
+ #noteNewest(ssId: number): void {
464
+ if (this.#newest === undefined || serial32Precedes(this.#newest, ssId)) this.#newest = ssId
465
+ }
466
+
467
+ #blockStartOf(ssId: number): number | undefined {
468
+ for (const [start, block] of this.#blocks) {
469
+ if (isoBlockContains(start, block.ssbLength, ssId)) return start
470
+ }
471
+ return undefined
472
+ }
473
+
474
+ /** Counts the sources of a new block the parser already has, and their paths. */
475
+ #countHeld(start: number, block: BlockState): void {
476
+ for (let i = 0; i < block.ssbLength; i++) {
477
+ const pathBit = this.#have.get(serial32Add(start, i))
478
+ if (pathBit === undefined) continue
479
+ block.received++
480
+ block.paths |= pathBit
481
+ }
482
+ }
483
+
484
+ #noteMixed(block: BlockState, outcome: keyof MmtpFecSessionMixedPathStats): void {
485
+ if ((block.paths & MIXED_PATHS) === MIXED_PATHS) this.#stats.mixedPath[outcome]++
486
+ }
487
+
488
+ /** The decoder's own rule: more than its retention behind, counted from below. */
489
+ #behindHorizon(start: number): boolean {
490
+ const newest = this.#newest
491
+ if (newest === undefined) return false
492
+ return isoBlocksBehindLowerBound(start, newest, this.sourceSymbols) > this.retentionBlocks
493
+ }
494
+
495
+ #settle(start: number): void {
496
+ this.#blocks.delete(start)
497
+ this.#settled.add(start)
498
+ }
499
+
500
+ #settleClean(start: number): void {
501
+ const block = this.#blocks.get(start)
502
+ if (!block) return
503
+ this.#settle(start)
504
+ this.#stats.blocksClean++
505
+ this.#noteMixed(block, 'clean')
506
+ try {
507
+ this.#decoder?.cleanup_blocks_detailed(Uint32Array.of(start))
508
+ } catch {
509
+ // The decoder retires the block by its own horizon instead.
510
+ }
511
+ }
512
+
513
+ /**
514
+ * The decoder returns a completed block as its K' ssbg_mode1 symbols,
515
+ * concatenated: split by T, trim by each symbol's length field, and hand
516
+ * back the packets the parser does not have yet.
517
+ */
518
+ #settleDecoded(start: number, block: BlockState, output: Uint8Array): Uint8Array[] {
519
+ this.#settle(start)
520
+ if (output.byteLength !== block.ssbLength * this.symbolSize) {
521
+ this.#stats.blocksFailed++
522
+ this.#stats.packetsLost += block.ssbLength - block.received
523
+ this.#noteMixed(block, 'failed')
524
+ this.#drop('block:decoded-length')
525
+ return []
526
+ }
527
+ const recovered: Uint8Array[] = []
528
+ let refused = 0
529
+ for (let i = 0; i < block.ssbLength; i++) {
530
+ const ssId = serial32Add(start, i)
531
+ if (this.#have.has(ssId)) continue
532
+ const symbol = output.subarray(i * this.symbolSize, (i + 1) * this.symbolSize)
533
+ const packet = trimSsbg1SourceSymbol(symbol)
534
+ if (!packet) {
535
+ refused++
536
+ continue
537
+ }
538
+ this.#have.set(ssId, 0)
539
+ recovered.push(packet.slice())
540
+ }
541
+ if (refused > 0) {
542
+ this.#stats.blocksFailed++
543
+ this.#stats.packetsLost += refused
544
+ this.#noteMixed(block, 'failed')
545
+ this.#drop('block:bad-ssbg1-symbol')
546
+ } else if (recovered.length === 0) {
547
+ this.#stats.blocksClean++
548
+ this.#noteMixed(block, 'clean')
549
+ } else {
550
+ this.#stats.blocksRecovered++
551
+ this.#noteMixed(block, 'recovered')
552
+ }
553
+ this.#stats.packetsRecovered += recovered.length
554
+ return recovered
555
+ }
556
+
557
+ /**
558
+ * Retires every block, and every SS_ID the session remembers, that the
559
+ * newest SS_ID has moved past the retention. An unsettled block retired
560
+ * here is a failure: more of its sources were lost than its repair could
561
+ * restore, or its repair never arrived.
562
+ */
563
+ #retireBehindHorizon(): void {
564
+ const decoder = this.#decoder
565
+ const newest = this.#newest
566
+ if (!decoder || newest === undefined) return
567
+ try {
568
+ decoder.cleanup_by_ss_start(newest)
569
+ } catch {
570
+ // Block fate below does not depend on the decoder's own sweep.
571
+ }
572
+ for (const [start, block] of this.#blocks) {
573
+ if (!this.#behindHorizon(start)) continue
574
+ this.#settle(start)
575
+ this.#stats.blocksFailed++
576
+ this.#stats.packetsLost += block.ssbLength - block.received
577
+ this.#noteMixed(block, 'failed')
578
+ }
579
+ // What is remembered only needs pruning once a block's worth of SS_IDs
580
+ // has gone by, not on every packet.
581
+ const prunedAt = this.#prunedAt
582
+ // #newest only moves forward, so the distance is how far it has moved.
583
+ if (prunedAt !== undefined && serial32Distance(prunedAt, newest) < this.sourceSymbols) return
584
+ this.#prunedAt = newest
585
+ for (const ssId of this.#have.keys()) {
586
+ if (this.#behindHorizon(ssId)) this.#have.delete(ssId)
587
+ }
588
+ for (const start of this.#settled) {
589
+ if (this.#behindHorizon(start)) this.#settled.delete(start)
590
+ }
591
+ }
592
+ }
593
+
594
+ function requirePositiveInteger(value: unknown, path: string): number {
595
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
596
+ throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`)
597
+ }
598
+ return value
599
+ }
600
+
601
+ function requireNumber(value: unknown, path: string): number {
602
+ if (typeof value !== 'number') {
603
+ throw new Error(`MmtpFecSession: ${path} is required (got ${String(value)}); it is never defaulted`)
604
+ }
605
+ return value
606
+ }