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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (205) 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 +1721 -705
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +72 -34
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +309 -204
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +15 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +137 -50
  15. package/dist/catalog-fec-params.js.map +4 -4
  16. package/dist/catalog-network-source.d.ts +24 -2
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +24 -1
  19. package/dist/catalog-network-source.js.map +3 -3
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/delivery-catalog.js +100 -230
  25. package/dist/delivery-catalog.js.map +4 -4
  26. package/dist/fec-manager.d.ts +64 -1
  27. package/dist/fec-manager.d.ts.map +1 -1
  28. package/dist/fec-manager.js +275 -62
  29. package/dist/fec-manager.js.map +4 -4
  30. package/dist/fec-state.d.ts +5 -3
  31. package/dist/fec-state.d.ts.map +1 -1
  32. package/dist/fec-state.js +34 -12
  33. package/dist/fec-state.js.map +4 -4
  34. package/dist/fec-worker-setup.d.ts +2 -0
  35. package/dist/fec-worker-setup.d.ts.map +1 -1
  36. package/dist/fec-worker-setup.js +15 -3
  37. package/dist/fec-worker-setup.js.map +3 -3
  38. package/dist/index.d.ts +5 -5
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +14 -8
  41. package/dist/index.js.map +2 -2
  42. package/dist/iso-block-locator.d.ts +29 -0
  43. package/dist/iso-block-locator.d.ts.map +1 -1
  44. package/dist/iso-block-locator.js +100 -17
  45. package/dist/iso-block-locator.js.map +4 -4
  46. package/dist/manifest-auth-plan.d.ts +26 -25
  47. package/dist/manifest-auth-plan.d.ts.map +1 -1
  48. package/dist/manifest-auth-plan.js +331 -1171
  49. package/dist/manifest-auth-plan.js.map +4 -4
  50. package/dist/mfu-reassembler.js +24 -13
  51. package/dist/mfu-reassembler.js.map +3 -3
  52. package/dist/mmtp-container-parser.d.ts.map +1 -1
  53. package/dist/mmtp-container-parser.js +96 -22
  54. package/dist/mmtp-container-parser.js.map +3 -3
  55. package/dist/mmtp-container-parser.no-modules.js +1138 -325
  56. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  57. package/dist/mmtp-decode-pipeline.js +96 -22
  58. package/dist/mmtp-decode-pipeline.js.map +3 -3
  59. package/dist/mmtp-fec-session.d.ts +159 -0
  60. package/dist/mmtp-fec-session.d.ts.map +1 -0
  61. package/dist/mmtp-fec-session.js +531 -0
  62. package/dist/mmtp-fec-session.js.map +7 -0
  63. package/dist/mmtp-router.d.ts +31 -5
  64. package/dist/mmtp-router.d.ts.map +1 -1
  65. package/dist/mmtp-router.js +168 -22
  66. package/dist/mmtp-router.js.map +3 -3
  67. package/dist/multicast-auth-catalog.d.ts +86 -92
  68. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  69. package/dist/multicast-auth-catalog.js +347 -132
  70. package/dist/multicast-auth-catalog.js.map +4 -4
  71. package/dist/multicast-input.d.ts +28 -6
  72. package/dist/multicast-input.d.ts.map +1 -1
  73. package/dist/multicast-input.js +293 -28
  74. package/dist/multicast-input.js.map +3 -3
  75. package/dist/multicast-manager.d.ts +89 -5
  76. package/dist/multicast-manager.d.ts.map +1 -1
  77. package/dist/multicast-manager.js +730 -356
  78. package/dist/multicast-manager.js.map +4 -4
  79. package/dist/multicast-transport.d.ts +12 -2
  80. package/dist/multicast-transport.d.ts.map +1 -1
  81. package/dist/multicast-transport.js +111 -235
  82. package/dist/multicast-transport.js.map +4 -4
  83. package/dist/multicast-unwrap.js +24 -13
  84. package/dist/multicast-unwrap.js.map +3 -3
  85. package/dist/no-modules.d.ts +4 -1
  86. package/dist/no-modules.d.ts.map +1 -1
  87. package/dist/no-modules.js +1087 -309
  88. package/dist/no-modules.js.map +4 -4
  89. package/dist/phase14-catalog-override.d.ts +1 -1
  90. package/dist/phase14-catalog-override.d.ts.map +1 -1
  91. package/dist/phase14-catalog-override.js +2 -2
  92. package/dist/phase14-catalog-override.js.map +2 -2
  93. package/dist/repair-fetch.d.ts +81 -6
  94. package/dist/repair-fetch.d.ts.map +1 -1
  95. package/dist/repair-fetch.js +159 -31
  96. package/dist/repair-fetch.js.map +3 -3
  97. package/dist/repair-layers.d.ts +2 -0
  98. package/dist/repair-layers.d.ts.map +1 -1
  99. package/dist/repair-layers.js +22 -2
  100. package/dist/repair-layers.js.map +3 -3
  101. package/dist/sample-combiner.d.ts +7 -1
  102. package/dist/sample-combiner.d.ts.map +1 -1
  103. package/dist/sample-combiner.js +14 -2
  104. package/dist/sample-combiner.js.map +2 -2
  105. package/dist/signaling.d.ts +2 -2
  106. package/dist/signaling.d.ts.map +1 -1
  107. package/dist/signaling.js +6 -3
  108. package/dist/signaling.js.map +3 -3
  109. package/dist/source-auth.js +2710 -7
  110. package/dist/source-auth.js.map +4 -4
  111. package/dist/switching-set-alignment.d.ts +1 -1
  112. package/dist/switching-set-alignment.js.map +1 -1
  113. package/dist/timestamp-codec.js +24 -13
  114. package/dist/timestamp-codec.js.map +3 -3
  115. package/dist/wasm-mfu-reassembler.js +3 -0
  116. package/dist/wasm-mfu-reassembler.js.map +3 -3
  117. package/dist/wasm-mmtp-container-parser.js +96 -22
  118. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  119. package/package.json +6 -9
  120. package/schemas/catalog.schema.json +124 -37
  121. package/src/align.ts +52 -21
  122. package/src/carp-catalog.ts +163 -61
  123. package/src/catalog-fec-params.ts +66 -20
  124. package/src/catalog-network-source.ts +45 -2
  125. package/src/catalog-validator.ts +4 -11
  126. package/src/fec-manager.ts +239 -63
  127. package/src/fec-state.ts +14 -12
  128. package/src/fec-worker-setup.ts +20 -2
  129. package/src/index.ts +29 -10
  130. package/src/iso-block-locator.ts +97 -6
  131. package/src/manifest-auth-plan.ts +39 -91
  132. package/src/mmtp-container-parser.ts +75 -7
  133. package/src/mmtp-fec-session.ts +533 -0
  134. package/src/mmtp-router.ts +133 -5
  135. package/src/multicast-auth-catalog.ts +131 -238
  136. package/src/multicast-input.ts +119 -61
  137. package/src/multicast-manager.ts +258 -21
  138. package/src/multicast-transport.ts +17 -3
  139. package/src/no-modules.ts +7 -1
  140. package/src/phase14-catalog-override.ts +3 -3
  141. package/src/repair-fetch.ts +283 -39
  142. package/src/repair-layers.ts +22 -2
  143. package/src/sample-combiner.ts +15 -2
  144. package/src/signaling.ts +2 -2
  145. package/src/switching-set-alignment.ts +1 -1
  146. package/test-vectors/align.json +108 -32
  147. package/test-vectors/bc-provenance-v2.json +1526 -0
  148. package/test-vectors/catalog/README.md +65 -4
  149. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  150. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  151. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  152. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  153. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  154. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  155. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  156. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  157. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  158. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  159. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  160. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  161. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  162. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  163. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  164. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  165. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  166. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  167. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  168. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  169. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  170. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  171. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  172. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  173. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  174. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  175. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  177. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  178. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  179. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  180. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  181. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  182. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  183. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  184. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  185. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  186. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  187. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  188. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  189. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +2 -2
  190. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  191. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  192. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  193. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  194. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  195. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  196. package/test-vectors/catalog/section-codes.json +30 -1
  197. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  198. package/test-vectors/catalog-validation.json +101 -5
  199. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  200. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  201. package/dist/fec-codec.d.ts +0 -32
  202. package/dist/fec-codec.d.ts.map +0 -1
  203. package/dist/fec-codec.js +0 -47
  204. package/dist/fec-codec.js.map +0 -7
  205. package/src/fec-codec.ts +0 -61
@@ -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
+ }